ORMs and the N+1 problem
one query for the list, one per row for the details. spotting it, and fixing it with a join.
- address
- everything.scale.orms_and_n_plus_one
- part
- part 17, scale and distribution
- chapter
- chapter 2 of 10
- reading time
- 7 min
an ORM that loads a list and then touches a relation on each row sends 1 + N queries: one for the list, one per row. each query is fast, so nothing looks slow, but every one pays a round trip, a parse, a plan and an executor start. eager loading asks for the related rows up front, with a join or one WHERE id = ANY($1) query, so the count stops growing with N.
the picture
you know how a page that renders 100 orders makes 101 queries, and each one shows up in the logs at 0.1 ms, and the page still takes ages? no query is slow. there are just a lot of them.
think of a waiter who takes your table's order one dish at a time, walking back to the kitchen after each (lazy loading), against one who writes down the whole table's order and walks once (eager loading). the kitchen cooks the same food either way. the walking is the difference.
101 statements. each one pays a round trip, so at 0.5 ms the network alone adds 51 ms, whatever the database does.
on one machine, with almost no network between the app and the database, the 101-statement page took about 4.5 ms, the single join about 1.4 ms, and the two-statement eager load about 0.9 ms (medians of 300 page loads each). put a real network between them and multiply 101 by your round trip.
what the ORM sends
here's the shape in most ORMs. it reads like a loop over objects; it runs like a loop over queries:
orders = Order.latest(100) # 1 query
for order in orders:
print(order.id, order.items.sum("qty")) # 1 query per order, on first touchSELECT id FROM orders ORDER BY ordered_at DESC, id LIMIT $1; -- once
SELECT sum(qty) FROM order_items WHERE order_id = $1; -- 100 timesthe relation is lazy: the ORM fetches order.items the first time you touch it, for that one order. convenient in a script, and invisible in a template that touches it once per row.
one of those per-order queries, on its own, is as good as a query gets:
EXPLAIN (ANALYZE, BUFFERS, TIMING OFF, SUMMARY OFF, COSTS OFF)
SELECT sum(qty) FROM order_items WHERE order_id = 9999;an index scan on the primary key and three pages. EXPLAIN has nothing to say about it. the database even does the per-row part efficiently: here are all 100 lookups as one statement, done the same way (one index lookup per order, loops=100):
LATERAL join, so one EXPLAIN can count them: an index scan run 100 times. the database work of the N+1 is this; what the app adds is 100 round trips, parses and plans.so the pages aren't the problem. 384 pages for all the lookups, plus 89 for the list. the statements are.
N+1: 1 list query + 100 lookups
JOIN: 1 statement
= ANY: 1 list query + 1 lookup for all idseager loading, two ways
every ORM has a switch for this, under some name. two shapes come out of it:
SELECT o.id, sum(oi.qty) AS items
FROM (SELECT id FROM orders ORDER BY ordered_at DESC, id LIMIT 5) AS o
LEFT JOIN order_items AS oi ON oi.order_id = o.id
GROUP BY o.id
ORDER BY o.id;| idint4 | itemsint8 |
|---|---|
| 9996 | 5 |
| 9997 | 4 |
| 9998 | 5 |
| 9999 | 1 |
| 10000 | 6 |
the join shape: one statement, and the database matches parents to children. it's what django's select_related, SQLAlchemy's joinedload and Rails' eager_load produce. the catch is fan-out: join two one-to-many relations at once and the rows multiply.
SELECT order_id, sum(qty) AS items
FROM order_items
WHERE order_id = ANY ('{9996,9997,9998,9999,10000}'::int[])
GROUP BY order_id
ORDER BY order_id;| order_idint4 | itemsint8 |
|---|---|
| 9996 | 5 |
| 9997 | 4 |
| 9998 | 5 |
| 9999 | 1 |
| 10000 | 6 |
the second query shape: load the parents, collect their ids, then fetch every child in one query with IN (...) or = ANY($1). django's prefetch_related, SQLAlchemy's selectinload and Rails' preload work this way. two statements no matter how many rows, no fan-out, and with = ANY($1) the statement text stays the same for any number of ids, so it stays one entry in pg_stat_statements and one prepared statement.
spotting it
from the app: count queries per request. most frameworks can log them, and test suites can assert a maximum ("this page runs at most 3 queries"), which catches the regression the day someone adds a field to a template.
from the database: a statement with calls in the thousands and about one row per call, filtered on a foreign key. finding slow queries shows exactly that row in pg_stat_statements, captured from this same page.
keylines
- lazy relations in a loop send 1 + N queries.
- each one is fast; the round trips and per-query overhead are the cost.
- eager load with a join, or with one
= ANY($1)query for all ids. - a join fixes the round trips but can still pick a bigger plan. check it.
- count queries per request in tests, and look for calls ≈ rows in pg_stat_statements.