7 Optimizing Data Fetching

 

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.

7.1  Caching and Batching

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.

7.1.1  The batch loading function

7.1.2  Defining and Using a DataLoader Instance

7.1.3  Adding Loader for Approaches

7.2  Using DataLoader with Custom IDs for Caching

7.2.1  The neadFeaturedList field

7.2.2  The search field

7.3  Using DataLoader with MongoDB

7.4  Single Resource Fields

7.5  The viewer Field

7.5.1  The needList Field

7.5.2  Dynamic Types

7.6  Summary

sitemap