Data Loader
ELI5 — The Vibe Check
DataLoader batches and caches database calls in GraphQL. Without it, fetching 100 users with their posts makes 101 database queries (the N+1 problem). DataLoader collects all the IDs, makes ONE query for all of them, and distributes the results. It's carpooling for database queries.
Real Talk
DataLoader is a utility for batching and caching database requests, primarily used to solve the N+1 problem in GraphQL resolvers. It collects individual load requests within a single tick of the event loop, batches them into a single database query, and distributes results back to the callers. Each DataLoader instance caches results per-request.
Show Me The Code
const userLoader = new DataLoader(async (ids) => {
const users = await db.users.findByIds(ids);
return ids.map(id => users.find(u => u.id === id));
});
// Instead of N queries, makes 1 batched query
const user1 = await userLoader.load('id-1');
const user2 = await userLoader.load('id-2');
When You'll Hear This
"Add a DataLoader to batch the user lookups — we're making 500 queries per request." / "DataLoader reduced our GraphQL query from 200ms to 15ms by batching."
Related Terms
Batch Loading
Batch loading is fetching many things in one call instead of one at a time. Instead of asking 'give me user 1... give me user 2... give me user 3...
GraphQL
GraphQL is like ordering food where YOU specify exactly what you want on your plate.
N+1 Problem
The N+1 problem is when your code makes 1 query to get a list of things, then N more queries to get related data for each thing.
Resolver
A resolver is a function that fetches the data for a single field in a GraphQL query. When you ask for user.