Detect Scaling Issues When Loading Data In a GraphQL API

Jacob Paris
InstructorJacob Paris
Share this video with your friends

Social Share Links

Send Tweet
Published 3 years ago
Updated 3 years ago

It's easy enough to use GraphQL to query an array of posts from a database. But if you try to include the author of each post, you can run into scaling issues where the server makes an additional request for each and every post.

Using the console, we'll show how to identify when this is happening

And by the end of this series, you'll know how to use data loaders to prevent it.

Instructor: [0:00] This is an Apollo GraphQL application with a Postgres database that contains a table of posts and a table of users. We have a post query that returns an array of posts, and a users query that returns an array of users.

[0:14] Let's query the posts. We can see every item in the database is returned, and the users query does the same for the users. What we're looking to accomplish here is to extend the post query to also return the user who wrote the post.

[0:29] We can start by adding a new field to the schema named author, with a return type of user. Then if we scroll down to the resolver section for the post type, and add an author field, we'll return a list of users where the ID matches the post's author ID.

[0:47] Since we only want one, grab the first one from the array. Let's try that request out with the author, ID, and the name. Let's see. We get all the author information for each post, so it's working here.

[1:02] It's a little hard to tell what the database is actually doing here. We'll add some console logs to track how many times we're interacting with the database. Under posts, we'll do console log, select all from posts.

[1:15] Under author, we'll do console log, select all from users, where ID = post.author ID. If we run our request again, we can see we're only making one database request to fetch the list of posts.

[1:36] We're also making individual requests for the author on each post including several requests for the same author. At the end of this series, we'll show how to use DataLoaders for caching and batching database operations so that we can serve all of these results with only one database request.