Writing
Fullstack English

The N+1 Query: Your API Is Slow in a Loop

How to spot N+1 queries in production, fix them with joins or batching, and keep them from coming back.

  • Published
  • 1 min read
On this page3 sections
  1. Spotting it
  2. Fixing it
  3. Keeping it fixed

An endpoint that is fast with 10 records and dies with 1,000 is almost always the same disease: one query for the list, then one more query per row. The ORM made it easy; the database is doing 1,001 round trips.

Spotting it

Turn on query logging in staging and hit the endpoint once. If the log scrolls, you have it:

text
SELECT * FROM orders LIMIT 100;
SELECT * FROM customers WHERE id = 1;
SELECT * FROM customers WHERE id = 2;
-- ... x100

Fixing it

Either join (one query) or batch (two queries):

sql
-- join
SELECT o.*, c.name FROM orders o JOIN customers c ON c.id = o.customer_id;

-- batch: fetch orders, collect ids, then
SELECT * FROM customers WHERE id = ANY($1);

Most ORMs spell “batch” as eager loading - includes(:customer), ->with('customer'), prefetch_related. The fix is usually one line. Finding which line is the actual work.

Keeping it fixed

  • Add a CI check that counts queries per request in integration tests (n_plus_one_control, django-zen-queries, or a homemade counter). Fail the build at a threshold.
  • Watch p95, not average - N+1 hides in averages because small lists stay fast.

Most mature codebases have a few of these in the hot path. It is the most profitable twenty minutes of performance work that exists.