Skip to content

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.

24 min read0/5 questions

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.

N+1 versus one batched query
AppDatabaseSELECT * FROM orders LIMIT 200200 rowsSELECT * FROM customers WHERE id = 11 row... 199 more, one per orderSELECT * FROM customers WHERE id = ANY($1)all customers needed

One query for the list. Fast.

1/7

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=True in 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 enormous calls and a tiny mean time, such as SELECT ... FROM customers WHERE id = $1 called 40 million times a day.

SQLite's set_trace_callback gives you the same visibility as ORM echo, so you can count queries:

Pythonn_plus_one.py
from shopdb import connectdb = connect() log = []db.set_trace_callback(log.append) # called with every SQL statement run # N+1: one query for orders, then one per order for its customerlog.clear()orders = db.execute("SELECT id, customer_id FROM orders ORDER BY id").fetchall()names = {}for order_id, customer_id in orders: names[order_id] = db.execute( "SELECT name FROM customers WHERE id = ?", (customer_id,)).fetchone()[0]print("N+1:", len(log), "queries")print(" first two:", log[0], "|", log[1]) # Fix 1: one JOINlog.clear()rows = db.execute("""SELECT o.id, c.name FROM orders o JOIN customers c ON c.id = o.customer_id ORDER BY o.id""").fetchall()print("JOIN:", len(log), "query,", len(rows), "rows") # Fix 2: load the list, then batch the related rows with IN (...)log.clear()orders = db.execute("SELECT id, customer_id FROM orders ORDER BY id").fetchall()ids = sorted({customer_id for _, customer_id in orders})marks = ",".join("?" * len(ids))customers = dict(db.execute(f"SELECT id, name FROM customers WHERE id IN ({marks})", ids))print("IN batch:", len(log), "queries for", len(ids), "distinct customers")print(" same answer:", {o: customers[c] for o, c in orders} == names)
Output
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 (IN or = 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 what selectinload does, 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.

OFFSET drift when a row is inserted between pages
p9
0
p8
1
p7
2
p6
3
p5
4
p4
5
p3
6
page = 1offset = 0limit = 3

Newest first. Page 1 is LIMIT 3 OFFSET 0: p9, p8, p7.

1/4

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 add id as a tiebreaker in both the ORDER BY and 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-expanded created_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:

Pythonkeyset_vs_offset.py
import random, timefrom shopdb import connectdb = connect()random.seed(2) db.execute("CREATE TABLE feed (id INTEGER PRIMARY KEY, created_at TEXT NOT NULL, body TEXT)")db.executemany("INSERT INTO feed VALUES (?, ?, ?)", ( (i, time.strftime("%Y-%m-%d %H:%M", time.gmtime(1767225600 + (i // 3) * 60)), f"post {i}") for i in range(1, 100_001))) # three posts share each minute, so ties happendb.execute("CREATE INDEX ix_feed_created_id ON feed (created_at, id)") OFFSET_SQL = """SELECT id, created_at, body FROM feed ORDER BY created_at DESC, id DESC LIMIT 20 OFFSET ?"""KEYSET_SQL = """SELECT id, created_at, body FROM feed WHERE (created_at, id) < (?, ?) ORDER BY created_at DESC, id DESC LIMIT 20""" def ms(sql, params): start = time.perf_counter() rows = db.execute(sql, params).fetchall() return rows, (time.perf_counter() - start) * 1000 for page in [1, 500, 2500, 4900]: offset = (page - 1) * 20 rows, offset_ms = ms(OFFSET_SQL, (offset,)) # the cursor is the last row of the previous page before = db.execute(OFFSET_SQL, (offset - 20,)).fetchall()[-1] if page > 1 else None keyset_rows, keyset_ms = ms(KEYSET_SQL, (before[1], before[0])) if before else (rows, offset_ms) assert keyset_rows == rows print(f"page {page:>4}: OFFSET {offset_ms:6.2f} ms keyset {keyset_ms:6.3f} ms") print(db.execute("EXPLAIN QUERY PLAN " + KEYSET_SQL, ("x", 1)).fetchone()[3])
Output
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 description and the jsonb blob that this screen never shows.
  • No index-only scans. A query that needs id, status, created_at can 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'::regclass returns the planner's estimate, updated by VACUUM and ANALYZE. For a filtered count, some teams parse the rows estimate from EXPLAIN. 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:

Pythonbatch_writes.py
import os, sqlite3, time path = "/tmp/batch_demo.db"if os.path.exists(path): os.remove(path)db = sqlite3.connect(path)db.execute("CREATE TABLE readings (id INTEGER PRIMARY KEY, sensor TEXT, value REAL)")db.commit()rows = [(f"s{i % 50}", i * 0.5) for i in range(3000)] start = time.perf_counter()for row in rows: db.execute("INSERT INTO readings (sensor, value) VALUES (?, ?)", row) db.commit() # one transaction per rowone_by_one = time.perf_counter() - start start = time.perf_counter()with db: # one transaction for all db.executemany("INSERT INTO readings (sensor, value) VALUES (?, ?)", rows)batched = time.perf_counter() - start print(f"one transaction per row: {one_by_one * 1000:7.1f} ms")print(f"one batched transaction: {batched * 1000:7.1f} ms")print("rows:", db.execute("SELECT count(*) FROM readings").fetchone()[0])
Output
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.
  • COPY for bulk loads. It streams rows in one command and is the fastest way in; psycopg 3 exposes it as cursor.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 transaction in pg_stat_activity are the classic symptom: the application ran BEGIN, 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 transaction

Give 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 CONCURRENTLY rebuilds 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

Quick check
An endpoint returns 100 customers, each with all of their orders (some have hundreds). Which SQLAlchemy loading strategy is usually best for the orders?
Need a nudge? A hint rules out a wrong answer.
Predict the outputPython

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)
Need a nudge? Hints walk you through it.
Match the pairs0/5 matched

Match each symptom to the pattern that fixes it.

Choose an item, then its match on the other side.
Quick check
A keyset query uses WHERE created_at < $1 ORDER BY created_at DESC LIMIT 20. What goes wrong?
Need a nudge? A hint rules out a wrong answer.
Put it in order5 steps

Order the steps for safely backfilling a new column on a 100-million-row table.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
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.