The N+1 Problem
GraphQL's field-by-field execution is elegant, but it hides a classic performance trap. Each resolver fetches its own data, independently of its siblings. Ask for a list of 50 posts with their authors, and a naive server runs 1 query for the posts plus 50 queries for the authors: the N+1 problem.
Seeing it happen
We'll simulate a database that logs every query it receives:
import { graphql, buildSchema } from 'graphql';
const schema = buildSchema(`
type User { id: ID!, name: String! }
type Post { id: ID!, title: String!, author: User! }
type Query { posts: [Post!]! }
`);
const tables = {
users: [{ id: 1, name: 'Ana' }, { id: 2, name: 'Ben' }, { id: 3, name: 'Chloé' }],
posts: [
{ id: 1, title: 'Hello', authorId: 1 },
{ id: 2, title: 'GraphQL tips', authorId: 2 },
{ id: 3, title: 'On caching', authorId: 1 },
{ id: 4, title: 'Batching', authorId: 3 },
{ id: 5, title: 'Wrap-up', authorId: 2 },
],
};
const queryLog = [];
const db = {
allPosts: async () => {
queryLog.push('SELECT * FROM posts');
return tables.posts;
},
userById: async (id) => {
queryLog.push(`SELECT * FROM users WHERE id = ${id}`);
return tables.users.find((u) => u.id === id);
},
};
const rootValue = {
posts: async () => {
const rows = await db.allPosts();
return rows.map((row) => ({ ...row, author: () => db.userById(row.authorId) }));
},
};
const result = await graphql({ schema, rootValue, source: '{ posts { title author { name } } }' });
console.log(result.data.posts.map((p) => `${p.title} by ${p.author.name}`).join('; '));
console.log(`${queryLog.length} database queries:`);
console.log(queryLog.join('\n'));Hello by Ana; GraphQL tips by Ben; On caching by Ana; Batching by Chloé; Wrap-up by Ben
6 database queries:
SELECT * FROM posts
SELECT * FROM users WHERE id = 1
SELECT * FROM users WHERE id = 2
SELECT * FROM users WHERE id = 1
SELECT * FROM users WHERE id = 3
SELECT * FROM users WHERE id = 2
Five posts, six queries, and users 1 and 2 were fetched twice. With nested lists (posts → comments → authors) the count multiplies.
Why GraphQL is prone to it
In REST you'd write one handler with one SQL JOIN. In GraphQL, the author resolver runs once per post, with no knowledge of the others. That's what makes resolvers composable (any query shape works), and also what causes N+1.
Fix 1: eager loading in the parent
The parent resolver can fetch everything its children will need in one query, if it knows they'll be needed. Here posts loads all authors with an IN (…) query:
const tables = {
users: [{ id: 1, name: 'Ana' }, { id: 2, name: 'Ben' }, { id: 3, name: 'Chloé' }],
posts: [
{ id: 1, title: 'Hello', authorId: 1 },
{ id: 2, title: 'GraphQL tips', authorId: 2 },
{ id: 3, title: 'On caching', authorId: 1 },
{ id: 4, title: 'Batching', authorId: 3 },
{ id: 5, title: 'Wrap-up', authorId: 2 },
],
};
const queryLog = [];
const db = {
allPosts: async () => { queryLog.push('SELECT * FROM posts'); return tables.posts; },
usersByIds: async (ids) => {
queryLog.push(`SELECT * FROM users WHERE id IN (${ids.join(', ')})`);
return tables.users.filter((u) => ids.includes(u.id));
},
};
async function postsWithAuthors() {
const posts = await db.allPosts();
const ids = [...new Set(posts.map((p) => p.authorId))];
const users = await db.usersByIds(ids);
const byId = new Map(users.map((u) => [u.id, u]));
return posts.map((p) => ({ ...p, author: byId.get(p.authorId) }));
}
const posts = await postsWithAuthors();
console.log(posts.map((p) => p.author.name).join(', '));
console.log(queryLog);Ana, Ben, Ana, Chloé, Ben
[ 'SELECT * FROM posts', 'SELECT * FROM users WHERE id IN (1, 2, 3)' ]
Two queries instead of six. The downside: posts now always loads authors, even for a query like { posts { title } }. You could inspect info to see whether author was selected, but that couples parent and child resolvers tightly.
Fix 2: batching (the usual answer)
The better approach keeps every resolver independent but delays the actual lookups for a moment. All author resolvers of one execution step register the id they want; then one batched query loads them all. This is what DataLoader does, and it's the subject of the next lesson.
How to notice N+1 in your app
- Log or trace database queries per GraphQL request; a count that grows with the list size is the tell-tale sign.
- Watch for the same query repeated with different ids.
- APM and GraphQL tracing tools (Apollo Studio, OpenTelemetry) show resolver timings in a waterfall, where N+1 looks like a staircase.
Test yourself
A query loads 20 orders and each order's customer with a naive resolver. How many database queries run?
- 1
- 2
- 21
- 40
What is the drawback of eager-loading children in the parent resolver?
- It doesn't reduce queries
- It loads related data even when the query didn't ask for it
- It breaks validation
- It only works with SQL
Which technique keeps resolvers independent while avoiding N+1?
- Making all fields non-null
- Batching lookups with a DataLoader
- Using fragments
- Disabling introspection