Lesson 18 of 29Indexes and query performance
Query Patterns That Scale
Fix N+1 queries, replace OFFSET with keyset pagination, count and write in bulk sensibly, and keep transactions short, so features stay fast as tables grow.
Most slow queries in production were fast when they shipped. The orders page made one query per row, which was fine with eight test customers. Page 4,000 of the activity feed used OFFSET, which nobody clicked until a scraper did. A nightly job updated ten million rows in one statement and held locks for forty minutes. None of these are exotic; they are patterns, and the fixes are patterns too. This lesson collects the ones that come up again and again at work, shows each with a runnable measurement, and ends with a checklist you can use in code review.
N+1: death by a thousand round trips
The N+1 problem is one query to load a list, then one more query per item to load something related. You met it in Databases with SQLAlchemy. Here the focus is on how you find it in a real system and which fix to pick.
Each query is fast, often under a millisecond, so no single query shows up as slow. The cost is the round trips. With the database across a network, every query pays a fixed latency of roughly 0.2 to 1 ms before it does any work, plus driver and ORM overhead on both ends. A page that lists 200 orders with their customers pays that 201 times.
One query for the list. Fast.
How you detect it at work:
- Query counts per request. Many teams log or export the number of queries per request, and alert in tests when an endpoint exceeds a budget. A test that asserts "this endpoint runs at most 5 queries" catches N+1 before review does.
- ORM echo or debug logging in development (
echo=Truein SQLAlchemy, Django Debug Toolbar, Rails logs). Look for the same statement repeated with different ids. - APM traces in production show a request as a waterfall of hundreds of identical, tiny database spans.
pg_stat_statements: a query with enormouscallsand a tiny mean time, such asSELECT ... FROM customers WHERE id = $1called 40 million times a day.
SQLite's set_trace_callback gives you the same visibility as ORM echo, so you can count queries:
Press Run (⌘ Enter) to see what happens.The f-string in the last fix only builds a list of ? placeholders; the values still travel as parameters. In Postgres you do not need that trick: pass an array as one parameter, WHERE id = ANY($1), which also keeps the SQL text identical for any number of ids, so pg_stat_statements sees one query shape instead of one per list length.
Which fix to choose:
- JOIN when you need both sides in one result and the relationship is many-to-one (each order has one customer). In SQLAlchemy that is
joinedload. - A second batched query (
INor= ANY) for one-to-many collections. Joining a customer to 500 orders repeats the customer's columns 500 times; a separate query sends each row once. That is whatselectinloaddoes, and it is the usual default for collections. - Watch the batch size. A list of 50,000 ids makes a huge statement. Chunk it into groups of a few hundred or a few thousand, or join against the source query instead.
OFFSET pagination gets slower with every page
The obvious way to page through a feed is:
SELECT id, created_at, body FROM posts
ORDER BY created_at DESC, id DESC
LIMIT 20 OFFSET 40000;OFFSET 40000 does not jump to row 40,000. The database has no way to know where row 40,000 is, so it produces 40,020 rows in order and throws away the first 40,000. Page 1 is cheap, page 2,000 is two thousand times the work. Crawlers, exports and "load more" loops are what reach those pages.
OFFSET also drifts. If a new post arrives between page 1 and page 2, everything shifts down by one, and the last item of page 1 appears again at the top of page 2. Deletes do the opposite and silently skip an item.
Newest first. Page 1 is LIMIT 3 OFFSET 0: p9, p8, p7.
Keyset pagination (also called cursor or seek pagination) remembers the last row the client saw and asks for the rows after it:
SELECT id, created_at, body FROM posts
WHERE (created_at, id) < ($1, $2) -- the last row of the previous page
ORDER BY created_at DESC, id DESC
LIMIT 20;
CREATE INDEX ix_posts_created_id ON posts (created_at DESC, id DESC);Three details make it correct:
- The sort key must be unique. Many posts share a
created_at, so addidas a tiebreaker in both theORDER BYand the cursor. Otherwise rows with the same timestamp at a page boundary get skipped or repeated. - Use the row-value comparison
(created_at, id) < ($1, $2). It means "earlier timestamp, or same timestamp and smaller id", and planners can turn it into a single index range. It works in Postgres, MySQL and SQLite 3.15+. The hand-expandedcreated_at < $1 OR (created_at = $1 AND id < $2)is equivalent but some planners, SQLite included, cannot use the index for it. - A matching composite index on the sort columns, in the same order, so each page is a seek plus 20 index entries.
Run both on 100,000 rows:
Press Run (⌘ Enter) to see what happens.Both methods return identical pages (the assert checks it), but OFFSET time grows with the page number and keyset time stays flat. The plan line shows the cursor turned into a range search on the index.
The cursor itself should be opaque to clients. Encode the last row's sort values, for example as base64 of {"created_at": "...", "id": 123}, return it as next_cursor, and accept it back as ?cursor=.... Clients cannot build page numbers from it, and you can change the format later. Validate it like any input, because a client can send garbage. Some teams sign it with an HMAC to stop tampering.
Keyset is not free. You cannot jump straight to page 37, and the sort order is fixed by the index you built. Most products are fine with that: feeds, infinite scroll, APIs and exports all move forwards. Keep OFFSET for small, bounded lists such as an admin table capped at a few hundred rows, where page numbers matter more than speed.
SELECT * and wide rows
SELECT * feels harmless, but it has three costs at scale:
- Bytes. Every column travels over the network and through the driver, including the 30 kB
descriptionand thejsonbblob that this screen never shows. - No index-only scans. A query that needs
id, status, created_atcan be answered from a covering index.SELECT *needs every column, so it must visit the table. - Fragility. Adding a column changes the result of every
SELECT *, which breaks code that unpacks rows by position and views built on the table.
Name the columns you need, especially in hot queries and APIs. ORMs make this easy to forget; most have a way to load only some columns (load_only in SQLAlchemy).
Counting rows on big tables
"Showing 1 to 20 of 48,213,907 results" looks simple. In Postgres, an exact count(*) must find every visible row, because MVCC keeps several versions of rows and each transaction can see a different set. There is no stored row count to read. On a table with tens of millions of rows that is a full scan, or at best a full index-only scan, on every page load.
Options, from best to worst for a UI:
- Do not show it. "Next page" does not need a total.
- Cap it. Count at most 1,001 rows and show "1,000+":
SELECT count(*) FROM (
SELECT 1 FROM orders WHERE customer_id = $1 LIMIT 1001
) AS capped;- Estimate it. For a whole table,
SELECT reltuples::bigint FROM pg_class WHERE oid = 'orders'::regclassreturns the planner's estimate, updated by VACUUM and ANALYZE. For a filtered count, some teams parse therowsestimate fromEXPLAIN. Both are approximate. - Maintain it. Keep counts in a summary table updated by your application, a trigger or a periodic job, when the number really must be exact and fast.
MySQL InnoDB has the same problem for the same reason. SQLite has no stored count either.
Writing in bulk
Inserting one row per statement, each in its own transaction, pays the round trip and the commit (a log flush to disk) every time. Batching both is often 10 to 100 times faster:
Press Run (⌘ Enter) to see what happens.In the browser the "disk" is memory, so the gap here understates it. On a real disk with a network between you and the database it is much larger. In Postgres the tools are:
- Multi-row
INSERT ... VALUES (...), (...), ...for hundreds to a few thousand rows per statement. COPYfor bulk loads. It streams rows in one command and is the fastest way in; psycopg 3 exposes it ascursor.copy().- Arrays with
unnest:INSERT INTO t (a, b) SELECT * FROM unnest($1::bigint[], $2::text[])sends any number of rows as two parameters. - Driver batching such as
executemany. How many round trips it saves depends on the driver, so check its documentation.
The opposite mistake is doing too much in one statement. UPDATE events SET archived = true WHERE created_at < '2025-01-01' on 80 million rows runs as one transaction: it locks every row it touches until the end, generates a huge burst of WAL that replicas must replay, and leaves 80 million dead row versions for VACUUM. Chunk it:
-- run repeatedly from a script until it updates 0 rows
UPDATE events SET archived = true
WHERE id IN (
SELECT id FROM events
WHERE created_at < '2025-01-01' AND NOT archived
ORDER BY id
LIMIT 5000
);Each batch commits quickly, other work keeps flowing, and you can stop and resume. Pause briefly between batches if replicas fall behind.
Keep transactions short
A transaction that stays open is a quiet source of trouble in Postgres:
- It holds every lock it has taken, so other writers to those rows wait.
- It holds back VACUUM. Dead row versions newer than the oldest open transaction's snapshot cannot be removed, anywhere in the database. One forgotten session can bloat every busy table.
- Sessions shown as
idle in transactioninpg_stat_activityare the classic symptom: the application ranBEGIN, did a query, then went off to call a payment API or wait for a user.
The rules: never hold a transaction open across a network call to another service or across user think-time, and do slow work before or after the transaction, not inside it. Transactions themselves are the subject of Transactions and ACID. Then add guard rails per role, so a runaway query or a leaked session is killed instead of hurting everyone:
ALTER ROLE web_app SET statement_timeout = '5s';
ALTER ROLE web_app SET idle_in_transaction_session_timeout = '30s';
ALTER ROLE web_app SET lock_timeout = '2s';
-- Postgres 17+ also has transaction_timeout for the whole transactionGive batch jobs and migrations their own role with different limits. A report that legitimately takes two minutes should not share the web app's five-second ceiling, and a migration should have a short lock_timeout so it fails fast instead of queueing behind a long query and blocking everything behind it.
Caching and precomputing
When the same expensive answer is needed over and over, stop computing it per request.
- Materialised views store a query's result as a table. Good for dashboards that can be a few minutes stale.
REFRESH MATERIALIZED VIEW CONCURRENTLYrebuilds it without blocking readers, but it requires a unique index on the view, and each refresh recomputes the whole query.
CREATE MATERIALIZED VIEW daily_revenue AS
SELECT date_trunc('day', created_at) AS day, sum(total_cents) AS revenue_cents
FROM orders WHERE status IN ('paid', 'shipped')
GROUP BY 1;
CREATE UNIQUE INDEX ON daily_revenue (day);
REFRESH MATERIALIZED VIEW CONCURRENTLY daily_revenue; -- e.g. every 10 minutes- Summary tables that you update incrementally (add today's numbers) when a full refresh is too slow.
- An application cache such as Redis for hot reads, with the invalidation trade-offs covered in Redis and Caching.
- Read replicas to take reporting load off the primary, accepting that they lag slightly.
Caching hides a slow query rather than fixing it, and every cache adds a staleness question. Fix the query first, then cache what is still expensive.
Practice
A new post arrives between the two page requests. What does this print?
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE posts (id INTEGER PRIMARY KEY)")
db.executemany("INSERT INTO posts VALUES (?)", [(i,) for i in range(1, 10)])
page = "SELECT id FROM posts ORDER BY id DESC LIMIT 3 OFFSET ?"
first = [r[0] for r in db.execute(page, (0,))]
db.execute("INSERT INTO posts VALUES (10)")
second = [r[0] for r in db.execute(page, (3,))]
print(first, second)Match each symptom to the pattern that fixes it.
WHERE created_at < $1 ORDER BY created_at DESC LIMIT 20. What goes wrong?Order the steps for safely backfilling a new column on a 100-million-row table.
- Tap the steps below in the right order.
- N+1 query
- One query for a list plus one per item for related data. Fixed with a JOIN or one batched query.
- keyset pagination
- Paging by remembering the last row's sort values and asking for rows after them. Constant cost per page and no drift.
- row-value comparison
- Comparing tuples such as
(created_at, id) < ($1, $2), which planners can serve with one composite index range. - opaque cursor
- An encoded token holding a page boundary that clients pass back but cannot interpret or construct page numbers from.
- COPY
- The Postgres command for streaming many rows in or out in one operation. The fastest way to bulk load.
- idle in transaction
- A session that opened a transaction and is not running a query. It holds locks and blocks VACUUM cleanup.
- materialised view
- A stored query result that you refresh on a schedule, trading freshness for fast reads.