Batch 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
When a GraphQL query resolves nested relationships, like fetching the author of each post in a list, a naive resolver issues one database query per item. That’s the N+1 problem: one query for the list plus N queries for the related data. DataLoader fixes it by collecting .load(id) calls made during a single event-loop tick and dispatching them as one batched query. If you suspect N+1 in a running API but haven’t confirmed it, detect it first, then come back for the fix. This recipe is the runnable implementation; for the concept and when it fits, see the DataLoader pattern.
When to Use This
- Resolvers that fetch related data by foreign key (
post.author,user.posts,order.items) - Any GraphQL schema with nested type relationships
- APIs where N+1 queries don’t just slow responses but exhaust database connections
- Fields that load the same entity several times in one request; the per-request cache dedupes them
- Skip it when resolvers already join everything in one query, or for single-item lookups that never batch; DataLoader adds indirection a
JOINdoesn’t need
Prerequisites
- Node.js 18+ with a GraphQL server (Apollo Server, GraphQL Yoga)
- A database client that supports
WHERE id IN (...)queries
Solution
1. Install DataLoader
npm install dataloader
2. Create Batch Loader Functions
// loaders.ts
import DataLoader from 'dataloader';
type User = { id: string; name: string; email: string };
type Post = { id: string; title: string; authorId: string };
interface UsersTable {
findMany(opts: { where: { id: { in: string[] } } }): Promise<User[]>;
}
interface PostsTable {
findMany(opts: { where: { authorId: { in: string[] } } }): Promise<Post[]>;
}
export function createUserLoader(db: { users: UsersTable }) {
return new DataLoader<string, User>(async (userIds: readonly string[]) => {
const users = await db.users.findMany({
where: { id: { in: [...userIds] } },
});
const userMap = new Map(users.map((u) => [u.id, u]));
return userIds.map((id) => userMap.get(id) ?? new Error(`User ${id} not found`));
});
}
export function createPostLoader(db: { posts: PostsTable }) {
return new DataLoader<string, Post[]>(async (authorIds: readonly string[]) => {
const posts = await db.posts.findMany({
where: { authorId: { in: [...authorIds] } },
});
return authorIds.map((authorId) =>
posts.filter((p) => p.authorId === authorId)
);
});
}
Two rules inside every batch function: the returned array must have the same length as the input keys, and each position must match its key. Returning an Error for a key makes that key fail without sinking the rest of the batch.
3. Inject Loaders Per Request
Create a fresh DataLoader instance per request so the cache only lives for the duration of that request:
// context.ts
import DataLoader from 'dataloader';
import { createUserLoader, createPostLoader } from './loaders';
export type Context = {
db: Db;
user: User | null;
loaders: {
user: DataLoader<string, User>;
postsByAuthor: DataLoader<string, Post[]>;
};
};
export function createContext(db: Db): Context {
return {
db,
user: null, // attach auth/session here if your resolvers need it
loaders: {
user: createUserLoader(db),
postsByAuthor: createPostLoader(db),
},
};
}
4. Use Loaders in Resolvers
// resolvers.ts
export const resolvers = {
Query: {
posts: (_: unknown, __: unknown, ctx: Context) =>
ctx.db.posts.findMany({ take: 20 }),
},
Post: {
author: (post: Post, _: unknown, ctx: Context) =>
ctx.loaders.user.load(post.authorId),
},
User: {
posts: (user: User, _: unknown, ctx: Context) =>
ctx.loaders.postsByAuthor.load(user.id),
},
};
With 20 posts on screen, Post.author fires 20 .load() calls that DataLoader collapses into one WHERE id IN (...) query.
5. Wire Up in Apollo Server
// server.ts
import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
import { createContext } from './context';
import { db } from './db';
import { typeDefs } from './schema';
import { resolvers } from './resolvers';
const server = new ApolloServer({ typeDefs, resolvers });
const { url } = await startStandaloneServer(server, {
context: async () => createContext(db),
});
console.log(`Server ready at ${url}`);
The context function runs once per request, which is what keeps each request’s cache isolated.
How It Works
- Batching: DataLoader collects every
.load(id)call within the same tick. Whenprocess.nextTickfires, it dispatches them as a single batch function call with all IDs. - Caching: after the batch function returns, results are cached by key. A second
.load(id)for the same key returns the cached value without touching the database. - Per-request isolation: a new DataLoader instance is created in the context factory for each request, which prevents cross-request cache leaks.
- Error handling: if the batch function returns an
Errorfor a specific key, that error is thrown when.load(id)resolves for that key; other keys in the batch are unaffected. If the batch function itself throws, every pending load in that batch rejects.
The API surface worth knowing:
loadMany(keys)returns aPromise<(Value | Error)[]>aligned to the input keys, the standard way to resolve a field that needs several entities at once.prime(key, value)writes a value into the cache without fetching, useful after a mutation so later loads in the same request see fresh data.clear(key)evicts one key,clearAll()drops the whole cache.maxBatchSizecaps how many keys a single dispatch accepts;cacheKeyFnderives cache keys for compound inputs;batchScheduleFnoverrides when batches dispatch.
Variants
Cache Invalidation After Mutations
The request cache turns stale the moment a mutation writes. Clear or prime the affected keys inside the mutation resolver:
Mutation: {
updateUser: async (_: unknown, args: { id: string; name: string }, ctx: Context) => {
const updated = await ctx.db.users.update({
where: { id: args.id },
data: { name: args.name },
});
ctx.loaders.user.clear(args.id); // or: ctx.loaders.user.prime(args.id, updated)
return updated;
},
},
Redis-Backed DataLoader
For shared caching across requests, wrap the batch function with a Redis lookup. Keep in mind this shares data across users, so only cache entities that every requester may see:
export function createRedisUserLoader(redis: Redis, db: Db) {
return new DataLoader<string, User>(async (ids: readonly string[]) => {
const cached = await redis.mget(ids.map((id) => `user:${id}`));
const uncachedIds = ids.filter((_, i) => !cached[i]);
const fresh = await db.users.findMany({ where: { id: { in: uncachedIds } } });
await Promise.all(fresh.map((u) => redis.set(`user:${u.id}`, JSON.stringify(u), 'EX', 300)));
const userMap = new Map(fresh.map((u) => [u.id, u]));
return ids.map((id, i) => cached[i] ? JSON.parse(cached[i]!) : userMap.get(id)!);
});
}
Custom Batch Schedule
For high-throughput scenarios, don’t wait for the next tick; dispatch batches on a fixed delay:
const loader = new DataLoader(batchFn, {
batchScheduleFn: (callback) => setTimeout(callback, 10),
maxBatchSize: 500,
});
Best Practices
- Create loaders per request: never share DataLoader instances across requests; the cache leaks data between users
- Align results to input order: DataLoader maps results by position, so sort or map the database rows back onto the input keys
- Return per-key errors: return
new Error()in the result array for missing keys instead of rejecting the whole batch; see GraphQL error handling best practices for shaping the error payload - Disable batching for single-item loads: pass
{ batch: false }when a loader will only ever load one key - Batch authorization into the loader: if field-level access rules apply, check each key inside the batch function and return an
Errorfor denied keys, or you silently widen access
Common Mistakes
- Sharing a DataLoader across requests: causes stale data and cross-user cache contamination
- Not returning results in input order: DataLoader maps results by position, not by key; a filtered
findManyresult returned as-is misaligns the array - Returning fewer results than input keys: same problem as above; every key needs a slot, even if it’s an
Errorornull - Using
.load()in a loop without awaiting: DataLoader batches automatically, but you still mustawaiteach call or collect them withPromise.all/loadMany - Cross-request caching with the default cache: the built-in
Mapcache is request-scoped by design; reach for Redis or{ cache: false }when you need different semantics - Forgetting mutations invalidate the cache: updates leave stale entries in the request cache unless you
clearorprimethe key
See Also
- DataLoader on GitHub: the reference implementation, options, and caching semantics
- Apollo Server context docs: how per-request context is built and passed to resolvers
- Detect and fix N+1 queries in GraphQL resolvers: measure the problem before and after the fix
Frequently Asked Questions
Does DataLoader cache across requests?
No. The default cache is per-instance. Since you create a new instance per request, the cache is request-scoped. For cross-request caching, use Redis or another shared store with explicit invalidation.
Can I use DataLoader with non-database data sources?
Yes. DataLoader works with any batchable source: REST APIs, microservices, message queues, or in-memory stores. The batch function receives an array of keys and returns a Promise of an array of values.
What happens if a batch function throws?
The error propagates to every pending .load() call in that batch. Return Error objects inside the result array to fail individual keys without affecting the rest.
Should I use DataLoader for one-to-many relationships?
Yes. For one-to-many (user.posts), the batch function groups results by foreign key and returns an array per key. The same alignment rules apply: one slot per input key, in order.
How do I invalidate cached data after a mutation?
Call loader.clear(key) to evict the entry or loader.prime(key, freshValue) to replace it. Do it inside the mutation resolver so subsequent loads in the same request see updated data.
How is this different from the DataLoader pattern?
The DataLoader pattern explains the concept and when it fits; this recipe is the runnable implementation with Apollo Server context wiring, error semantics, and cache invalidation.
Related Resources
Build a GraphQL API with Apollo Server and TypeScript
How to build a production-ready GraphQL API using Apollo Server, TypeScript, and DataLoader to solve the N+1 query problem
RecipeCursor-based Pagination with GraphQL Relay Connections
Implement Relay-style cursor pagination in GraphQL with edges, nodes, and pageInfo for efficient forward and backward traversal
PatternGraphQL 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.
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
RecipeCustom GraphQL Scalar Types for Dates, Emails, and JSON
Define custom GraphQL scalars for Date, Email, URL, and JSON fields with serialization, parsing, and validation logic
RecipeStructured GraphQL Errors with Extension Codes
Implement structured error handling in GraphQL with custom error classes, extension codes, and consistent error formatting for clients.