user2734550
user2734550

Reputation: 962

Reduce data size returned from an API through GraphQL?

We use one endpoint that returns massive size of data and sometime the page would take 5-10s to load. We don't have control over the backend api. Is there a way to reduce the size that's going to be downloaded from the API? We have already enabled compression. I heard GraphQL could make a data schema before query it. Would GraphQL help in this case?

Upvotes: 1

Views: 2111

Answers (1)

Daniel Rearden
Daniel Rearden

Reputation: 84687

GraphQL could help, assuming:

  • Your existing API request is doing a lot of overfetching, and you don't actually need a good chunk of the data being returned
  • You have the resources to set up an additional GraphQL server to serve as a proxy to the REST endpoint
  • The REST endpoint response can be modeled as a GraphQL schema (this might be difficult or outright impossible if the object keys in the returned JSON are subject to change)
  • The response from the REST endpoint can be cached
  • The extra latency introduced by adding the GraphQL server as an intermediary is sufficiently offset by the reduction in response size

Your GraphQL server would have to expose a query that would make a request to the REST endpoint and then cache it server-side. The cached response would be used upon subsequent queries to the server, until it expires or is invalidated. Caching the response is key, otherwise simply proxying the request through the GraphQL server will simply make all your queries slower since getting the data from the REST endpoint to the server will itself take approximately the same amount of time as your request does currently.

GraphQL can then be used to cut down the size of your response in two ways:

  • By not requesting certain fields that aren't needed by your client (or omitting these fields from your schema altogether)
  • By introducing pagination. If the reason for the bloated size of your response is the sheer number of records returned, you can add pagination to your schema and return smaller chunks of the total list of records one at a time.

Note: the latter can be a significant optimization, but can also be tricky if your cache is frequently invalidated

Upvotes: 2

Related Questions