Improving GraphQL Performance

graphql

Providing Easy Access To Data

GraphQL is a data query language and a fantastic middleware layer that reduces round trips from the browser to get data and seamlessly hides the complexity of getting data from disparate data sources including REST apis, sql, nosql and graph databases as well as any other type of data storage.

Performance Can Be A Problem

Those are the upsides. The downside is that because it is so easy to get data from various sources it is possible to write GraphQL queries that generate hundreds or thousands of calls for underlying data.

DataLoaders Save The Day

GraphQL provides a mechanism to deal with all of these requests in a really elegant way. DataLoaders offer a way to load data for some key, which can be any string or id or object.  The DataLoader de-duplicates requests for identical information but they can do even better than that.  DataLoaders are invoked to load data for a single key (via the load function) or for multiple keys at a time (via the loadMany function).  Regardless of how the DataLoader is invoked, it queues up requests for data and only makes the request after all requests have been queued or after some arbitrary limit is hit.  This means that the requests for data can be consolidated into a single batch request for data.  Instead of asking for each piece of data by id, you can ask for all pieces of data for a set of ids.

These two properties of data loaders, de-duplication and batching, make them the perfect tool for improving GraphQL query performance.

Real World Example

Using DataLoaders, I recently was able to cut a heavy GraphQL query from taking 45 minutes and making hundreds of REST and thousands of sql database calls down to 4 seconds, making 20 REST and 20 sql database calls for data.

Conclusions

When you are looking to improve your GraphQL query performance, start by looking at the underlying calls for data.  Using DataLoaders you can de-duplicate and consolidate those calls for data and dramatically reduce query time.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s