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

1

Confirm the N+1 pattern by logging the number of DB queries per request

2

Install DataLoader: npm install dataloader

3

Create a loader per entity type that batches an array of IDs into a single query

4

Instantiate a new DataLoader per incoming request, never as a global singleton

5

Call loader.load(id) inside resolvers instead of querying the database directly

6

Add query depth/complexity limiting to prevent abusive deeply nested queries

7

Consider an ORM's built-in batching (e.g., Prisma) as an alternative to manual DataLoaders

8

Monitor with Apollo Server's tracing plugin to confirm query counts dropped

Found an issue with this solution?

Related Topics

dataloader caching per requestgraphql query complexity limitingapollo server performance tracing