What is the N+1 problem in GraphQL and how does DataLoader solve it?
Answer
The N+1 problem occurs when fetching a list of N items triggers N additional database queries — one per item. For example, querying 100 posts where each post resolver then queries the database for the author causes 1 (list) + 100 (authors) = 101 queries. DataLoader solves this by batching and caching. It collects all individual load requests within a single event loop tick, then fires one batched query (e.g., SELECT * FROM users WHERE id IN (1,2,...,100)), and distributes results back to the individual resolvers. It is the standard solution in Node.js GraphQL servers and has ports in virtually every backend language.
Previous
What is over-fetching and under-fetching in REST and how does GraphQL solve them?
Next
What are persisted queries in GraphQL?
More GraphQL Questions
View all →- Intermediate What are persisted queries in GraphQL?
- Intermediate What is the difference between schema-first and code-first GraphQL approaches?
- Intermediate What are the pagination strategies in GraphQL?
- Intermediate How is authentication handled in GraphQL?
- Intermediate How do you implement field-level authorization in GraphQL?