GraphQLgraphqldataloadern-plus-oneperformanceproduction-ready

DataLoader for N+1 Prevention

DataLoader pattern for batching and caching database queries in GraphQL resolvers, preventing the N+1 query problem.


title: "DataLoader for N+1 Prevention" description: "DataLoader pattern for batching and caching database queries in GraphQL resolvers, preventing the N+1 query problem." category: "GraphQL" language: "typescript" tags: ["graphql", "dataloader", "n-plus-one", "performance", "production-ready"] createdAt: "2025-03-10" updatedAt: "2025-03-30"

Overview

DataLoader solves the N+1 query problem in GraphQL by batching individual field resolver database calls into single bulk queries. Each request gets fresh loader instances that deduplicate and cache within that request's lifecycle.

Code

// Instead of N individual queries:
// SELECT * FROM users WHERE id = '1'
// SELECT * FROM users WHERE id = '2'
// ...
 
// DataLoader batches into one:
// SELECT * FROM users WHERE id = ANY(['1', '2', ...])

Notes

  • Create new DataLoader instances per request to prevent data leaking between users
  • Results must be returned in the same order as the input keys array
  • Return null for missing items (not undefined) to maintain array alignment
  • maxBatchSize prevents excessively large IN queries from overwhelming the database
  • For one-to-many relationships, the batch function returns arrays grouped by parent ID
  • DataLoader caches within a single request; for cross-request caching, add Redis on top