N+1 avoidance with DataLoader (GraphQL)

9320
0

GraphQL makes it very easy to accidentally create N+1 query explosions. DataLoader batches requests for the same resource during a single tick and gives you per-request caching. The trick is scoping: loaders must be per-request, not global singletons, otherwise user A can see cached data from user B. I keep the key format simple (usually a string id) and make sure the batch function returns results in the same order as the keys. This keeps GraphQL’s ergonomics without sacrificing DB performance. Even outside GraphQL, a loader-like approach helps any time you see repeated lookups inside a loop.