skip to content

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.

loading =
orders =
100
round trip =
0.5 ms
lazy (N+1)
55.0 ms
eager, JOIN
1.9 ms
eager, = ANY
1.9 ms

101 statements. each one pays a round trip, so at 0.5 ms the network alone adds 51 ms, whatever the database does.

work, timed on one machineround trips (N+1)round trips (eager)
model: the grey part is measured on one machine with the shop dataset and scaled by the number of orders; the coloured part is statements × the round trip you pick
one page of orders, three ways. pick a strategy, then drag the number of orders and the network round trip. the N+1 bar grows with both; the eager ones barely move.

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.

measured on this mac (m4 pro), node-postgres 8, a throwaway postgres 18.6 with the shop dataset, client and server on the same machine. the 100 latest orders and their item counts, 300 page loads each way over 127.0.0.1, named (prepared) statements, median per page load, two runs

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:

text
orders = Order.latest(100)          # 1 query
for order in orders:
    print(order.id, order.items.sum("qty"))   # 1 query per order, on first touch

the 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:

sqldb=shop
EXPLAIN (ANALYZE, BUFFERS, TIMING OFF, SUMMARY OFF, COSTS OFF)
SELECT sum(qty) FROM order_items WHERE order_id = 9999;
output, from postgres 18.6
EXPLAIN
Aggregate (actual rows=1.00 loops=1) Buffers: shared read=3 -> Index Scan using order_items_pkey on order_items (actual rows=1.00 loops=1) Index Cond: (order_id = 9999) Index Searches: 1 Buffers: shared read=3 Planning: Buffers: shared hit=32 read=4

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):

show =
actual rowsbuffer hitsbuffer reads
real output, postgres 18.6 (PGlite 0.5.12) · n-plus-one
the 100 follow-up lookups expressed as a 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.

predict the output
which one touches the fewest pages for the 100-order page?
text
N+1:        1 list query + 100 lookups
JOIN:       1 statement
= ANY:      1 list query + 1 lookup for all ids

eager loading, two ways

every ORM has a switch for this, under some name. two shapes come out of it:

sqldb=shop
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;
output, from postgres 18.6
SELECT 5
idint4itemsint8
99965
99974
99985
99991
100006
(5 rows)

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.

sqldb=shop
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;
output, from postgres 18.6
SELECT 5
order_idint4itemsint8
99965
99974
99985
99991
100006
(5 rows)

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.

N+1: statements101
join: statements1
= ANY: statements2
N+1: pages473
join: pages242
= ANY: pages94
real output, postgres 18.6 (PGlite 0.5.12) · n-plus-one
the same page, both ways, counted on the browser's postgres. statements are what the app sends; pages are shared buffers touched, from each plan's BUFFERS.

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.