Full answer
The problem
- Query: posts { title author { name } }. The posts resolver runs 1 query for N posts. The author resolver then runs for every post, N more queries. With 100 posts that is 101 queries, which hurts latency and the database.
DataLoader
- const loader = new DataLoader(async (ids) => { rows = await db.users.where(id in ids); return ids.map((id) => rows.find(...) ?? null); }).
- Resolvers call loader.load(post.authorId). DataLoader waits until the current tick ends, gathers all keys, deduplicates them, calls the batch function once, and gives each caller its own result.
- Caching: the loader remembers values per key, so the same author is loaded once per request.
Rules
- Create loaders in the context function for each request. A global loader would cache data across users and across time (stale and a privacy leak).
- The batch function must return an array with the same length and order as the keys. Missing rows need null or an Error at that position. Mismatched ordering is the classic bug.
- Use it for any one-to-one or one-to-many relation (loaders keyed by foreign key for lists).
- It batches within one tick. Work that is separated by awaits of other work may not batch.
- Clear or prime the cache after mutations if the same request reads the data again.
Other fixes: joins and select-ahead in the parent query (look at info to see requested fields), and in REST the same idea is called eager loading.
Check the effect: log the number of queries per request and test it, because N+1 comes back quietly.
const { buildSchema, graphql } = require('graphql');
const DataLoader = require('dataloader');
// A fake database that counts queries.
let queries = [];
const users = [{ id: 1, name: 'Asha' }, { id: 2, name: 'Ravi' }, { id: 3, name: 'Meera' }];
const posts = Array.from({ length: 6 }, (_, i) => ({ id: i + 1, title: 'Post ' + (i + 1), authorId: (i % 3) + 1 }));
const db = {
allPosts: async () => { queries.push('SELECT * FROM posts'); return posts; },
userById: async (id) => { queries.push(`SELECT * FROM users WHERE id = ${id}`); return users.find((u) => u.id === id); },
usersByIds: async (ids) => { queries.push(`SELECT * FROM users WHERE id IN (${ids.join(', ')})`); return users.filter((u) => ids.includes(u.id)); },
};
const schema = buildSchema(`
type User { name: String! }
type Post { title: String! author: User }
type Query { posts: [Post!]! }
`);
const query = '{ posts { title author { name } } }';
const naive = { posts: () => db.allPosts().then((list) => list.map((p) => ({ ...p, author: () => db.userById(p.authorId) }))) };
const batched = { posts: (args, context) => db.allPosts().then((list) => list.map((p) => ({ ...p, author: () => context.userLoader.load(p.authorId) }))) };
const makeContext = () => ({
userLoader: new DataLoader(async (ids) => {
const rows = await db.usersByIds(ids);
return ids.map((id) => rows.find((u) => u.id === id) ?? null); // same order and length as ids
}),
});
(async () => {
queries = [];
const a = await graphql({ schema, source: query, rootValue: naive });
console.log('naive resolvers :', queries.length, 'queries for', a.data.posts.length, 'posts');
queries = [];
const b = await graphql({ schema, source: query, rootValue: batched, contextValue: makeContext() });
console.log('with DataLoader :', queries.length, 'queries:', JSON.stringify(queries));
console.log('same result :', JSON.stringify(a.data) === JSON.stringify(b.data));
// Caching inside one request, and the batch order rule
queries = [];
const loader = makeContext().userLoader;
const [x, y, z] = await Promise.all([loader.load(2), loader.load(1), loader.load(2)]);
console.log('keys 2,1,2 ->', [x, y, z].map((u) => u.name).join(','), '| batch calls:', queries.length, '|', queries[0]);
await loader.load(1);
console.log('load(1) again hits the cache, batch calls still:', queries.length);
console.log('a missing key gives null, not a shifted result:', await loader.load(99));
})();Six posts are resolved with one query each for the author, and then with DataLoader. The last lines show deduplication, the cache and a missing key. Install first with npm install graphql dataloader (run here with graphql 16.15.0, dataloader 2.2.3). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): naive resolvers : 7 queries for 6 posts with DataLoader : 2 queries: ["SELECT * FROM posts","SELECT * FROM users WHERE id IN (1, 2, 3)"] same result : true keys 2,1,2 -> Ravi,Asha,Ravi | batch calls: 1 | SELECT * FROM users WHERE id IN (2, 1) load(1) again hits the cache, batch calls still: 1 a missing key gives null, not a shifted result: null
Key points
- N+1 means one query for the list plus one per item.
- DataLoader batches keys from one tick into a single call.
- It caches by key within the request.
- Create loaders per request, never globally.
- The batch function must keep key order and length.
Common mistakes
- Creating one global DataLoader.
- A batch function that returns rows in database order instead of key order.
- Calling await inside a loop of resolvers so keys never batch.
- Forgetting that the cache lives for the whole request.
- Not measuring the query count in tests.
Follow-ups
- How do you batch a one-to-many relation?
- What does the DataLoader cache do after a mutation?
- How can the parent query use joins instead?
Tips
- Show the 1 + N arithmetic.
- Say 'same tick, one batch, per request'.
- Mention the order rule.