Intermediate LevelREST APIs & Web Services
How does the DataLoader pattern solve N+1 Query Problems in GraphQL resolvers?
❓ Interview Prompt: Explain the N+1 Database Query problem in GraphQL nested resolvers and batching/memoizing with Dataloader.
The N+1 Query Problem:
If a GraphQL query requests 100 'authors' and their 'books', a naive nested resolver executes 1 query for authors + 100 separate queries for each author's books (101 SQL queries!).
DataLoader Solution:
DataLoader collects all author IDs requested within a single tick of the JavaScript event loop, batches them into a single SQL query ('SELECT FROM books WHERE author_id IN (1, 2, ... 100);'), reducing 101 queries down to 2 queries*!
Code Implementation Example
typescript
import DataLoader from 'dataloader';
// Create DataLoader batch loading function
const batchBooksByAuthor = new DataLoader(async (authorIds: readonly string[]) => {
const books = await db.books.findMany({ where: { authorId: { in: [...authorIds] } } });
// Map books back to matching authorId order...
return authorIds.map(id => books.filter(b => b.authorId === id));
});
// Resolver calls loader:
const resolvers = {
Author: {
books: (author) => batchBooksByAuthor.load(author.id)
}
};💡Batching GraphQL nested resolver database queries using DataLoader.
🎯 Interview Key Takeaway
DataLoader eliminates N+1 query bottlenecks in API resolvers by batching IDs requested in an event loop tick into a single SQL query.
#GraphQL#DataLoader#N+1 Problem#Intermediate
Back to all REST APIs & Web Services Questions→