OptimizationBeginner
What is the N+1 query problem?
“Explain N+1 and how you would fix it.”
What this tests
- Recognising a per-row query pattern
- Preloading / joining
Answers by level
Read the beginner answer first and notice what is missing.
One query to fetch a list, then one query per row for related data: 1 + N. Each is fast, so it is invisible to per-query monitoring, but the page pays N network round trips. ORMs produce it when you access a relationship inside a loop.
Fix with a single join and GROUP BY, or preload the children with one WHERE parent_id IN (…) and stitch in memory.
Green flags · Red flags
Strong green flag · Explains that the cost is round trips, not query time.
Green flags
- Counts 1 + N
- Knows it hides from per-query monitoring
- Preload or join
Red flags
- "Just cache it"
- Does not know why the page is slow while queries are fast
Follow-up questions
F1
How do you detect N+1 in production?
Scenario
GET /users returns 100 users in 900 ms; every query in the log is sub-ms. Diagnose.