advanced
N+1 queries
Detect repeated per-row relationship queries and fix them with joins, batching, preloading, or dataloader-style access.
N+1 happens when one query loads N parent rows and each row triggers another query for related data. Latency and database load grow linearly with result size.
1 query: SELECT * FROM orders LIMIT 100
100 queries: SELECT * FROM customers WHERE id = ?
→ 101 round trips
Fixes: joins, `IN (...)` preloading, dataloaders, batch loaders, narrower projections, or response-shape changes that drop unused relations.
On interviews: name detection via SQL logs or APM and explain why one giant join is not always the fix—it can duplicate rows and break pagination.
Common pitfalls: fixing N+1 with a cartesian join that explodes rows; ignoring pagination correctness; assuming typed ORMs cannot N+1.
The trade-off is batching complexity versus predictable query count.
Checklist:
- Read SQL logs for loops.
- Batch or preload relationships.
- Preserve pagination correctness.
- Match fix to cardinality and response shape.