Repaso
Español
Backend & APIsAdvancedAPI-23

In GraphQL, resolving posts { author { name } } naively causes many DB queries. Common fix?

Options

  1. Use REST endpoints instead of GraphQL for the nested data
  2. Batch and cache the lookups per request with a DataLoader (Correct option)
  3. Add more indexes to the tables of the database that is used
  4. Disable the nested fields in the schema for all the clients

Answer

Batch and cache per request with a DataLoader

Why

GraphQL calls a resolver function per field. For 50 posts, the author resolver runs 50 times = 50 queries (the N+1 problem again).

A DataLoader collects all author IDs requested in the same moment and loads them in ONE query (WHERE id IN (...)), then hands each resolver its author.

Remember

GraphQL N+1 → DataLoader batching.

Key terms

Practice this question in Repaso