Lesson 4 of 9 · 26m
N+1 and DataLoaders: Making Resolvers Batch by Default
Why naive resolvers multiply database queries, how request-scoped batching works, and the caching mistakes that corrupt correctness.
The first time a GraphQL endpoint melts a database, the query usually looks harmless: twenty workspaces, each with members, each member with an avatar. In REST you would have written one join. In GraphQL, nested resolvers execute independently, so one workspace query becomes one member query per workspace and one avatar lookup per member. Congratulations: you built a query amplifier.
See the amplification before fixing it
const resolvers = {
Workspace: {
members: (workspace, args, ctx) =>
db.membersByWorkspace(workspace.id),
},
Member: {
avatar: (member, args, ctx) =>
db.avatarByUser(member.userId),
},
};For 20 workspaces with 30 members each, this can execute 1 + 20 + 600 database queries. The schema did not cause it; uncoordinated resolver execution did.
DataLoader batches and memoizes within one request
A loader collects keys requested in the same execution tick, calls one batch function, and returns results in the same order as the keys:
import DataLoader from "dataloader";
function createLoaders(db) {
return {
membersByWorkspace: new DataLoader(async workspaceIds => {
const rows = await db.membersWhereWorkspaceIn(workspaceIds);
return workspaceIds.map(id => rows.filter(r => r.workspaceId === id));
}),
avatarByUser: new DataLoader(async userIds => {
const rows = await db.avatarsWhereUserIn(userIds);
const byUser = new Map(rows.map(r => [r.userId, r]));
return userIds.map(id => byUser.get(id) ?? null);
}),
};
}Resolvers then use the loader:
members: (workspace, args, ctx) => ctx.loaders.membersByWorkspace.load(workspace.id),
avatar: (member, args, ctx) => ctx.loaders.avatarByUser.load(member.userId),Those 621 queries often collapse to three: workspaces, members, avatars.
Loaders are request-scoped
Never share a DataLoader across requests unless you fully understand cache invalidation and tenant isolation. A loader caches by key for its lifetime. If user A can see a private document and user B cannot, a shared loader can hand B the cached object and bypass authorization. Create loaders per request in the context factory.
Batching is not only for SQL
Use the same pattern for downstream services:
new DataLoader(async projectIds => {
const response = await billingClient.getPlans({ projectIds });
return projectIds.map(id => response.plans[id] ?? null);
})Mind downstream fan-out. Batching ten keys into one HTTP call is good; batching five thousand into a call with a 10 MB payload is a new incident.
Priming and clearing caches
DataLoader exposes prime and clear, which are useful after mutations or when a batch already fetched related rows. Prime only values you know are correct for this request. Do not prime partially populated objects unless the field contract says partial data is acceptable; otherwise a later field resolver may mistake incomplete data for complete data.
Field notes
- Batch functions must return exactly one result per input key, in input order; length mismatches are painful production bugs.
loadManyis convenience, not semantics — errors and nulls still map by position.- Dataloader deduplicates identical keys. That is useful for repeated references, not a substitute for authorization.
- Put tracing around batch functions; resolver spans alone hide the real database work.
- A join can still beat a loader for fixed hot paths. Batching is a tool, not a religion.
Was this lesson helpful?