GraphQL DataLoader Pattern
The DataLoader library pattern: batch individual load() calls into one request, dedupe keys per tick, and cache results per request. Contract, options, and pitfalls.
Overview
DataLoader is a library that coalesces individual load() calls made during one event-loop tick into a single batched request. Facebook built it to solve the N+1 query problem in GraphQL servers: every call to load(key) in a tick is collected, deduplicated, and handed to a batch function that fetches all keys at once. Results live in a cache on the loader instance for as long as that instance lives.
The idea isn’t GraphQL-specific: it works anywhere you batch async lookups. It’s the same strategy as the batched resolver pattern, but this page is about the library itself: its contract, cache semantics, and options. For a runnable Apollo Server implementation with query counts, see the DataLoader batching recipe.
When to Use
- GraphQL resolvers that fetch related entities per parent item (
post.author,order.items) - Any async lookup where individual calls can be batched: database, REST, gRPC, in-memory stores
- Fields that may request the same key several times in one operation; the per-tick dedup wins for free
- Gateway or BFF layers aggregating data from several backend services
Skip it for single-item lookups (N=1), synchronous data access (it’s async-only), long-lived caching (the cache is per request), and real-time subscriptions where batching adds latency.
Solution
1. Basic DataLoader Setup
The batch function is the whole contract: it receives the collected keys and must return a same-length array in the same order.
import DataLoader from 'dataloader';
type User = { id: string; name: string; email: string };
interface Db {
query<T>(sql: string, params: unknown[]): Promise<T[]>;
}
async function batchUsers(ids: readonly string[], db: Db): Promise<(User | Error)[]> {
const rows = await db.query<User>('SELECT * FROM users WHERE id = ANY($1)', [ids]);
const map = new Map(rows.map((r) => [r.id, r]));
// Position matters: index i answers key ids[i]
return ids.map((id) => map.get(id) ?? new Error(`User ${id} not found`));
}
const userLoader = new DataLoader<string, User>((ids) => batchUsers(ids, db));
2. Using in GraphQL Resolvers
const resolvers = {
Query: {
posts: (_parent: unknown, _args: unknown, ctx: Context) => ctx.db.post.findMany({ take: 20 }),
},
Post: {
author: (post: Post, _args: unknown, ctx: Context) => ctx.loaders.userLoader.load(post.authorId),
comments: (post: Post, _args: unknown, ctx: Context) =>
ctx.loaders.commentLoader.loadMany(post.commentIds),
},
Comment: {
author: (comment: Comment, _args: unknown, ctx: Context) =>
ctx.loaders.userLoader.load(comment.authorId),
},
};
When a query asks for 20 posts with their authors plus comments with their authors, DataLoader coalesces it into one batchUsers call with the unique author IDs and one batchComments call: 2 queries instead of 40+.
3. Per-Request Context
Loaders must be fresh per GraphQL operation. Sharing an instance across requests leaks cached entities between users:
import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
interface Context {
db: Db;
loaders: ReturnType<typeof createLoaders>;
userId: string | null;
}
function createLoaders(db: Db) {
return {
userLoader: new DataLoader<string, User>((ids) => batchUsers(ids, db)),
commentLoader: new DataLoader<string, Comment>((ids) => batchComments(ids, db)),
};
}
const server = new ApolloServer<Context>({ typeDefs, resolvers });
startStandaloneServer(server, {
context: async ({ req }) => ({
db,
loaders: createLoaders(db),
userId: parseAuth(req.headers.authorization),
}),
listen: { port: 4000 },
});
Apollo runs the context factory once per request, which is what isolates each request’s cache.
4. Priming the Cache
When a parent resolver already fetched the entity, prime the loader so nested load(id) calls resolve instantly:
const resolvers = {
Query: {
user: async (_parent: unknown, { id }: { id: string }, ctx: Context) => {
const user = await ctx.db.user.findById(id);
ctx.loaders.userLoader.prime(id, user);
return user;
},
},
};
5. Clearing Cache After Mutations
A mutation that writes leaves the request cache stale. Evict or re-prime inside the mutation resolver:
const resolvers = {
Mutation: {
updateUser: async (_parent: unknown, { id, input }: { id: string; input: UserInput }, ctx: Context) => {
const user = await ctx.db.user.update(id, input);
ctx.loaders.userLoader.clear(id); // or .prime(id, user) to store the fresh value
return user;
},
},
};
How the Contract Works
- Batching: every
load()in one tick queues its key; whenprocess.nextTickfires, the whole queue goes to the batch function in one call. - Deduplication: repeated keys in the queue are requested once; all callers share the result.
- Order contract: the batch function must return an array with exactly one slot per input key, in input order. DataLoader pairs results to keys by position, so a missing slot silently misaligns the whole batch.
- Per-key errors: return an
Errorat a position to reject only thatload(); throwing in the batch function rejects every pending load in that batch. - Per-request cache: results live in a
Mapon the loader instance, which is why instances are per request. loadMany(keys)returnsPromise<(Value | Error)[]>aligned with the input keys, the standard way to resolve a field that needs several entities.
Options worth knowing
cacheMap: swap the internalMapfor a custom store (e.g., one with TTL or serialization).batchScheduleFn: redefine when the batch dispatches. Default isprocess.nextTick; asetTimeout(fn, 10)gives a wider coalescing window at a latency cost.maxBatchSize: caps keys per dispatch when the backend limitsINclause size.cacheKeyFn: derives the cache key for composite or object keys. Without it, two equal objects are different references and cache-miss every time.cache: false: disables the instance cache for data that changes within a request (stock prices, counters).
Variants
DataLoader with Prisma
const userLoader = new DataLoader<string, User>(async (ids) => {
const users = await prisma.user.findMany({ where: { id: { in: [...ids] } } });
const map = new Map(users.map((u) => [u.id, u]));
// Explicit null for missing keys; undefined would still work but is less clear
return ids.map((id) => map.get(id) ?? null);
});
DataLoader with Redis Pipeline
const sessionLoader = new DataLoader<string, Session>(async (sessionIds) => {
const pipeline = redis.pipeline();
sessionIds.forEach((id) => pipeline.get(`session:${id}`));
const results = await pipeline.exec();
return results.map(([err, value]) => {
if (err) return new Error(err.message);
return value ? (JSON.parse(value) as Session) : null;
});
});
Custom Cache Key Function
For composite keys, both the batch function and cacheKeyFn must agree on serialization:
const permissionLoader = new DataLoader<{ userId: string; resource: string }, Permission>(
async (keys) => {
const permissions = await db.permission.findMany({
where: { OR: keys.map((k) => ({ userId: k.userId, resource: k.resource })) },
});
const map = new Map(permissions.map((p) => [`${p.userId}:${p.resource}`, p]));
return keys.map((k) => map.get(`${k.userId}:${k.resource}`) ?? null);
},
{ cacheKeyFn: (key) => `${key.userId}:${key.resource}` },
);
Best Practices
- One loader instance per request, built in the context factory, never shared across requests
- Keep the batch function pure: keys in, positionally aligned values out, no side effects
- Use
prime()when a parent resolver already fetched the entity clear(id)or re-prime inside mutation resolvers- Name loaders after the entity (
userLoader, notdataLoader) - For a deeper look at batching as a general strategy, see the batched resolver pattern
Common Mistakes
- Sharing a DataLoader across requests: the per-request cache leaks data between users and serves stale reads.
- Throwing in the batch function: rejects the whole batch. Return
Errorobjects per position instead. - Returning fewer results than keys: position-based pairing misaligns every result after the gap.
- Forgetting
clear()after mutations: updated entities keep serving their old cached version for the rest of the request. - Using DataLoader as a long-lived cache: it’s request-scoped; for cross-request caching use Redis with explicit invalidation.
- Object keys without
cacheKeyFn:{ userId: '1' }twice are two different references, so the cache misses every time. - Detect N+1 before and after: if you can’t see the queries being batched, measure first with N+1 detection.
See Also
- graphql/dataloader on GitHub: reference implementation, full options list, and caching semantics
- Batched resolver pattern: batching as a general strategy, with and without the library
- DataLoader batching recipe: runnable Apollo Server implementation
- N+1 query detection: measure the problem before and after
Frequently Asked Questions
Is DataLoader only for GraphQL?
No. It's a general-purpose batching library. Anything with individual async lookups that can be grouped works: REST backends, microservices, message queues, in-memory stores. GraphQL is the most common use because nested resolvers independently request related data.
How does DataLoader decide when to batch?
It collects every load() call queued during the current event-loop tick and dispatches them together when process.nextTick runs, and batchScheduleFn lets you replace that timing: a small setTimeout widens the window and batches more keys at the price of added latency.
What's the difference between this pattern and the DataLoader recipe?
This page covers the pattern: the contract, cache semantics, and options. The DataLoader batching recipe is the runnable implementation: Apollo Server wiring, per-request context, and a demo that counts queries before and after.
What happens when a key isn't found?
Pick a convention and stick to it: null at that index for a non-error "not found", or new Error(...) if that caller's load() should reject. Never return undefined silently; make the choice explicit so callers know what to expect.
Should I use DataLoader with federation?
Federation's query planner already batches field resolution across subgraphs. Inside one subgraph (resolvers hitting the same database), DataLoader still helps. See the federation guide for where the boundary sits.
Can I use DataLoader outside JavaScript?
Yes. The concept is language-agnostic: aiodataloader for Python, dataloader for Go, java-dataloader for JVM. Only the reference implementation lives in the JavaScript ecosystem.
Related Resources
GraphQL Batched Resolver Pattern
Resolve nested GraphQL fields in a single batched request to eliminate N+1 queries and reduce database load.
RecipeBatch and Cache Database Queries with GraphQL DataLoader
Implement DataLoader batching in GraphQL resolvers with Apollo Server: collapse N+1 database queries into single batched calls cached per request
RecipeDetect and Fix N+1 Queries in GraphQL Resolvers
Identify N+1 query problems in GraphQL resolvers using logging, DataLoader, and query analysis tools before they hit production
GuideComplete Guide to GraphQL Caching
Cache GraphQL responses at every layer: CDN, gateway, DataLoader, persisted queries, and client-side. Covers cache keys, invalidation, HTTP caching directives, and Apollo Client cache.
PatternGraphQL Connection Pagination Pattern
Implement Relay-style cursor-based pagination with edges, nodes, and pageInfo for stable GraphQL list queries.
PatternGraphQL Mutation Validation: Centralized Input Checks
Centralize GraphQL mutation validation with reusable rules, custom scalars, and structured errors. Includes TypeScript examples and best practices.