In GraphQL, resolving posts { author { name } } naively causes many DB queries. Common fix?
Options
- Use REST endpoints instead of GraphQL for the nested data
- Batch and cache the lookups per request with a DataLoader (Correct option)
- Add more indexes to the tables of the database that is used
- 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.