This chapter covers:
- Caching and batching data-fetch operations
- Using the DataLoader library with primary keys and custom IDs
- Using GraphQL’s union type and field arguments
- Reading data from MongoDB
Now that we have a GraphQL service with a multi-model schema, we can look at one of GraphQL’s most famous problems: the N+1 queries problem. We’ve ended the previous chapter with a GraphQL query that fetches data from 3 database tables:
Listing 7.1. The N+1 query example
{ needFeaturedList { // ... author { // ... } approachList { // ... author { // ... } } } }
Because the GraphQL runtime traverses the tree field by field and resolves each field on its own as it does, this simple GraphQL query resulted in a lot more SQL statements than necessary.
To analyze a solution to this problem, let’s go back to the simpler query in listing 6.25:
Listing 7.2. The needFeaturedList
query
{ needFeaturedList { content author { id email name createdAt } } }
If you remember, this query was issuing four SQL SELECT statements to the database for the seed data, which is an example of the N+1 problem (N being 3 Needs records). We’ve seen how to use database join views to make it execute only one SQL statement but that solution is not ideal. It’s not easy to maintain or scale.