Full answer
Each round trip costs network latency and parsing even when the query itself is fast. At 2 ms per query, 51 queries take about 100 ms, and the number grows with the page size.
Fixes:
- One JOIN:
SELECT o.*, c.name FROM orders o JOIN customers c ON c.id = o.customer_id WHERE ... LIMIT 50. - Two queries: load the orders, collect distinct customer ids, then
SELECT * FROM customers WHERE id IN (...)and stitch in code. This avoids repeating wide customer rows. - ORM settings: eager loading (for example
select_relatedorincludes) turns lazy per-row loads into one of the forms above.
Detect it by counting queries per request in logs or tests. A test that asserts a maximum query count per endpoint stops regressions.
Key points
- N+1 = one list query plus one per row
- Latency per round trip dominates
- Use a JOIN or a batched IN query
- Count queries per request in tests
Common mistakes
- Caching each per-row query instead of batching
- Assuming fast individual queries mean a fast page
Follow-ups
- When is the two-query approach better than a join?
- How would you detect N+1 in production?
Tips
- Quantify the round trips