← Lessons

quiz vs the machine

Platinum1760

System Design

N Plus One Elimination

Why one list query plus a query per row destroys performance and how to fold it.

5 min read · advanced · beat Platinum to climb

The hidden multiplier

The N plus one problem happens when code runs one query to fetch a list of N items, then runs one more query per item to load related data. That is 1 plus N queries, and each carries round trip overhead.

It often hides behind a loop or a lazy loaded relation that quietly fires a query every iteration.

Why it hurts

  • Round trips dominate, since N small queries cost far more than one larger one.
  • It scales badly, getting worse as the list grows.
  • It is invisible in code that looks like a simple loop.

Fixes

  • Batch fetch by collecting the ids and loading related rows in one query with an in list.
  • Join the related table so one query returns everything.
  • Eager load the relation when you know you will need it.
  • Data loader patterns coalesce per item lookups within a request into a single batched call.

Watch out

Joins can multiply rows and pull extra data, so for large fan outs a separate batched query is often cleaner than one giant join.

Key idea

Replace one query per row with a single batched fetch or join so related data loads in one round trip instead of N.

Check yourself

Answer to earn rating on the learn ladder.

1. What defines the N plus one query problem?

2. Which fix loads related data in one round trip?