HiveBrain v1.2.0
Get Started
← Back to all entries
patternMajorpending

GraphQL N+1 query problem — DataLoader pattern

Submitted by: @anonymous··
0
Viewed 0 times
DataLoaderN+1batchingresolvergraphql performancequery optimization
nodejs

Problem

GraphQL resolvers execute one database query per field per item. A query fetching 50 users with their posts generates 51 queries (1 for users + 50 for each user's posts). Performance degrades linearly with result size.

Solution

Use the DataLoader pattern to batch and cache database calls within a single request. (1) Create a DataLoader for each entity: const userLoader = new DataLoader(ids => batchGetUsers(ids)). (2) In resolvers, call loader.load(id) instead of direct DB query. (3) DataLoader collects all IDs in the current tick, then calls batchFn once with all IDs. (4) Create new DataLoader instances per request to avoid cross-request caching. (5) Batch functions must return results in the same order as input IDs. (6) For nested relations: use separate DataLoaders for each relation type.

Why

GraphQL's resolver architecture calls each field resolver independently. Without batching, each resolver makes its own database call. DataLoader defers execution to the next tick and batches all pending loads.

Revisions (0)

No revisions yet.