Fetching a list along with nested relations (like posts and their authors) triggers one database query per item instead of one batched query, causing slow responses and heavy database load.
Use the DataLoader pattern to batch and cache lookups within a single request instead of querying the database once per item.
Step-by-Step Guide
Confirm the N+1 pattern by logging the number of DB queries per request
Install DataLoader: npm install dataloader
Create a loader per entity type that batches an array of IDs into a single query
Instantiate a new DataLoader per incoming request, never as a global singleton
Call loader.load(id) inside resolvers instead of querying the database directly
Add query depth/complexity limiting to prevent abusive deeply nested queries
Consider an ORM's built-in batching (e.g., Prisma) as an alternative to manual DataLoaders
Monitor with Apollo Server's tracing plugin to confirm query counts dropped
Found an issue with this solution?