Node.js › GraphQL with Node.js
What is the N+1 query problem specific to GraphQL, and how does DataLoader solve it?
AdvancedAnswer
Because a GraphQL query can request nested related data (like a list of posts, each with their author), a naive resolver implementation ends up calling the database once per post to fetch its author individually, exactly the N+1 problem -- DataLoader solves this by batching and caching individual load requests that occur within the same tick of the event loop, automatically combining what would have been N separate database calls into a single batched query, while still letting each resolver be written as if it were making an independent request.
const DataLoader = require('dataloader');
const userLoader = new DataLoader(async (userIds) => {
const users = await db.users.findByIds(userIds); // one batched query for all requested IDs
return userIds.map(id => users.find(u => u.id === id));
});
// Each resolver call looks independent, but DataLoader batches them automatically
const resolvers = {
Post: { author: (post) => userLoader.load(post.authorId) },
};Real-world example A GraphQL API serving a query requesting 50 blog posts along with each post's author previously triggered 51 separate database queries under the hood; introducing a DataLoader for user lookups collapses this into just 2 queries total, regardless of how many posts are requested in a single GraphQL query.