Three books, four SQL queries. A hundred books, 101 queries. That's what happens on the Bookshop server for { books { title author { name } } } when every resolver reads the database on its own. It's called the N+1 problem: the server runs 1 query to fetch a list, then 1 more query for each item in that list.
DataLoader fixes it: it gathers all the small requests first, then fetches them in one go. It's like the Bookshop cashier preparing 3 orders. The slow way: take the first order, walk to the stockroom to look up its author, come back, then walk again for the second order, and so on. The fast way: write down every author needed first, then walk to the stockroom once with one list.
Counting N+1
These are "honest" resolvers: each one runs its own SQL query. sql() records the query and returns its result, just like the Lab on this page:
const resolvers = {
Query: {
books: () => sql("SELECT * FROM books"),
},
Book: {
// Called once for EVERY book.
author: (book) => sql(`SELECT * FROM authors WHERE id = ${book.authorId}`),
},
};
In the "Resolvers" lesson you saw the order: Query.books first, then Book.author once per book. Written down:
| # | Resolver | SQL that runs |
|---|---|---|
| 1 | Query.books |
SELECT * FROM books |
| 2 | Book.author (The Rainbow Troops) |
SELECT * FROM authors WHERE id = 1 |
| 3 | Book.author (This Earth of Mankind) |
SELECT * FROM authors WHERE id = 2 |
| 4 | Book.author (Beauty Is a Wound) |
SELECT * FROM authors WHERE id = 3 |
Four queries: 1 for the list, plus N = 3 for the authors. It's called N+1 because the count grows with the list: 100 books means 101 queries, when the data could come in 2. The same problem shows up in { authors { name books { title } } }: 1 query for the authors, then 1 books query per author, so 5 queries for 4 authors.
DataLoader: gather first, fetch once
A resolver can't see its siblings, so Book.author for book 1 doesn't know books 2 and 3 need an author too. The trick: the resolver doesn't query right away. It only says "I need author 1" through load(1), then waits. Here is a DataLoader written by hand:
class DataLoader {
constructor(batchFn) {
this.batchFn = batchFn;
this.cache = new Map(); // key -> Promise, for one request
this.queue = []; // keys waiting for the next batch
}
load(key) {
if (this.cache.has(key)) return this.cache.get(key);
const promise = new Promise((resolve, reject) => {
this.queue.push({ key, resolve, reject });
// the first load schedules the batch, after the code that is running now finishes
if (this.queue.length === 1) queueMicrotask(() => this.dispatch());
});
this.cache.set(key, promise);
return promise;
}
async dispatch() {
const queue = this.queue;
this.queue = [];
try {
const values = await this.batchFn(queue.map((item) => item.key));
queue.forEach((item, i) => (values[i] instanceof Error ? item.reject(values[i]) : item.resolve(values[i])));
} catch (error) {
queue.forEach((item) => item.reject(error));
}
}
}
const authorLoader = new DataLoader(async (ids) => {
const rows = await sql(`SELECT * FROM authors WHERE id IN (${ids.join(", ")})`);
return ids.map((id) => rows.find((a) => a.id === id) ?? new Error(`Author ${id} not found`));
});
const resolvers = {
Book: {
author: (book) => authorLoader.load(book.authorId),
},
};
load(key)puts the key in the queue and returns a Promise. No query yet.queueMicrotaskdelaysdispatch()until the code that is running now finishes. All threeBook.authorcalls happen in the same run, so whendispatch()runs, the queue is already[1, 2, 3].batchFngets every key at once and runs one query:SELECT * FROM authors WHERE id IN (1, 2, 3). That makes 2 queries in total, however many books there are.- The results must have the same order and length as
ids. A database may return rows in any order, which is whyids.map(...)finds the row for each id. Value i answers load i. - Errors per key: if author 9 doesn't exist, that position holds
new Error(...). Onlyload(9)fails; the other keys still get their data. - Cache: a second
load(1)(The Dreamer, say, also by Andrea Hirata) gets the same Promise. Key 1 enters the batch only once.
The dataloader package
In a real project, use the dataloader package (version 2.2.3, from the GraphQL Foundation). The rules are exactly the same:
import DataLoader from "dataloader";
const authorLoader = new DataLoader(async (ids) => {
const { rows } = await db.query("SELECT * FROM authors WHERE id = ANY($1)", [ids]); // node-postgres
return ids.map((id) => rows.find((a) => a.id === id) ?? new Error(`Author ${id} not found`));
});
- If the array it returns has a different length, every
loadin that batch fails withDataLoader must be constructed with a function which accepts Array<key> and returns Promise<Array<value>>, but the function did not return a Promise of an Array of the same length as the Array of keys. - Its timing is a little more patient than ours: in Node.js the batch goes out after every queued Promise job has run (
process.nextTick), in a browser throughsetImmediateorsetTimeout. - Options you'll use:
cache: false(still batches, no cache; the same key can go in twice),maxBatchSize, andcacheKeyFnfor keys that are objects. - Its cache is a
Map, so1and"1"are different keys. Keep the key type the same.
One loader per request
A DataLoader's cache keeps results for as long as the loader lives. If the loader is made once for the whole server, an author who was changed is still answered with the old version, and data one user may see can travel to another user. That's why the loaders are made fresh in context, which is made fresh for every request anyway:
await startStandaloneServer(server, {
context: async () => ({
loaders: {
authorById: new DataLoader(batchAuthors),
booksByAuthor: new DataLoader(batchBooksByAuthor),
},
}),
});
const resolvers = {
Book: {
author: (book, _, { loaders }) => loaders.authorById.load(book.authorId),
},
Author: {
books: (author, _, { loaders }) => loaders.booksByAuthor.load(author.id),
},
};
booksByAuthor returns one array per key: ids.map((id) => rows.filter((b) => b.authorId === id)). An author with no books, like Ahmad Tohari, gets [].
Other options for N+1. This lesson uses DataLoader because it works with any data source:
| Way | When to pick it |
|---|---|
| DataLoader (used here) | you write the resolvers yourself, and the data can come from SQL, Redis or another API |
Lighthouse on Laravel: author: Author! @belongsTo |
your schema is built with Lighthouse. Relation directives such as @belongsTo and @hasMany combine their relation queries into one database query, with no loader of your own |
Prisma: prisma.author.findUnique({ where: { id: book.authorId } }) |
you use Prisma. findUnique() calls with the same shape in the same tick are combined automatically. findMany() is not combined |
| A JOIN in the parent resolver | the list screen nearly always asks for the author, so books fetches the books and their authors with one JOIN. If author is not asked for, the JOIN is wasted: check the requested fields through info first |
Query batching over HTTP: a different problem
One term sounds alike. Query batching means the client sends several operations in one HTTP request, as an array, and the server answers with an array too:
[
{ "query": "{ book(id: 1) { title } }" },
{ "query": "{ book(id: 2) { title } }" }
]
In Apollo Server it's off by default (allowBatchedHttpRequests: false), and a request shaped like an array gets status 400 with the message Operation batching disabled.. On the client, Apollo Client has BatchHttpLink to send them.
The difference: query batching cuts the number of requests from client to server. DataLoader cuts the number of queries from server to database. You can use both together.
⚠️ The loader is there, so why are the results odd?
- A global loader. Made once outside
context, its cache serves every request: stale data, leaking between users. Make a new one per request. - Batch results out of order. Returning
rowsas they come gives books the wrong author. Alwaysids.map(...). - A result of a different length. One id isn't found and is dropped from the array: the whole batch fails. Fill its position with
nullornew Error(...). - Mixed key types.
load("1")andload(1)don't share the cache.
TL;DR: N+1 = 1 query for the list + 1 query per item; in the Bookshop, { books { title author { name } } } runs 4 queries, and 100 books means 101. DataLoader has resolvers call load(key) instead of querying directly; every key in one run is gathered, then batchFn is called once (WHERE id IN (1, 2, 3)), for 2 queries in total. batchFn must return an array with the same length and order as the keys (use ids.map), with an Error for a key that failed. Its cache fetches the same key only once. Make new loaders in context for every request. Query batching over HTTP is something else: several operations in one HTTP request, off by default in Apollo Server.
⚡ One query per book
Write:
const resolvers = {
Query: {
books: () => sql("SELECT * FROM books"),
},
Book: {
// Called once for EVERY book.
author: (book) => sql(`SELECT * FROM authors WHERE id = ${book.authorId}`),
},
};
Guess first: { books { title author { name } } } for 100 books. How many SQL queries run?
101: one for the book list, then one more for each book's author. Yet the data could come in 2 queries.
Meaning: That's the N+1 problem: a resolver calls the database again and again, once for every item in the list.
⚡ DataLoader: gather first, fetch once
Write:
const resolvers = {
Book: {
author: (book) => authorLoader.load(book.authorId),
},
};
Meaning: load() only notes the key it needs; no query runs yet. Once every Book.author has been called, the batch function gets all the keys at once and runs one query, WHERE id IN (1, 2, 3). Its results must match ids in length and order.
⚡ One loader per request
Meaning: A DataLoader's cache lives as long as its loader. Make fresh loaders in context for every request, so old data or another user's data doesn't carry over.