· 1 min
Why DataLoader exists, and what it actually fixes
The N+1 problem is easy to explain and easy to ignore — until a list endpoint starts making hundreds of queries per request.
By Akshay Dhanraj Kurve, software engineer
Resolve a list of 50 conversations, and ask each one for its last sender's profile, and you've just made 51 database round-trips for one page load. That's the N+1 problem, and it shows up in GraphQL resolvers and plain REST handlers alike.
Without batching
[Client] -> [API] -> SELECT * FROM messages LIMIT 50;
├─> SELECT * FROM users WHERE id = 1;
├─> SELECT * FROM users WHERE id = 2;
... 50 separate queries
What DataLoader changes
DataLoader exploits the Node.js event loop. Calling userLoader.load(id) doesn't fire a query — it queues the id and returns an unresolved promise. On the next tick, DataLoader runs your batch function once with every id collected so far.
const userLoader = new DataLoader(async (userIds: readonly string[]) => {
const users = await db.query("SELECT * FROM users WHERE id IN (?)", [userIds]);
const map = new Map(users.map((u) => [u.id, u]));
return userIds.map((id) => map.get(id) ?? null);
});
- Batch functions must return results in the same order as the input keys
- Scope DataLoader instances per request — a global cache leaks data across users
- 50 lookups become one query:
SELECT * FROM users WHERE id IN (1, 2, ... 50)
On a chat platform I built, adding DataLoader to the conversation-list resolver cut database round-trips by about 85% with no change to the API shape — just to how the resolver fetches data underneath it.