MidDatabases

What is the N+1 query problem, and how do you fix it?

What they are really testing: Whether you recognize this extremely common ORM performance bug, can explain why it happens (lazy loading), and know the fixes (eager loading, joins, batching).

A real interview question

What is the N+1 query problem, and how do you fix it?

What most people say

drag me

It is when you run too many queries; you fix it by optimizing the queries.

Vague. The N+1 pattern is specific, a query per row from lazy loading, and the fix is specific, eager loading or batching. "Optimize the queries" shows you do not actually recognize the pattern.

The follow-ups they ask next

  • Why does this often pass in development but fail in production?

    In dev the lists are tiny (10 rows = 11 queries, fast). In prod the same code hits thousands of rows = thousands of round trips. The pattern scales with data volume, so it only hurts at real scale.

  • What is the difference between eager loading and batching here?

    Eager loading fetches the relation along with the parent (a JOIN or ORM preload). Batching collects the IDs and issues a single IN query for all related rows. Both replace N per-row queries with one or two.

What the interviewer is listening for

  • Recognizes the pattern + lazy loading cause
  • Knows the per-round-trip impact at scale
  • Fixes with eager loading/JOIN/batching

What sinks the answer

  • Vague "too many queries"
  • Does not name lazy loading
  • No specific fix

If you genuinely do not know

Say this instead of freezing. Reasoning out loud from what you do know beats silence every single time, and a good interviewer is listening for exactly that.

N+1 = [one query for N items, then one query per item for a relation, so N+1 total]. Cause: [ORM lazy loading, accessing a relation in a loop fires a query each time]. Impact: [each is a round trip, fine at 10 rows, catastrophic at 10,000]. Fix: [eager-load (JOIN/preload) or batch into one IN query]. Catch it by [watching query count per request].

Keep going with databases

All 336 cloud engineer questions

Knowing the answer is not the same as recalling it under pressure

Sign in to send the questions you fumble to spaced recall, so they come back right before you would forget them, and learn the concepts behind them with hands-on labs.

Start free