⬡ GraphQL Intermediate

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.