The N+1 problem
Every other performance problem in this part shows up in a slow-query log. This one does not, which is why it survives in production for years.
N+1 is the most common database performance bug in application code, and it is the one most likely to come up in a backend interview — because it lives exactly at the boundary between SQL and the code that calls it.
What it is
One query to fetch a list, then one more query per item in that list.
SELECT * FROM department; -- 1 query, 4 rows
SELECT * FROM employee WHERE department_id = 1; -- then one
SELECT * FROM employee WHERE department_id = 2; -- per
SELECT * FROM employee WHERE department_id = 3; -- department
SELECT * FROM employee WHERE department_id = 4;
Five queries for four departments. With four hundred departments it is four hundred and one, and every single one is fast. Each is an indexed lookup returning in under a millisecond. The slow-query log is empty. The endpoint takes three seconds.
Why it is slow when every query is fast
The cost is not the queries, it is the round trips. Each one pays:
- network latency to the database and back
- query parsing and planning
- a connection-pool checkout
- in many frameworks, object materialisation per result
Call that 1 ms of fixed overhead on the same host, and several milliseconds across a network or an availability zone. Four hundred of them is a second or two spent almost entirely on overhead, with the actual data access being negligible.
This is why an index does not fix N+1. The queries are already using one. The problem is the count, not the cost.
How it gets into code
Almost always through an ORM’s lazy loading, which is a feature doing exactly what it was designed to do:
departments = Department.all # 1 query
for d in departments:
print(d.name, len(d.employees)) # 1 query per iteration, invisibly
Nothing in that loop looks like a database call. That is the whole trap: the expensive thing is an attribute access.
It also happens without an ORM, in any code shaped as “fetch the ids, then loop and fetch the details” — including the common case of a service calling another service once per row.
Fix 1: one join
SELECT d.name AS department, e.name AS employee
FROM department d
LEFT JOIN employee e ON e.department_id = d.id
ORDER BY d.name, e.name;
One query, all the data. LEFT so departments with no employees survive, which
is the outer-join point.
The caveat is the one from the grain lesson: the result is one row per employee, not per department, so the calling code has to group it. And if you join two separate one-to-many relationships this way, they multiply — which is why this fix does not scale to several child collections.
Fix 2: one aggregate
When you only need a summary, aggregate in the database rather than counting in the application:
SELECT d.name AS department, count(e.id) AS headcount
FROM department d
LEFT JOIN employee e ON e.department_id = d.id
GROUP BY d.name
ORDER BY d.name;
count(e.id) and not count(*), for the reason in
GROUP BY and HAVING — Research would otherwise show
1 instead of 0.
Fix 3: two queries, batched
This is the fix ORMs call eager loading or preloading, and it is the one that scales to several collections:
SELECT id, name FROM department ORDER BY name;
SELECT department_id, id, name
FROM employee
WHERE department_id IN (1, 2, 3, 4)
ORDER BY department_id, name;
Two queries regardless of how many departments there are. The application stitches them by key, which is a hash map and costs nothing.
Two queries beats one join when there are multiple child collections. Three children means four queries — rather than one join that multiplies three relationships together and returns a result the size of their product.
The one thing to watch: an IN list of fifty thousand ids is its own problem.
Batch it in chunks of a few hundred to a few thousand.
How to find it
The symptom is a shape, not a number: query count scaling with result size.
- Log the query count per request and alert on it. An endpoint whose count varies with the size of its response has an N+1 in it.
- ORM query loggers, or
pg_stat_statementsordered bycallsrather than by total time — N+1 queries have enormous call counts and tiny per-call times. - In review: any loop whose body touches a related object.
Sorting by total time hides it, because the time is spread across hundreds of
thousands of individually trivial calls. Sorting by calls finds it
immediately.
Try it
The join and the batched pair both run in the SQL playground. You cannot feel the latency on a local WASM engine — there is no network — which is itself the lesson: N+1 is invisible in development and obvious in production, because development has no round trips worth paying.
Drill it with Latest order per customer in one query, which is the 1 + N loop above written as a single statement.
The service-to-service version of the same problem is a system-design concern; the HLD fundamentals cover fan-out and batching at that level.
Interview questions
1. What is the N+1 query problem? One query to fetch a collection, then one additional query per item in it. The query count grows with the result size.
2. Why does adding an index not fix it? Because each individual query is already fast and usually already indexed. The cost is per-round-trip overhead — latency, parsing, pool checkout — multiplied by the number of queries. The count is the problem.
3. Give three ways to fix it.
A single join; an aggregate computed in the database; or two batched queries
with an IN list, stitched by key in the application.
4. When is the batched two-query form better than one join? When there are several child collections. Joining them all multiplies the relationships together and returns rows proportional to the product, while batching costs one query per collection.
5. How would you detect N+1 in a running system?
Look for query count scaling with response size — log queries per request, or
sort pg_stat_statements by calls rather than total time. Sorting by time
hides it, because each call is trivially fast.
6. Why is N+1 so often invisible in development? Because development runs against a local database with negligible latency and a tiny dataset, so the round-trip overhead the bug consists of is near zero and the loop is short. It appears when latency and row counts both grow.
Next
That closes Part 3. Transactions and isolation levels opens Part 4, where two queries start interfering with each other.