The same customer-orders query returns its twenty rows in 23.929 milliseconds before an index exists and in 0.376 milliseconds after it, and nothing in the Python changed. Same SQL, same response shape, same rows. What changed is the plan PostgreSQL chose, and the plan changed because walking 200,000 rows stopped being something the planner could afford to ignore.
The cover image above is part of the evidence, not decoration: the composite-index before and after (23.929 ms to 0.376 ms), the one-round-trip ratio for LATERAL with statement logging off (23.33 times), the parallel speed-up once the spill was removed first (3.67 times) and the OFFSET block count against keyset (82,450 against 12) are all figures measured in sections 4, 7, 8 and 12 and repeated in the tables that produced them. The one proxy this article names and does not measure, PgBouncer, is listed with the rest of the scope below.
This guide is about the gap between that moment and a fix. It is written for engineers who can read a traceback but have not spent years inside a query planner, and it is built the way a production incident is built: reproduce the shape, measure it, change one thing, measure again, and keep the evidence. Every latency, row count and byte count below was produced by a script against a real PostgreSQL server; the tables are hand-written but every figure in them is filled in from the recorded result file of the experiment named beside it, and the plan text is quoted verbatim where the plan is the point rather than the timing. The complete set of scripts, JSON files and tests will be published with the companion repository; once that repository is published, the link will appear in the box at the end of this article. Until then the article is the record, not a pointer to one – a tuning guide that cannot be reproduced is only a rumour with tables.
TL;DR
- Read
EXPLAIN (ANALYZE, BUFFERS)before touching a setting. The plan names the problem; the settings only move its cost. - Match the index to the whole query: equality column first, sort column second, the returned column last or in
INCLUDE. - A covering index only skips the heap while the visibility map says the pages are clean. A single
UPDATEtakes that back untilVACUUMruns. - If a predicate wraps the column in a function, no ordinary index can serve it. Rewrite the predicate or index the expression, and prefer a half-open range over
date_trunc. - OFFSET pagination reads and throws away every skipped row. Keyset pagination reads one page.
- One query per parent is not a style preference; it is 200 round trips where one would do, and the database does the same work either way.
- A pool of 5 connections is empty after 5 calls that forget to release. The next caller waits out the acquire timeout and fails with an error that blames the pool.
- Retry only transient SQLSTATE classes, with bounded attempts. Retrying a syntax error multiplies the damage.
- Deadlocks are a lock-order bug, not a timeout to raise: locking rows in a fixed order removed every deadlock in the measured batch.
- Bigger pools do not add throughput; they add queueing. On a CPU-bound two-core box, a pool of 20 made each query 4.7 times slower inside the database than a pool of 5 and moved no more queries per second.
What this guide covers
- What was measured, on what, and what was not
- The triage matrix: four symptoms, four plans
- Reading EXPLAIN (ANALYZE, BUFFERS) without a textbook
- Build the index the query asks for
- Make the index able to answer alone
- Stop hiding the column from the index
- Paginate by key, not by offset
- One round trip instead of N
- Pools leak, and nothing tells you
- Locks, waiting, and the deadlock you can delete
- The write path, and what it leaves behind
- Three settings, measured on real queries
- The runbook: four questions the built-in views can answer
- The module behind these numbers, and the tests that keep them true
- Frequently asked questions
- The order to do this in
1. What was measured, on what, and what was not
The measurements come from a userland PostgreSQL cluster: the official 16.2 server binaries from the pgserver wheel, initialised with initdb and started on 127.0.0.1:55432 with two non-default startup options. track_io_timing is on, so the I/O timings printed in the plans are measured rather than estimated. The first pass also ran with log_min_duration_statement = 0 – a log line for every statement – which is a real setting but not a production one, and it sits directly on the path of the statements this article is about: it inflates anything that sends many small statements. The read comparisons in section 8 and the write comparison in section 11 were therefore measured a second time with logging off, in two rounds in opposite order, and their tables carry one column per condition instead of a footnote about it. It is a genuine server – the same planner, executor, buffer manager and lock manager as production – but it is a small one, and every absolute time in this article should be read as “this machine, this dataset” rather than as a number to expect on your hardware. What transfers is the shape: which plan appears, why, what changes when the query or the index changes, and which counter moves.
| Item | Measured value | How it was read |
|---|---|---|
| PostgreSQL | 16.2 | SHOW server_version |
| CPUs visible to the container | 2 | os.cpu_count() |
| Memory | 1.45 GiB | /proc/meminfo |
shared_buffers | 163848kB | pg_settings |
work_mem | 4096kB | pg_settings |
max_connections | 100 | pg_settings |
effective_cache_size | 5242888kB | pg_settings |
| Database size | 157,204,480 bytes | pg_total_relation_size sum |
orders | 200,000 rows, 26 MB | row count and pg_total_relation_size |
order_items | 800,000 rows, 63 MB | row count and pg_total_relation_size |
customers | 50,000 rows | row count |
events | 400,000 rows, JSONB payload | row count |
| Heaviest customer | 20,135 orders | GROUP BY customer_id ORDER BY count DESC |
| Orders per tail customer (mean) | 2.321 orders | average over customers above the whale set |
| Statements timed per case | 30 | warm-up then perf_counter around each call |
The dataset is deliberately skewed, because a uniform dataset hides the most common production plan regression: a query that is perfectly planned for the median customer and badly planned for the whale. 5 customers own 99,568 of the 200,000 orders, while the remaining 43,265 customers average 2.321 orders each. Every query in this article is run twice for that reason – once with the whale’s id, once with a tail customer’s id – and the two answers are often different.
Out of scope, stated plainly. This guide contains no measurement of pg_stat_statements: the bundled build ships no contrib modules, so the extension is not available in this cluster and any numbers attributed to it would be invented. The runbook in section 13 uses only the always-present views (pg_stat_activity, pg_stat_database, pg_stat_user_tables, pg_stat_user_indexes) and says which question each answers. It contains no PgBouncer, no connection-proxy latency, no cloud block storage behaviour, no replication, and no query rewriting by an ORM version other than SQLAlchemy 2.0.57. It also does not measure your workload: a 2-vCPU container with 1.45 GiB of RAM and a 157,204,480-byte database is a workbench, not a production estate.
2. The triage matrix: four symptoms, four plans
“The database is slow” is not a diagnosis. In practice one of four shapes is happening, and each leaves a different fingerprint in EXPLAIN and in pg_stat_activity. The matrix below is the one used for the rest of this article; the measured value in the third column is the number that separates the shapes in this dataset, and the reference to the section where it is reproduced.
| Symptom you see | What the plan says | Measured here | Section |
|---|---|---|---|
| One endpoint slow, database CPU moderate | Seq Scan or Bitmap Heap Scan over the table, many shared reads | 23.929 ms per call before, 0.376 ms after the index | section 4 |
| Latency spikes with no query change | Index Only Scan with a growing Heap Fetches count | 10,108 heap fetches after an UPDATE; one VACUUM left 17 (it is 0 before the update) | section 5 |
| Request waits, then fails with a pool timeout | No plan at all: the statement is never sent | 5 leaked connections exhausted a pool of 5 | section 9 |
| Writes hang, then one transaction dies | wait_event_type = Lock, or SQLSTATE 40P01 | 542.2 ms waiting on one row; 38 deadlocks in one batch | section 10 |
The ordering matters. A pool timeout is usually the last symptom of a slow query, not a pool bug: callers hold connections for as long as the query takes, so fixing the query empties the queue. Resizing the pool first hides the problem for an hour and then multiplies it, which is why section 9 measures what a bigger pool actually bought here: 469.2 queries per second against 423.4, and a per-query service time 4.7 times higher inside the database. The request latencies in that run cannot be told apart – the two interquartile bands overlap – so the honest summary is no more throughput and more work per query, not a latency claim in either direction.
3. Reading EXPLAIN (ANALYZE, BUFFERS) without a textbook
One plan, one reading, then a routine you can apply to any query. This is the customer-orders query from section 4 as it ran before the index existed, executed with a cold cache so the read counts are visible:
Limit (cost=5699.48..5701.78 rows=20 width=25) (actual time=40.300..48.348 rows=20 loops=1)
Buffers: shared hit=89 read=2876
I/O Timings: shared read=19.589
-> Gather Merge (cost=5699.48..7086.27 rows=12059 width=25) (actual time=40.298..48.343 rows=20 loops=1)
Workers Planned: 1
Workers Launched: 1
Buffers: shared hit=89 read=2876
I/O Timings: shared read=19.589
-> Sort (cost=4699.47..4729.62 rows=12059 width=25) (actual time=17.663..17.666 rows=10 loops=2)
Sort Key: created_at DESC
Sort Method: top-N heapsort Memory: 27kB
Buffers: shared hit=89 read=2876
I/O Timings: shared read=19.589
Worker 0: Sort Method: quicksort Memory: 25kB
-> Parallel Seq Scan on orders (cost=0.00..4378.59 rows=12059 width=25) (actual time=0.010..16.082 rows=10068 loops=2)
Filter: (customer_id = 4)
Rows Removed by Filter: 89932
Buffers: shared hit=32 read=2876
I/O Timings: shared read=19.589
Planning:
Buffers: shared hit=40
Planning Time: 0.316 ms
Execution Time: 48.446 ms
Read it from the inside out, because that is the order in which work happens. The deepest node is a Parallel Seq Scan, and loops=2 does not mean the table was read 2 times. In a parallel plan PostgreSQL hands each process a different range of the table’s blocks – here the leader and one worker, because Workers Launched is one – and loops counts the processes that ran the node. The row figures are per-process averages, so each process returned about 10,068 rows to the filter and threw away about 89,932: together that is the table read once, not twice, with the total in Rows Removed by Filter. That number is the whole diagnosis. The query wants twenty rows; the scan examined every row of the table to find them, then sorted what survived so the Limit could take the top twenty. The sort spilled nothing and the plan is not pathological – it is exactly what a planner without a usable index must do.
The second line is the other half of the story. Buffers: shared hit=89 read=2876 means most of what the scan touched was not in shared_buffers and had to come from the operating system’s page cache or from storage; the I/O Timings line attributes most of the read work to the storage path rather than to CPU. On this container that read path is quick. On a volume with real latency the same plan spends most of its time waiting for reads, which is why a plan review that ignores buffers reviews only half of the query.
Now the same query one index later:
Limit (cost=0.42..12.61 rows=20 width=25) (actual time=0.005..0.011 rows=20 loops=1)
Buffers: shared hit=22
-> Index Scan using orders_customer_created_idx on orders (cost=0.42..12287.62 rows=20160 width=25) (actual time=0.004..0.009 rows=20 loops=1)
Index Cond: (customer_id = 4)
Buffers: shared hit=22
Planning Time: 0.018 ms
Execution Time: 0.017 ms
Two nodes instead of the four above, Index Cond instead of Filter, 22 buffer hits instead of thousands of reads, and no sort at all: the index already stores the rows in the order the ORDER BY asked for, so the Limit can stop after twenty. The measured median for the warm-cache version of this query fell from 23.929 ms to 0.376 ms (section 4 has both parameters and the ratio). The Execution Time printed inside that plan is the server’s own clock, so it reads microseconds where the median includes the client round trip – the plan is quoted for its shape, the table for its timing.
| Look at this first | What it tells you | What to do when it is bad |
|---|---|---|
Rows Removed by Filter | The scan touched rows the query did not want | Add or reshape the index so the predicate becomes an Index Cond |
Index Cond versus Filter | Whether the index did the selection or the executor did | Check column order and whether the predicate wraps the column in a function |
Sort node above a scan | The index did not supply the requested order | Put the sort column into the index, in the direction the query orders |
actual rows versus rows | The planner’s estimate was wrong, so its cost model was wrong | ANALYZE, raise the statistics target, or use a multicolumn statistic |
loops greater than one | The node ran once per outer row (a nested loop), or once per parallel process | Compare the multiplied cost; for a parallel node, remember the printed rows are per process |
Buffers: read | Work that reached storage rather than memory | Shrink the working set, or accept it and tune for fewer reads |
Heap Fetches on an Index Only Scan | Rows the index-only scan still had to fetch from the heap: the page is not marked all-visible, or the index still holds dead entries | VACUUM; if it keeps happening, VACUUM (VERBOSE) and look for index scan bypassed, then check the writer that keeps dirtying pages |
Workers Launched: 0 with a parallel plan | The plan wanted parallelism and got none | Check max_worker_processes and max_parallel_workers, not just the per-gather setting |
The helper below is the one used throughout this article’s suites. It runs EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON), flattens the node list, and surfaces the four fields worth asserting on: the node types, the indexes named, the buffer counts and the execution time. Keeping it in one function matters because plan assertions then read like tests rather than like psql archaeology.
import json
from typing import Any, Iterable, Mapping
import asyncpg
def _load_plan(payload: Any) -> list[dict[str, Any]]:
if isinstance(payload, str):
return json.loads(payload)
return payload
def walk_plan(node: Mapping[str, Any]) -> Iterable[Mapping[str, Any]]:
yield node
for child in node.get("Plans", []):
yield from walk_plan(child)
def plan_node_types(root: Mapping[str, Any]) -> list[str]:
return [node["Node Type"] for node in walk_plan(root)]
async def explain(
conn: asyncpg.Connection, sql: str, *args: Any, analyze: bool = True
) -> dict[str, Any]:
"""EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) as a flat dict the tests can assert on."""
prefix = "EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) " if analyze else "EXPLAIN (FORMAT JSON) "
row = await conn.fetchrow(prefix + sql, *args)
document = _load_plan(row[0])[0]
root = document["Plan"]
return {
"nodes": plan_node_types(root),
"indexes": sorted({n["Index Name"] for n in walk_plan(root) if n.get("Index Name")}),
"execution_ms": round(document.get("Execution Time", 0.0), 3),
"planning_ms": round(document.get("Planning Time", 0.0), 3),
"hit_blocks": root.get("Shared Hit Blocks", 0),
"read_blocks": root.get("Shared Read Blocks", 0),
"rows": root.get("Actual Rows", 0),
}
One warning that saves an afternoon: EXPLAIN ANALYZE executes the statement. On an UPDATE or DELETE that means it writes. Run those inside a transaction you intend to roll back, or use plain EXPLAIN and accept that you are reading estimates instead of measurements.
4. Fix one: build the index the query asks for
The query is a customer’s latest orders: an equality on customer_id, an ordering by created_at DESC, and a limit. The index that serves all three is not an index on customer_id – that one finds the rows but leaves the sort to the executor – and it is not an index on created_at, which cannot narrow the range by customer. It is the pair, in the order the query uses them.
CREATE INDEX orders_customer_created_idx
ON orders (customer_id, created_at DESC);
-- Returned columns that are not in the key can ride along in the leaf pages:
CREATE INDEX orders_customer_status_idx
ON orders (customer_id, created_at DESC) INCLUDE (status);
-- A predicate that wraps a column needs an expression index...
CREATE INDEX customers_lower_email_idx ON customers (lower(email));
-- ...and a half-open range needs an index whose first column is that column.
CREATE INDEX orders_created_at_idx ON orders (created_at);
| Case | Plan before | Median before | Plan after | Median after | Speed-up |
|---|---|---|---|---|---|
| Whale customer, 20,135 orders | Limit / Sort / Seq Scan | 23.929 (22.292–26.93) ms | Index Scan | 0.376 (0.33–0.43) ms | 63.64x |
| Tail customer, 4 orders | Seq Scan plus sort | 20.926 (20.091–21.981) ms | Bitmap Index Scan plus sort | 0.322 (0.293–0.352) ms | 64.99x |
| Index size | – | – | 6184 kB | – | – |
| Buffer hits per call, whale | 2937 | – | 22 | – | – |
Both parameters improved, and they improved for different reasons, which is worth noticing. The whale’s case switched to a plain Index Scan that walks the index in created_at DESC order and stops at twenty rows: 63.64 times faster. The tail customer, who owns 4 orders, got a Bitmap Index Scan and still sorted – the planner judged that reading a handful of heap pages in bulk and sorting four rows was cheaper than the index walk, and at 0.322 ms it was right. The lesson is not “the index makes every plan an index scan”. It is that the index removed the sequential scan from both plans, and the planner is free to choose the cheapest shape from there. The two figures in brackets are the 25th and 75th percentile of the same 30 calls, and the before and after bands do not overlap at all – which is the reason to believe the change, more than the size of the ratio.
Index size is the tax. The composite index occupies 6184 kB for 200,000 orders, roughly a quarter of the table’s 26 MB, and every write to orders now maintains it. On a read-heavy table that is a bargain. On a table that takes more writes than reads, measure the write cost before adding a fourth index “just in case” – section 11 shows how the write path was measured here.
Column order is not a detail
The tempting mistake is to build the index in the order the columns appear in the ORDER BY, because that is the order the query reads them. PostgreSQL will still use such an index – a non-leading column can appear as an index condition – but it has to walk the index in its stored order and test every entry until the limit is satisfied. Whether that is cheap depends entirely on how common the value is, which is why the same wrong index is invisible in staging and painful on the long tail.
| Index on the copy | Whale, execution | Tail, execution | Tail blocks touched |
|---|---|---|---|
| none | 21.032 ms | 20.079 ms | 2937 |
(created_at DESC, customer_id) | 0.035 ms | 1.739 ms | 773 |
(customer_id, created_at DESC) | 0.018 ms | 0.021 ms | 7 |
Read the last column twice. For the whale the reversed index is indistinguishable from the correct one – 0.035 ms against 0.018 ms – because one row in ten belongs to that customer, so a short walk down the index finds twenty matches. For the tail customer the reversed index costs 82.8 times more than the right one, because finding four matches means walking through the entries of tens of thousands of other customers first. A benchmark that only uses your biggest customer will tell you the index order does not matter. Your monitoring, which is dominated by small customers, will disagree.
Partial indexes, when the predicate is always there
If a query always filters on the same status – “unshipped orders”, “open tickets” – an index that contains only those rows is smaller and stays in cache longer. The rule is the same as any index: it must match the predicate the query actually sends, literally. An index WHERE status = 'pending' cannot serve WHERE status IN ('pending', 'paid'), and a planner that cannot prove the predicate matches will fall back to the full index or to the heap. In this dataset 200,000 orders carry 4 statuses, and paid is 92.0 percent of them while the rarest, cancelled, is 2,036 rows – exactly the skew that makes a partial index on the rare statuses worth measuring before committing to it.
Two operational notes, both of which cost a production outage somewhere every year. CREATE INDEX takes a lock that blocks writes for the duration; CREATE INDEX CONCURRENTLY does not, but it can fail halfway and leave an invalid index behind that still costs write time, so check pg_index.indisvalid afterwards. And an index that no query uses is not free: it is maintained on every insert, update and delete. Section 13 shows the query that lists which indexes have actually been used.
5. Fix two: make the index able to answer alone
An Index Scan finds a row’s location in the index and then fetches the row from the heap. An Index Only Scan skips the second step – if the index contains every column the query needs, and if the visibility map says the page the row lives on contains no tuples that an older transaction might still need to see. That second condition is the part people forget, and it is why an index-only scan can look like a regression six hours after a deployment that only added an index.
Two queries, four states of the same table. The first asks for the whale customer’s newest twenty orders including status, which the plain composite index does not carry. The second counts that customer’s orders by status, touching 20,135 index entries. The first column is the baseline the other three are bought against: the composite index on its own, with no INCLUDE.
| State of the index and the table | Recent-20 median | Blocks, recent-20 | Heap fetches, recent-20 | Status-count median | Heap fetches, count | Blocks, count |
|---|---|---|---|---|---|---|
Composite index only, no INCLUDE | 0.257 (0.243–0.304) ms | 22 | not an index-only plan | 6.843 (6.592–7.162) ms | bitmap heap scan, not counted | 2,955 |
INCLUDE (status), clean visibility map | 0.296 (0.294–0.299) ms | 4 | 0 | 2.884 (2.827–2.934) ms | 0 | 104 |
| Same index, 1,977 rows just updated | 0.242 (0.236–0.35) ms | 24 | 20 | 5.26 (5.109–5.556) ms | 10,108 | 10,217 |
After VACUUM (ANALYZE) | 0.287 (0.276–0.307) ms | 4 | 0 | 2.914 (2.866–2.976) ms | 17 | 115 |
Read the small query with suspicion and the large one with interest. For the recent-20 query the wall-clock difference between the heap-reading plan and the index-only plan is in the wrong direction and inside the noise: 0.257 (0.243–0.304) ms without INCLUDE, 0.296 (0.294–0.299) ms with it, and the bands overlap. Twenty rows are a client round trip and a plan; no index shape is going to show up in that measurement. The honest signal is the block count, 22 against 4, and the heap fetches. That is also the trade: the covering index is a little larger and must be maintained on every write, and for a twenty-row lookup it buys pages rather than milliseconds.
The count query is where the index earns its keep, and the no-INCLUDE baseline shows why. Without status in the index the same statement cannot be answered from the index at all: the plan becomes a Bitmap Heap Scan, reads 2,955 blocks and takes 6.843 ms. With INCLUDE, the clean index answers it in 2.884 ms over 104 blocks. Then the visibility map went stale: 10,108 heap fetches and 10,217 blocks, 5.26 ms. The index did not change. The visibility map did.
The update in that experiment was deliberately gentle: it rewrote status to its own value, which still creates a new tuple version and marks the page dirty. That is what an application’s ordinary UPDATE does, and it is why the performance of a covering index is really the performance of your vacuum schedule. A cluster that vacuums promptly keeps the map clean and gets the fast plan; a cluster that defers vacuum gets index-only scans that read the heap on every call, while the plan still says Index Only Scan, which is the most confusing way a plan can lie to you.
After VACUUM the count query came back to 2.914 ms with 17 heap fetches. Do not read that as a guarantee: three further update-and-vacuum cycles on the same table left 0, 1,941 and 0 heap fetches. The cause is not a page whose visibility-map bit went missing – VACUUM VERBOSE reports dead but not yet removable: 0 in every state below – it is an index pass that VACUUM decided it did not need to make: dead item identifiers stay in the index, the pages they point at cannot be treated as all-visible on their behalf, and an index-only scan has to fetch those rows from the heap to find out they are dead. Skipped index pass, dead entries left behind, heap fetch: the three follow each other, and the first is the one the report names.
VACUUM treats its index pass as optional. When the heap pass finds nothing dead, it can skip cleaning the dead item identifiers out of the indexes, and it says so: index scan bypassed, with the number it left behind. An index-only scan cannot tell a dead entry from a live one without visiting the heap, so those identifiers become heap fetches. Experiment 30 walks the cycle once, from a clean table (0 heap fetches, index scan not needed): it updated 1,993 rows and vacuumed with the index cleanup switched off, the explicit form of the automatic decision, and the report answered with index scan bypassed: 43 pages from table ... have 1,839 dead item identifiers. The heap versions went (1,993 removed) and the identifiers stayed, and the count query reported 1,996 heap fetches against 0 before the update. A plain VACUUM immediately afterwards did not repair it, because it again found no dead heap tuples and skipped the index pass: still 1,839 identifiers, still 157 heap fetches. Only VACUUM (INDEX_CLEANUP ON) cleared them – 1,839 dead item identifiers removed, 0 heap fetches – and plain VACUUMs after that kept it at 0.
The practical reading is narrower and more useful than “vacuum more”: watch whether the index pass actually ran. On a table that takes updates, autovacuum may skip it for several cycles while index-only scans quietly pay for the stale entries, and VACUUM (VERBOSE) on that table answers the question in one line. The counter is a trend that should sit near zero, not a boolean you assert once and forget – and on a cached table it can even be cheap, which is exactly why the block count is the number to watch when the table is larger than memory.
6. Fix three: stop hiding the column from the index
A btree index answers questions about the values of a column. If the predicate asks about a function of that column, the index has nothing to look up: the planner must compute the function for every candidate row, which means reading the table. The two common cases in application code are a case-insensitive lookup and a day-bucketed timestamp, and the second one has a second trap under it: rewriting the predicate is necessary but not sufficient, because the range can only seek if an index starts with the column in the range.
| Predicate and index | What the planner can do | Median | Blocks touched | Speed-up |
|---|---|---|---|---|
WHERE lower(email) = $1, no expression index | Seq Scan, function evaluated per row | 6.072 (5.973–6.168) ms | 417 | – |
Same query, (lower(email)) index | Index Scan on the expression index | 0.16 (0.157–0.172) ms | 4 | 37.95x faster |
date_trunc('day', created_at) = $1 | Parallel Seq Scan behind an aggregate | 33.929 (33.823–34.017) ms | 2,908 | – |
Half-open range, only (customer_id, created_at DESC) exists | Index Only Scan; Index Cond on a column that is not the leading key, so every entry is tested | 9.707 (9.549–9.782) ms | 770 | 3.495x faster than date_trunc |
Half-open range, orders(created_at) added | Index Only Scan with a real range seek | 0.662 (0.611–0.728) ms | 5 | 14.663x faster than the row above |
| Rows the day range matches | 327 of 200,000, identical for the function and both ranges | |||
-- Rewrite the predicate: two comparisons instead of a function call.
-- Wrong: cannot use a btree on created_at
SELECT count(*) FROM orders
WHERE date_trunc('day', created_at) = DATE '2026-05-04';
-- Right: a half-open range, and the same rows
SELECT count(*) FROM orders
WHERE created_at >= DATE '2026-05-04'
AND created_at < DATE '2026-05-04' + INTERVAL '1 day';
-- ...and the index that lets the range seek instead of filtering everything
CREATE INDEX orders_created_at_idx ON orders (created_at);
-- Or index the expression the query actually uses, and keep the query as it is
CREATE INDEX customers_lower_email_idx ON customers (lower(email));
SELECT id FROM customers WHERE lower(email) = 'user01234@example.com';
The email case is the straightforward one: 37.95 times faster once the expression the query uses is the expression the index stores, for a 2008 kB index on 50,000 customers plus the write cost of maintaining it.
The date case is instructive, and it is the trap a first rewrite walks into. Rewriting date_trunc('day', created_at) = $1 as a half-open range does turn the parallel sequential scan (2,908 blocks, 33.929 ms) into an index-only scan, and it returns exactly the same 327 rows. But on this schema the only index on orders was (customer_id, created_at DESC), and created_at is not its leading column. PostgreSQL will happily print Index Cond for it – the condition is evaluated against every index entry – and that is the trap: the scan read all 773 pages of the index to find 327 rows, at 9.707 ms. With a dedicated index whose first column is created_at the same statement reads 5 pages and returns in 0.662 ms, 14.663 times faster. So the honest rule is two-part: make the predicate a range, and make sure some index leads with the column the range is on. The rewrite alone is not a fix, and “needs no new index” would be the wrong claim.
Two traps live under this heading. Comparing a timestamptz to a date resolves the date in the session’s time zone, so the same statement returns different counts for two clients with different TimeZone settings; send an explicit instants-inclusive range from Python instead of a bare date. And an implicit cast can hide a column the same way a function does: passing a string parameter to an integer column is harmless, but WHERE created_at::date = $1 is the date_trunc problem wearing a different hat.
7. Fix four: paginate by key, not by offset
LIMIT 20 OFFSET 195,000 is a request to produce 195,020 rows and discard 195,000 of them. Nothing about that is a bug – it is the definition of OFFSET – but at depth the work is proportional to the page number, and the page number grows with the data. The alternative uses the ordering key as the cursor: give me the rows after this id, twenty of them.
| Access pattern | Median, 30 calls | Blocks touched | Rows produced internally | Rows returned |
|---|---|---|---|---|
ORDER BY id LIMIT 20 OFFSET 195,000 | 22.532 (22.407–22.925) ms | 82,450 | 195,000 skipped, then twenty | 20 |
WHERE id > $1 ORDER BY id LIMIT 20 | 0.142 (0.136–0.168) ms | 12 | twenty | 20 |
The two statements returned the identical id range, 195,001 to 195,020, so this is not a comparison of different answers. One walked 82,450 buffer pages, the other 12, and the medians differ by a factor of 158.68. Both plans say Index Scan; the difference is entirely in how many entries the scan had to pass before the limit was satisfied, which is exactly what the plan does not print for you. The offset figure this run recorded is flattered by the cache: those pages were already in shared_buffers, so the scan paid for CPU rather than for reads. The block count is the number that travels – 82,450 pages walked to return twenty rows, against 12 – and on a table that no longer fits in memory that difference is paid in I/O.
That block count needs one caveat, because it is the number most likely to disagree with the same query on your own server. It counts buffer accesses, not distinct pages, and it depends on where the rows physically live. The same query and the same 200,000 rows, measured on three tables in experiment 31: on a copy whose heap order follows the primary key it touched 3,317 buffers and returned in 19.686 ms; on a copy of the same rows whose heap order does not follow the key – the shape a table takes after a series of updates and inserts has appended new row versions wherever they fit – it touched 195,498 buffers and needed 65.839 ms. Both copies hold 200,000 rows in 2,880 pages. Nothing changed but the order, and the scan went from one visit per page to roughly one visit per row. The live table in the table above sits between the two, because the sections before this one had already updated rows in it. Keyset does not care: 4 and 23 blocks, 0.208 and 0.354 ms, on the same two tables. That is the part of this comparison that transfers.
import re
from typing import Any, AsyncIterator, Sequence
import asyncpg
# a bare identifier, one item of a SELECT list, and a bound value's placeholder
_IDENTIFIER = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
_COLUMN_LIST_ITEM = re.compile(
r"^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)?"
r"(?:\s+AS\s+[A-Za-z_][A-Za-z0-9_]*)?$",
re.IGNORECASE,
)
_PLACEHOLDER = re.compile(r"\$(\d+)")
async def iter_keyset(
conn: asyncpg.Connection,
*,
table: str,
key: str = "id",
page_size: int = 500,
tiebreak: str | None = None,
columns: str = "*",
where: str = "",
where_args: Sequence[Any] = (),
start: Any = None,
descending: bool = False,
) -> AsyncIterator[list[asyncpg.Record]]:
"""Yield pages with a keyset cursor; values are bound, the cursor follows them."""
if page_size < 1:
raise ValueError("page_size must be >= 1")
if not table.replace("_", "").replace(".", "").isalnum():
raise ValueError(f"unexpected table name: {table!r}")
for column in (key, tiebreak):
if column is not None and not _IDENTIFIER.match(column):
raise ValueError(f"unexpected column name: {column!r}")
# columns is interpolated and checked; where is text too, but its values are bound
if columns.strip() != "*":
for token in columns.split(","):
if not _COLUMN_LIST_ITEM.match(token.strip()):
raise ValueError(f"unexpected column list item: {token.strip()!r}")
if where and any(bad in where for bad in ("'", '"', ";", "--", "/*", "\\")):
raise ValueError("a quote or a statement break belongs in where_args, not in where")
if {int(n) for n in _PLACEHOLDER.findall(where)} != set(range(1, len(where_args) + 1)):
raise ValueError("where placeholders must be $1..$n, one per where_args value")
direction = "DESC" if descending else "ASC"
operator = "<" if descending else ">"
order = f"{key} {direction}, {tiebreak} {direction}" if tiebreak else f"{key} {direction}"
cursor: Any = start
if tiebreak is not None and cursor is not None:
if not isinstance(cursor, (tuple, list)) or len(cursor) != 2:
raise ValueError("start must be a (key, tiebreak) pair when tiebreak is set")
first = len(where_args) + 1 # the cursor takes the placeholders after where_args
while True:
if cursor is None:
cursor_clause, cursor_args = "", []
elif tiebreak is not None:
cursor_clause = f"({key}, {tiebreak}) {operator} (${first}, ${first + 1})"
cursor_args = [cursor[0], cursor[1]]
else:
cursor_clause = f"{key} {operator} ${first}"
cursor_args = [cursor]
clauses = ([f"({where})"] if where else []) + ([cursor_clause] if cursor_clause else [])
clause = " AND ".join(clauses) if clauses else "TRUE"
sql = (f"SELECT {columns} FROM {table} WHERE {clause} "
f"ORDER BY {order} LIMIT {int(page_size)}")
rows = await conn.fetch(sql, *(list(where_args) + cursor_args))
if not rows:
return
yield rows
last = rows[-1]
cursor = (last[key], last[tiebreak]) if tiebreak is not None else last[key]
if len(rows) < page_size:
return
Two of those arguments are SQL text rather than parameters, and that is the one thing in this function that can be got wrong dangerously. table, key and tiebreak are checked against a plain-identifier pattern, and columns against a pattern that allows * or a comma-separated list of optionally qualified names with an optional alias. Values never travel inside that text: the predicate takes placeholders – where="status = $1" with where_args=["paid"] – and the cursor is numbered after them, so the argument order is always the predicate’s values first and the cursor last. A quote, a semicolon, a comment marker or a backslash inside where is refused, because that is what a pasted value or a second statement looks like, and the placeholder count is checked against where_args before anything is sent. The test suite asserts both halves: that a bound predicate pages exactly what OFFSET returns, and that placeholders which do not match the values are rejected rather than sent.
A cursor that keeps the tie-breaker in ORDER BY only, comparing a single column, looks right and pages a table of unique ids perfectly – which is why it survives review. On a table where four rows share a timestamp it loses 120 of 60,000 rows, because the page after a boundary resumed at created_at > cursor and skipped the rest of the tied group. Comparing the pair – (created_at, id) > ($1, $2), or < when the page is descending – returned 60,000 of 60,000 in the same order as OFFSET. That difference is a test, not a code comment: the suite pages a table of duplicate timestamps seven rows at a time and asserts the result is identical to OFFSET, in both directions.
Keyset pagination has its own sharp edges, and they are worth stating because each produces a plausible-looking bug. The key must be unique or paired with a unique tie-breaker, and the pair has to appear in both the ORDER BY and the cursor condition – putting it only in the ordering is the bug above, and the missing rows are invisible until someone reconciles a report against the table. The cursor is a position in a changing table, not a snapshot: rows inserted behind the cursor will not appear in later pages, and rows deleted ahead of it shorten the walk. If the client needs a stable view of the data, that is a transaction with a repeatable-read snapshot, which is a different feature and has its own cost. And the cursor should be opaque to the client – base64 of the key pair, signed if you care whether clients forge it – because the day the ordering changes, every cached cursor in the wild becomes wrong.
8. Fix five: one round trip instead of N
The N+1 pattern is usually not a loop someone wrote on purpose. It is a helper that fetches “the orders for this customer” called from a list comprehension, or an ORM relationship touched inside a serializer. The database work is not the problem: 200 indexed lookups cost about 0.111 ms each with per-statement logging off, which is the condition a production server runs in. The problem is that each one is a network round trip, a parse, a plan and a context switch, and they add up linearly with the page size.
The condition matters more here than anywhere else in the article, because this is the one page that sends hundreds of statements. Both conditions are therefore in the table, measured in two rounds of opposite order: the same page costs 22.186 (21.041–23.488) ms with logging off and 54.231 (51.031–57.927) ms with every statement logged, which is 2.4 times the same work.
| Strategy for “newest five orders of each of 200 customers” | Round trips | Rows returned | Median, logging off | Median, every statement logged | Against the loop, logging off |
|---|---|---|---|---|---|
| One query per customer | 200 | 423 | 22.186 (21.041–23.488) ms | 54.231 (51.031–57.927) ms | baseline |
One CROSS JOIN LATERAL | 1 | 423 | 0.951 (0.709–0.991) ms | 0.966 (0.872–1.052) ms | 23.33x faster |
One customer_id = ANY($1), top five chosen in Python | 1 | 99,969 | 154.918 (147.779–160.583) ms | 153.764 (147.986–160.403) ms | 0.14x (slower) |
Read the two timing columns together, because their difference is the point. The single-statement shapes are unmoved by the logger: LATERAL reads 0.951 ms against 0.966 ms, and ANY 154.918 against 153.764. Only the row that makes 200 statements per page pays, and it pays by a factor of 2.4. That is also why the ratio matters as much as the comparison: the logged-on pass puts LATERAL at 56.14 times, because the logger inflates the loop’s own baseline. Against the logged-off baseline it is 23.33 times – still the whole argument for one round trip, with none of it borrowed from a log setting.
The third row is the instructive one, and it needs its qualifier stated: those 200 ids include the five whales, so the = ANY($1) statement returned 99,969 rows to keep 423. Batching the ids into a single statement removed the round trips and made the page 0.14 times slower, because the transfer and deserialisation of every whale’s history cost more than the round trips it saved. Batching is not the goal; one round trip that returns only the rows you need is the goal, and that is what LATERAL expresses: for each id, run the limited subquery in the database.
The qualifier matters enough to measure separately, because the same statement is the best option as soon as the ids stop containing a whale. The table below repeats the page for 200 tail customers, where the widest history is a handful of rows, again under both conditions:
| Strategy, 200 tail customers | Round trips | Rows returned | Median, logging off | Median, every statement logged | Against the loop, logging off |
|---|---|---|---|---|---|
| One query per customer | 200 | 419 | 22.244 (20.512–23.269) ms | 53.791 (49.86–56.436) ms | baseline |
One CROSS JOIN LATERAL | 1 | 419 | 0.738 (0.659–0.776) ms | 0.957 (0.785–1.024) ms | 30.14x faster |
One customer_id = ANY($1), top five chosen in Python | 1 | 427 | 0.977 (0.942–1.012) ms | 1.236 (1.041–1.32) ms | 22.77x faster |
Now = ANY wins, and it wins for the honest reason: with no whale in the list the statement returns 427 rows instead of 419, so the “batch everything then pick in Python” strategy is no longer transferring a history it will throw away. Between the two shapes, LATERAL is the one that is right for both: it returns exactly 419 rows whether the id list contains whales or not, which is why it is the shape to put behind a shared helper rather than the faster of the two on today’s data.
SELECT c.cid, o.id, o.total_cents, o.created_at
FROM unnest($1::int[]) AS c(cid)
CROSS JOIN LATERAL (
SELECT id, total_cents, created_at
FROM orders
WHERE customer_id = c.cid
ORDER BY created_at DESC
LIMIT $2
) o;
The same question in SQLAlchemy 2.0
With an async session you cannot touch a lazy relationship outside a greenlet context, so the N+1 shows up as MissingGreenlet rather than as a slow page – unless you load the relationship eagerly in the wrong way, or loop queries yourself. The measurement below uses 400 line items across 100 orders and counts statements with a before_cursor_execute listener rather than by reading the source. It was run under both logging conditions, and the table keeps the logged column because the hand-written loader is a hundred statements: with logging off, the loop’s median is 3930.036 ms against 3927.36 ms logged, and the two loader medians move by a few milliseconds each. The loader comparison is the same either way; only the absolute numbers belong to a condition, so each column says which.
| Loader | Statements | No index on the foreign key, every statement logged | No index on the foreign key, logging off | With the foreign key indexed, logging off |
|---|---|---|---|---|
| Query per order, by hand | 101 | 3927.36 (3906.398–4182.545) ms | 3930.036 (3907.078–5074.044) ms | 50.282 (49.917–55.32) ms |
selectinload | 2 | 66.902 (53.198–80.261) ms | 52.529 (50.902–54.707) ms | 7.989 (7.506–8.165) ms |
joinedload | 1 | 61.016 (57.549–65.428) ms | 61.033 (57.876–68.062) ms | 6.406 (6.292–6.689) ms |
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import joinedload, selectinload
from app.models import Order
async def with_selectinload(session: AsyncSession, order_ids: list[int]) -> list[Order]:
"""Two statements: parents, then one IN (...) for all children."""
result = await session.execute(
select(Order).options(selectinload(Order.items)).where(Order.id.in_(order_ids)))
return list(result.scalars().all())
async def with_joinedload(session: AsyncSession, order_ids: list[int]) -> list[Order]:
"""One statement, but duplicate parent rows that must be de-duplicated."""
result = await session.execute(
select(Order).options(joinedload(Order.items)).where(Order.id.in_(order_ids)))
return list(result.unique().scalars().all())
Both loaders are correct; the table shows which cost you are paying. selectinload issues one extra statement with an IN list, which is predictable and stays one statement as the page grows. joinedload issues one statement but repeats each parent once per child, so the row count in the wire protocol is the child count, and forgetting .unique() raises rather than silently duplicating. The more important columns are the last two: adding an index on order_items.order_id, which the schema did not have, cut the hand-written loop from 3930.036 ms to 50.282 ms – 78.16 times – and the loader fix still wins after the index, 6.29 times over the loop.
9. Fix six: pools leak, and nothing tells you
A connection pool is a semaphore with a reputation. It looks like a resource manager, so the failure mode people expect is “too small”; the failure mode that actually takes a service down is “the slot was never given back”. The shape is always the same: a helper acquires a connection, does something that can raise – a validation error, an upstream 4xx turned into an exception, a timeout – and returns the result on the happy path. The error path returns the connection to nobody.
The measurement below uses a pool of 5 and a helper that raises on every second call without releasing. The error handler keeps the exception objects, the way a log sink or an error registry would.
| Pattern | Leaks before the pool was empty | First caller to wait | Wait for a connection | Pool state at the end |
|---|---|---|---|---|
pool.acquire() without a release on the error path | 5 of 5 | call number 11 | 500.7 ms, then TimeoutError | 0 idle of 5 |
async with pool.acquire() | none (100 errors raised, every one released) | none | none | 5 idle of 5 |
The arithmetic is unforgiving, so it is worth spelling out slowly: each failed call that never releases costs one connection, so a pool of 5 is empty after 5 of them. This helper fails on every second call, so those 5 leaks are spread over 10 calls – and it is call number 11, the next failing one, that waits 500.7 ms and dies with an error that points at the pool rather than at the handler that leaked. In this run the pool could not even be closed within two seconds of the last leak, which is the detail that makes a leak hard to attribute: the process looks alive, requests hang for the timeout, and the database reports no problem at all because the statements are never sent.
The fix is not discipline, it is structure: one function that acquires, executes and returns, used everywhere, so there is no error path to forget.
import asyncio
from typing import Any
import asyncpg
from pgperf import with_retry
async def fetch(
pool: asyncpg.Pool,
sql: str,
*args: Any,
attempts: int = 3,
timeout: float | None = None,
) -> list[asyncpg.Record]:
"""Fetch rows through the pool; the connection is released on every path."""
async def once() -> list[asyncpg.Record]:
async with pool.acquire() as conn: # release is unconditional
if timeout is None:
return await conn.fetch(sql, *args)
return await asyncio.wait_for(conn.fetch(sql, *args), timeout=timeout)
return await with_retry(once, attempts=attempts)
Cancellation is the other leak
A canceled request is an error path that does not look like one. asyncio.wait_for raises TimeoutError in the caller and asks the driver to cancel the query; with asyncpg the cancellation is forwarded to the server, the backend stops the statement, and the connection stays usable. Measured here: the call returned after 201.5 ms against a deadline of two hundred milliseconds, the connection answered a following query, and no backend was still running the statement afterwards.
asyncio.wait is not that. Given a task and a timeout, it returns the sets of done and pending tasks and leaves the pending ones running: the caller believes the work was abandoned, the server is still executing it, and the connection is still checked out. Measured here: 1 task still pending when the wait returned, 1 backend still active at that moment, 1 still active two hundred milliseconds later, and only 0 once the task was cancelled explicitly. Python 3.12 also refuses the lazier version of the mistake outright – passing the coroutine itself to asyncio.wait raises TypeError: Passing coroutines is forbidden, use tasks explicitly. – but the task variant fails silently, which is worse.
Put the deadline where it cannot be forgotten
Client-side deadlines cover the client. A server-side statement_timeout covers the backend even when the client process disappears mid-query, which is exactly what happens when a worker is killed or a pod is evicted. Setting it per transaction rather than per session is what keeps a recycled connection from inheriting a deadline that belonged to another request; in this run a deadline of one hundred fifty milliseconds fired after 150.6 ms with SQLSTATE 57014, and the connection answered the next query normally.
from contextlib import asynccontextmanager
from typing import AsyncIterator
import asyncpg
@asynccontextmanager
async def statement_timeout(conn: asyncpg.Connection, milliseconds: int) -> AsyncIterator[None]:
"""Apply a statement timeout for one transaction, then restore the previous one."""
if milliseconds < 0:
raise ValueError("milliseconds must be >= 0")
if conn.is_in_transaction():
# a savepoint does not end a transaction: SET LOCAL made inside it would
# stay in force until the caller's transaction ends, so put it back
previous = await conn.fetchval("SHOW statement_timeout")
await conn.execute("SELECT set_config('statement_timeout', $1, true)", f"{milliseconds}ms")
try:
yield
finally:
try:
await conn.execute(
"SELECT set_config('statement_timeout', $1, true)", str(previous))
except asyncpg.PostgresError:
pass # the timeout aborted the transaction; the setting dies with it
return
async with conn.transaction():
await conn.execute("SELECT set_config('statement_timeout', $1, true)", f"{milliseconds}ms")
yield
Note what is not there: a finally that sets the value back on the normal path. set_config(..., true) is transaction-local, so the end of the transaction restores it – commit, rollback, or the rollback that follows a canceled statement – and a naive restore runs on an aborted transaction, raising a second error from inside the cleanup path and hiding the original cause. That is why the restore in the branch above is wrapped: it only ever runs when the caller had already opened a transaction.
That branch exists because of a measured surprise. async with conn.transaction() is a savepoint when a transaction is already open, and a savepoint does not end a transaction: on 16.2, a set_config('statement_timeout', ..., true) made inside a released savepoint still read back as the new value for the rest of the outer transaction, and only vanished when that transaction ended. So a helper that opened its own transaction and trusted the setting to be local would leave a deadline on the caller’s connection for whatever it did next – the exact leak the context manager was written to prevent, one level up. The test suite asserts both halves of the fix: the savepoint behaviour itself, and that the previous value is back after the inner block while the outer transaction is still open.
Retry the classes that deserve it
Retrying is a statement about the error, not about the caller’s optimism. Serialization failures and deadlocks are expected outcomes of concurrent transactions and are safe to repeat; a syntax error, a constraint violation or a permission error will fail identically every time and retrying only multiplies the load on a database that is already unhappy. A deadlock is the one entry in this table where “safe to repeat” is not the same as “free to repeat”: the batch measured in section 10 commits most of its transfers on a bounded retry and finishes in a fraction of the time if the rows are simply locked in one order. The classifier below is the one the module ships, and its tests assert both directions.
| SQLSTATE | Name | Retry? | Why |
|---|---|---|---|
40001 | serialization_failure | yes, with backoff | The transaction can be replayed against a fresh snapshot |
40P01 | deadlock_detected | yes, bounded – and fix the order if it repeats | One side of the cycle is chosen as the victim while the other commits, so the losing statement can be replayed; each attempt pays another deadlock_timeout wait |
55P03 | lock_not_available | yes, short and bounded | A lock_timeout or NOWAIT asked for the refusal |
53300 | too_many_connections | yes, with jitter | The server is at capacity; immediate retries make it worse |
57014 | query_canceled | no | A deadline was reached on purpose; repeating it repeats the deadline |
42601 | syntax_error | no | Deterministic; a retry loop is a load generator |
23505 | unique_violation | no | Let the caller handle the conflict |
42501 | insufficient_privilege | no | A grant is missing, not a moment of bad luck |
Sizing: the pool is a queue, and the database is the server
The intuitive move when callers wait for connections is a bigger pool. The measurement says what actually happens when you do that on a database that is already busy: 60 callers, each running a query that takes about 3.063 ms alone, against two pool sizes on a 2-vCPU machine.
| Pool size | Median request | 95th percentile | Median time inside the database | Throughput | Wall time for all callers |
|---|---|---|---|---|---|
| 5 | 70.453 (43.2–103.199) ms | 126.636 ms | 6.824 (6.101–9.418) ms | 469.2 queries/s | 127.87 ms |
| 20 | 101.711 (75.826–131.852) ms | 136.037 ms | 32.075 (18.006–60.724) ms | 423.4 queries/s | 141.71 ms |
Quadrupling the pool did not raise throughput: 469.2 against 423.4 queries per second, and the 95th-percentile request time moved by 1.07 of its old value – a difference this short burst cannot resolve either way. The median request does move more visibly, 70.453 (43.2–103.199) ms to 101.711 (75.826–131.852) ms, but those two interquartile bands overlap as well, so it is not evidence either: sixty callers on a shared container produce a spread that wide on its own. What the burst does resolve is the work inside the database: each query became 4.7 times more expensive there, because more concurrent backends on two cores means more context switching and more time waiting for a core. The queue did not disappear; it moved from the pool into the executor. That is the argument for sizing a pool against cores – a small multiple, not a multiple of your caller count – and for putting a bounded queue in front of it so that the wait is visible and shedable instead of turning into a timeout.
Stated as a condition, because it is one: this is a CPU-bound local burst – sixty callers on one machine, a warm cache and a database with 2 cores, so the resource being queued for is the CPU rather than the network or the disk. On a workload that waits on I/O, a larger pool can raise throughput because the waiting overlaps. That is a measurement for your workload, not an argument against sizing a pool to cores, and it is why the number to carry away is the service time inflation rather than the throughput of this particular burst.
10. Fix seven: locks, waiting, and the deadlock you can delete
A row lock is not slow; waiting for one is. The interesting question is never “how do I make the lock faster” but “how long do I let a request wait before it is better to fail”. PostgreSQL gives four answers, and the choice between them is a product decision dressed as a setting.
| Approach | Measured outcome | What the caller sees | Use it when |
|---|---|---|---|
| Wait indefinitely (default) | 542.2 ms while the holder kept the lock for 500 ms | A response that is as slow as the slowest writer ahead of it | The wait is short by construction and correctness needs the row |
lock_timeout = '200ms' | gave up after 200.6 ms with SQLSTATE 55P03 | A retryable error with a known cause | Interactive requests with a latency budget |
FOR UPDATE NOWAIT | refused in 0.6 ms | An immediate “busy, try later” | You would rather tell the user than queue them |
FOR UPDATE SKIP LOCKED | returned no row because another session held it | Another worker’s job, not this one’s | Queue tables with many competing workers |
The blocked statement reported itself honestly while it waited: state = active, wait_event_type = Lock, wait_event = transactionid. Those three fields are the fastest way to tell a lock wait from a slow query in production, because a waiting backend is doing no work at all – the CPU is idle, the plan is irrelevant, and adding an index changes nothing. If pg_stat_activity shows a growing set of sessions in that state, the question is which transaction holds the lock and why it is taking so long, not how to speed up the waiting statement.
Deadlocks are a lock-order bug
Two transactions that touch the same two rows in opposite orders will deadlock as soon as they overlap, and PostgreSQL will resolve it by killing one after deadlock_timeout. That timer, not the data, decides how much wall time the victim loses: in the two-session reproduction the victim received SQLSTATE 40P01 after 1001 ms.
The fix is not a longer timeout. It is a rule that every transaction takes locks in the same order – sort the ids before updating – and the difference is measurable at batch scale: 60 concurrent transfers over 5 accounts, each holding two row locks.
| Lock order in the batch | Deadlocks | Transfers committed | Wall time |
|---|---|---|---|
| Rows locked in id order | 0 | 60 of 60 | 657.3 ms |
| Rows locked in random order | 38 | 22 of 60 | 16256.4 ms |
| Random order, each transfer retried up to 5 times | 65 (all attempts) | 57 of 60 | 29625.2 ms |
Every deadlock in the second row costs about a second of deadlock_timeout before the victim is aborted, and nothing in that batch retried the victim: the ordered batch committed 60 of 60 transfers in 657.3 ms, and the random one committed 22 of 60 in 16256.4 ms. The other 38 are not slower transfers, they are failures.
The retry that the SQLSTATE table in section 9 recommends is the third row: the same random batch, with each transfer allowed up to 5 attempts. It commits 57 of 60 – most of them, not all, because 3 transfers spent the whole budget and still ended in 40P01 – and the row shows what it costs: 65 deadlock waits across 28 retried transfers, 29625.2 ms of wall time against 16256.4 ms for the batch that gave up at the first failure, plus the work every victim did before it was killed. Retrying widens what the system tolerates and it is the right answer for a cycle you cannot design away; it does not give the batch back the time the ordered one took. That is why the fix belongs in the lock order, where it is free, rather than in the retry loop, where it is a bet: the order removes the waits and the discarded attempts, and those are what the loss actually consisted of.
-- Same order everywhere: lowest id first, every time.
BEGIN;
SELECT id FROM accounts WHERE id IN (42, 17) ORDER BY id FOR UPDATE;
UPDATE accounts SET balance = balance - 100 WHERE id = 17;
UPDATE accounts SET balance = balance + 100 WHERE id = 42;
COMMIT;
-- A work queue where workers must not fight over the same row.
WITH next_job AS (
SELECT id FROM jobs
WHERE state = 'queued'
ORDER BY created_at
FOR UPDATE SKIP LOCKED
LIMIT 1
)
UPDATE jobs SET state = 'running', started_at = now()
WHERE id IN (SELECT id FROM next_job)
RETURNING id, payload;
The queue pattern deserves one warning: SKIP LOCKED makes workers independent, but it also means a row that no worker ever picks is invisible forever. Pair it with a visibility timeout – a started_at older than some deadline is reclaimable – or a crashed worker’s job stays running until someone notices.
11. Fix eight: the write path, and what it leaves behind
Reads are half the problem. The other half is how rows get in and what the table looks like afterwards. Three ways to write 50,000 rows from Python, measured into the same indexed table with a truncate between runs. Each method was measured twice in one session: once with per-statement logging on, which is how the first pass of this article ran, and once with it off, in two rounds in opposite order so that a checkpoint could not pass for the effect of logging.
| Method | Wall time, every statement logged | Wall time, logging off | Rows per second, logging off | Notes |
|---|---|---|---|---|
executemany() | 9,790 ms | 5,471 ms | 9,140 | One statement per row, pipelined by the driver |
Multi-row INSERT, 1,000 rows per statement | 6,032 ms | 6,304 ms | 7,932 | Fewer parses, but parameter lists grow fast |
COPY | 2,556 ms | 2,718 ms | 18,399 | No per-row parse or plan at all |
from typing import Any, Iterable, Sequence
import asyncpg
async def copy_rows(
conn: asyncpg.Connection, table: str, columns: Sequence[str], rows: Iterable[Sequence[Any]]
) -> int:
"""COPY rows into ``table``; returns how many were written."""
if not columns:
raise ValueError("columns must not be empty")
records = [tuple(row) for row in rows]
if not records:
return 0
await conn.copy_records_to_table(table, records=records, columns=list(columns))
return len(records)
COPY ran at 18,399 rows per second against 9,140 for row-at-a-time once logging was out of the picture, and the gap that remains is the parse, bind and plan the driver pays per row. The logged column explains itself once you know what it cost: one logging phase wrote 37,788,504 bytes to the server log, and the row-at-a-time method was 1.789 times slower with that switched on. Both numbers in that row come from the same session, in two rounds of opposite order – an earlier separate pass recorded 11,174 ms for the same statement with logging on, which is the same setting and a different afternoon.
The other two rows did not move, and it is worth being blunt about the part that looks backwards: COPY and the multi-row insert came out 5.9 and 4.3 percent faster with logging on in this pass. That is the measurement noise of this container at this size, not a benefit of writing log lines; the runs in opposite order put it on both sides of the line. What is far outside that noise is the row-at-a-time penalty, and the reason is structural: those methods send one or fifty statements for the whole batch, while executemany() sends 50,000 of them, so a per-statement log setting is paid per row. That is also why a per-statement log setting is worth checking before you believe a benchmark of a round-trip-bound design.
The catch is that COPY fails the whole batch on the first bad row, so a loader that must skip invalid input needs a staging table and a merge, or a per-row fallback for the rejects. For a nightly import either is fine; for a request path, batch size matters more than method, because a single 50,000-row transaction holds locks and generates WAL that has to be written before the commit returns.
What 80,000 updates leave behind
An update in PostgreSQL does not change a row in place: it writes a new version and marks the old one dead, which is what makes MVCC work and what makes a table grow under an update-heavy workload. In this experiment 80,000 of 200,000 orders had their JSONB column rewritten in place.
| State | Heap size | Table plus indexes | Composite index size | Dead tuples | Full count, median |
|---|---|---|---|---|---|
| Baseline | 22,413,312 bytes | 41,639,936 bytes | 6,397,952 bytes | 2,027 | 5.842 ms |
| After the updates | 32,440,320 bytes | 70,467,584 bytes | 12,632,064 bytes | 82,027 | 7.665 ms |
After VACUUM | 32,440,320 bytes | 70,467,584 bytes | 12,632,064 bytes | 93 | 6.322 ms |
After VACUUM FULL | 23,355,392 bytes | 42,393,600 bytes | 6,332,416 bytes | 0 | 6.973 ms |
Two numbers matter here. VACUUM removed the dead tuples – 82,027 down to 93 – but left the files exactly the same size, because the space becomes reusable inside the table rather than being returned to the operating system. VACUUM FULL rewrote the table and gave the space back (42,393,600 bytes against a peak of 70,467,584), at the price of an exclusive lock for the duration. On a live table that lock is usually unacceptable, so the practical answer is regular autovacuum plus a maintenance window for the rare table that has genuinely bloated – not a nightly VACUUM FULL script.
The median full-count time moved from 5.842 ms to 7.665 ms and back to 6.973 ms, which is smaller than the noise in this container and worth reporting as such: at this size bloat costs index lookups and cache space long before it shows up in a single sequential count. The size numbers are the honest signal, and they are what turns into cache misses once the table no longer fits in memory.
12. Three settings, measured on real queries
Settings are the last place to look, not the first, and they are worth looking at only when the plan is already right. Three of them come up in every “Postgres tuning” conversation: work_mem, parallel query, and the prepared-statement plan cache. Each was measured against the same data, and each answer is more conditional than the checklist version.
work_mem is per sort node, and the spill costs more than the setting saves
The query sorts all 800,000 line items by a column no index covers. At the default 4096kB it spilled; at a deliberately tiny setting it spilled catastrophically; at a generous setting it sorted in memory. Each setting was run twice, and the two runs are shown because the difference between them is smaller than the difference between the settings.
work_mem | Sort method | Sort space | Execution, two runs | Against 4 MB |
|---|---|---|---|---|
| 64kB | external merge | 17,296 kB | 29,375 and 30,772 ms | 47.9x slower |
| 4MB | external merge | 17,312 kB | 627 and 630 ms | baseline |
| 64MB | quicksort in memory | 55,826 kB | 514 and 446 ms | 1.3x faster than 4 MB |
The ratio between the two spilling settings is the point, and it goes the other way from the one people expect. 64 kB is 64 times less memory than 4 MB, but the sort was 47.9 times slower – less than the memory ratio, not more. The setting did not scale the work; it changed how the work was done. Both settings spill, and they spill nearly the same volume: 17,296 kB of sorted runs at 64 kB against 17,312 kB at 4 MB. What differs is how many runs that volume is divided into, and each merge pass has to read all of them – which is why the honest statement is “spilling is expensive” rather than “less memory is proportionally slower”.
The step that removes work rather than rearranging it is the one to 64 MB: quicksort in memory, no temporary files, 628.2 ms to 479.8 ms (1.3x). That is the win worth paying for, and it is worth paying for selectively.
The trap is that work_mem is per sort or hash node, not per connection and certainly not per cluster. A query with three sorts can allocate three times the setting, and with a pool of 20 connections the ceiling is the multiplication everyone forgets until the OOM killer reminds them. Set it per session for the handful of reporting queries that need it, keep the global value modest, and watch for Sort Method: external merge in plans rather than pre-emptively raising it everywhere.
A second core helps only when the query is the bottleneck
Three aggregates over the same tables, each with parallel query off and with two workers on a 2-vCPU machine:
| Query | Parallel off | Two workers | Workers launched | Speed-up |
|---|---|---|---|---|
| Group 800,000 line items into buckets | 159.2 ms | 123.7 ms | 2 | 1.29x |
| Sum a column over 800,000 rows | 116.7 ms | 90.4 ms | 2 | 1.29x |
| Join orders to line items and aggregate | 937 ms | 208.7 ms | 2 | 4.49x |
The two simple aggregates gave up about a fifth of their time, which is what two workers on two cores can offer once the leader process also has to coordinate. The join gained far more than two cores should explain, and that is the interesting case. The plans say why, and the difference is not “the work split cleanly”:
| What the plan did | Parallel off, 4MB work_mem | Parallel off, 8MB work_mem | Two workers, 4MB work_mem |
|---|---|---|---|
| Execution, median of 5 | 796.645 ms | 346.107 ms | 217.306 ms |
| Shape | Aggregate over Hash Join over two Seq Scan | same as the left | Finalize GroupAggregate over Gather Merge, Sort and Partial HashAggregate over Parallel Hash Join |
| Hash node and batches | Hash, Batches: 2 | Hash, Batches: 1 | Parallel Hash, Batches: 1 |
| Hash memory | 6,773 kB, one of two batches | 11,470 kB in one batch | 11,552 kB shared by three participants |
| Temporary blocks written | 2,195 | 0 | 0 |
The first thing that table corrects is the budget. A Hash node’s limit is not work_mem; it is work_mem times hash_mem_multiplier, which is 2 on this server (SHOW hash_mem_multiplier, the PostgreSQL 16 default), so at the 4096kB default the hash may use 8,192 kB. The hash needs about 11,470 kB for these 200,000 rows – the figure it reaches when it fits in one batch – and 6,773 kB is the peak of one of two batches, not a requirement being compared against a 4096kB budget. So the serial plan splits the table in two, writes 2,195 temporary blocks, and reads them back; at 8MB the budget is 16,384 kB, the same hash fits in one batch, and the query finishes without touching a temporary file. The parallel plan reports a single 11,552 kB hash as well, shared across three participants that each bring their own budget: it still fits in one batch at 2MB, where a single participant is allowed 4,096 kB, and it collapses at 1MB, where 2,048 kB per participant is not enough – the same plan then runs 8 batches, writes 4,408 temporary blocks and takes 2,127 ms. That is the whole budget question in one ladder: the limit is per participant, so a parallel hash gets three times the memory, and part of its speed is that rather than the split scan.
With that, the speed-up can be split instead of attributed. Raising work_mem alone, with parallelism still off, took the query from 796.645 ms to 346.107 ms – 2.3 times, all of it spill removal – and 345.913 ms at 16MB, which is the same number twice: once the spill is gone there is nothing left for memory to buy. Turning the two workers on at the original 4MB took it to 217.306 ms, another 1.59 times. The total, 3.67 times, is therefore roughly three quarters spill removal and one quarter second core – and only the second part is parallelism. That total and the 4.49 times in the aggregate table above are one query under identical settings, measured in two separate passes – 5 repeats for this decomposition, 2 for that table – which is why both are quoted rather than one being smoothed into the other: the multiplier moves by about a fifth between passes while the plan shape does not, and the multi-pass experiment behind the section’s plans shows the same spread from the other side, 777.14 ms against 200.588 ms over 3 repeats (3.874 times). Turning on parallelism to rescue a spill is a measure of luck; fixing the spill is the one that repeats.
So the practical rule stands, with its mechanism attached: parallelism multiplies the speed of work that is already the right work, and it can also multiply the memory available to a hash or a sort. It cannot rescue a sequential scan that should have been an index lookup, and on a two-core box it competes with the connections your pool is trying to keep busy.
The plan cache can choose a plan for the wrong customer
A prepared statement is planned once. If the plan is built with the parameter in hand it is a custom plan and fits that value; if it is built without the parameter it is a generic plan and must work for all values, which for a skewed column means it works well for the many and badly for the few. The same statement, customer_id = $1, run against the whale and against a tail customer, with the two modes forced:
| Plan mode | Whale: median | Plan used | Tail: median | Plan used |
|---|---|---|---|---|
Custom plan (auto, first executions) | 0.211 (0.209–0.215) ms | Index Scan on the composite index | 0.214 (0.186–0.22) ms | Bitmap Heap Scan |
| Forced generic plan | 5.322 (5.218–5.469) ms | Bitmap Heap Scan, 2,989 blocks | 0.126 (0.12–0.146) ms | Bitmap Heap Scan |
The generic plan is not a bad plan in general – it is the same shape the tail customer’s custom plan uses, a bitmap heap scan over the same index, at the same 7 buffers and 4 rows, and for that customer the two runs come out at 0.126 ms against 0.214 ms. That gap is plan time, not execution: a custom plan is built on every call (0.027 ms of planning) while the generic plan is not (0.003 ms), and both medians carry a client round trip, so the relevant conclusion is that re-planning a ten-thousandth-of-a-second query costs more than the query – not that the generic plan suits the tail better. It is a bad plan for the whale: 5.322 ms, 25.22 times slower, because a bitmap scan followed by a sort has to read 2,989 buffers where the ordered index scan reads 22. The default plan_cache_mode = auto lets PostgreSQL compare and usually keeps the custom plan, which is why this problem appears when something else pins the mode: a driver configured for generic plans, a proxy that pools in transaction mode with unnamed statements, or a global setting someone added while chasing a different problem. If your p99 has a step change with no query change, check whether the plan for the hot statement changed shape before you check anything else.
13. The runbook: four questions the built-in views can answer
None of this helps at 2 a.m. unless there is a query to run. The four below need no extension and no special grant beyond reading statistics, and each answers one question that a plan review cannot. The measured column is what they returned for one workload on this cluster – 200 indexed lookups and one heavy join – so the shape of the answer is visible rather than described.
| Question | View | Measured in one batch |
|---|---|---|
| Is anything running too long right now? | pg_stat_activity | A heavy join caught in flight, state active, 3 ms into the statement |
| Are reads hitting cache or storage? | pg_stat_database | 5,334 hits, 5,899 reads, ratio 47.5 percent |
| Which access path does the table use? | pg_stat_user_tables | orders: 1 sequential scan, 200 index scans |
| Which indexes earn their write cost? | pg_stat_user_indexes | orders_customer_created_idx has 24,815 scans; order_items_pkey has 0 |
| Is a table accumulating dead rows? | pg_stat_user_tables | 200,000 live, 0 dead |
-- 1. What is running now, and for how long
SELECT pid, state, wait_event_type, wait_event,
round(extract(epoch FROM (now() - query_start)) * 1000) AS running_ms,
left(query, 120) AS query_head
FROM pg_stat_activity
WHERE datname = current_database()
AND state <> 'idle'
ORDER BY running_ms DESC
LIMIT 20;
-- 2. Cache hit ratio since the last statistics reset
SELECT sum(blks_hit) AS hits,
sum(blks_read) AS reads,
round(sum(blks_hit)::numeric / nullif(sum(blks_hit) + sum(blks_read), 0), 4) AS ratio
FROM pg_stat_database
WHERE datname = current_database();
-- 3. Sequential scans on big tables: candidates for an index
SELECT relname, seq_scan, idx_scan, n_live_tup, n_dead_tup
FROM pg_stat_user_tables
WHERE n_live_tup > 10000
ORDER BY seq_scan DESC
LIMIT 20;
-- 4. Indexes nobody reads, and the rows they still cost on every write
SELECT relname, indexrelname, idx_scan, idx_tup_read,
pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_stat_user_indexes
ORDER BY idx_scan ASC, pg_relation_size(indexrelid) DESC
LIMIT 20;
Two readings of those numbers keep people out of trouble. The cache hit ratio is a property of the window you measured, not a health score: 47.5 percent here is what a cold-ish cache and a 48,324,608-byte read burst look like, and the same cluster reports a very different number after the working set is warm. And idx_scan = 0 is only evidence of an unused index if the window covers real traffic – a replica that only serves analytics, or a table that is written nightly and read never, will look identical to an index that should be dropped.
The one question these views cannot answer is “which statement consumed the most total time”, because that needs pg_stat_statements and this build does not ship it. If your server has it, that is the view to reach for first: it aggregates by normalised statement text, so it finds the query that is individually fast and collectively expensive – the one a plan review never sees because each execution looks fine.
14. The module behind these numbers, and the tests that keep them true
Every experiment in this article used the same small module: bounded retries that classify by SQLSTATE, a statement-timeout context manager that cannot leak into the next request, a keyset paginator that binds its predicate values and validates the identifiers it interpolates, a plan-explanation helper, a plan assertion, a COPY loader and a pool-health snapshot. It is 408 lines, has no dependency beyond asyncpg, and ships with 31 tests that run against a live server – all of them passing on PostgreSQL 16.2 with the same dataset this article measures. One of them pages a table where duplicate timestamps straddle every seventh row and asserts that the composite cursor returns exactly what OFFSET returns, ascending and descending; another reproduces the single-column cursor beside it and asserts that it loses rows, so the fix cannot quietly regress into the bug it replaced; a third filters through a bound predicate and asserts that the cursor continues the placeholder numbering after it.
The repository is not public yet. Until it is, this article carries the parts that matter – the retry classifier, the timeout manager, the paginator, the COPY loader, the plan helper and five of the tests – and the closing box says where the link will appear once the repository is published. That is a smaller claim than “the full source is here”, and it is the accurate one.
import time
import asyncpg
import pytest
import pgperf
async def test_plan_assertion_fails_on_seq_scan(conn):
plan = await pgperf.explain(conn, "SELECT count(*) FROM t_orders WHERE total_cents < 0")
with pytest.raises(pgperf.PlanAssertionError):
pgperf.assert_index_used(plan, forbid_seq_scan=True)
async def test_connection_returned_after_error(pool):
for _ in range(50):
with pytest.raises(asyncpg.UndefinedTableError):
await pgperf.fetch(pool, "SELECT * FROM t_missing_table")
health = pgperf.pool_health(pool)
assert health.idle == health.size
assert not health.leaked
async def test_statement_timeout_raises_and_resets(conn):
started = time.perf_counter()
with pytest.raises(asyncpg.QueryCanceledError) as info:
async with pgperf.statement_timeout(conn, 120):
await conn.fetch("SELECT pg_sleep(2)")
elapsed_ms = (time.perf_counter() - started) * 1000
assert info.value.sqlstate == "57014"
assert 80 <= elapsed_ms < 1500
async def test_composite_cursor_keeps_tied_rows(conn):
expected = [r["id"] for r in await conn.fetch(
"SELECT id FROM t_orders ORDER BY created_at ASC, id ASC")]
paged = [r["id"]
async for page in pgperf.iter_keyset(
conn, table="t_orders", key="created_at", tiebreak="id",
columns="id, created_at", page_size=7)
for r in page]
assert paged == expected
async def test_statement_timeout_inside_caller_transaction_restores(conn):
await conn.execute("SELECT set_config('statement_timeout', '3s', false)")
async with conn.transaction():
async with pgperf.statement_timeout(conn, 120):
assert await conn.fetchval("SHOW statement_timeout") == "120ms"
# a savepoint does not end the transaction: without the restore this
# would still read 120ms here
assert await conn.fetchval("SHOW statement_timeout") == "3s"
await conn.execute("SELECT set_config('statement_timeout', '0', false)")
Two of those tests are worth more than the rest. The plan assertion turns a performance property into a CI failure: the day a migration drops an index or a query gains an ORDER BY that the index cannot serve, the test fails in the pull request instead of on the p99 dashboard three weeks later. The pool test asserts the property that is hardest to see in production – after fifty failed calls the pool still has all of its connections – because the failure mode is silence followed by a timeout that blames the wrong component.
Wiring it into a FastAPI service takes one lifespan handler and one dependency. The pool is created once, with a size chosen against the database’s cores rather than the number of workers, and closed on shutdown; nothing in the request path creates a connection.
import os
from contextlib import asynccontextmanager
import asyncpg
from fastapi import FastAPI, Request
import pgperf
DATABASE_URL = os.environ.get("DATABASE_URL", "postgresql://localhost/app")
POOL_MAX = int(os.environ.get("DB_POOL_MAX", "8"))
QUERY_TIMEOUT = float(os.environ.get("DB_QUERY_TIMEOUT", "2.0"))
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.pool = await asyncpg.create_pool(
dsn=DATABASE_URL,
min_size=2,
max_size=POOL_MAX, # small multiple of database cores
command_timeout=QUERY_TIMEOUT,
max_inactive_connection_lifetime=60,
)
try:
yield
finally:
await app.state.pool.close()
app = FastAPI(lifespan=lifespan)
@app.get("/customers/{customer_id}/orders")
async def recent_orders(customer_id: int, request: Request):
rows = await pgperf.fetch(
request.app.state.pool,
"SELECT id, status, total_cents, created_at FROM orders "
"WHERE customer_id = $1 ORDER BY created_at DESC LIMIT 20",
customer_id,
timeout=0.5,
)
return [dict(row) for row in rows]
15. Frequently asked questions
Why is my new index not used by the planner?
The three usual causes, in order of frequency: the predicate is not sargable because a function or a cast wraps the column; the column order does not match the query, so the index cannot serve the ordering and the planner prefers a scan; or the statistics are stale and the planner’s row estimate makes the index look more expensive than a scan. Run EXPLAIN and look for Index Cond versus Filter – if the index is not named at all, the first two causes apply; if it is named but a Sort sits above it, stale statistics are the likely cause.
Should I always create indexes with CONCURRENTLY in production?
On a table that takes writes, yes – a plain CREATE INDEX blocks them for the duration of the build. The cost is that CONCURRENTLY takes longer, cannot run inside a transaction block, and can leave an invalid index if it fails; check pg_index.indisvalid and drop and rebuild if it is false. On a small or write-idle table the plain form is simpler and faster, and the lock is measured in milliseconds.
When should we use PgBouncer instead of the application pool?
When the number of application processes exceeds the number of connections the database should serve, which happens as soon as you run many worker processes or many pods. A proxy in transaction mode multiplexes those clients onto a small server-side pool; the trade is that session state – prepared statements, SET, advisory locks, LISTEN – does not survive between transactions. The measurement in section 9 is the reason to care: more concurrent backends made each query slower without adding throughput.
Why does the plan say Index Only Scan but the query is still slow?
Because the scan had to visit the heap anyway. The usual chain starts with VACUUM: when its heap pass finds nothing dead it may skip the index pass, the dead item identifiers stay in the index, and an index-only scan cannot prove those entries dead without fetching the rows they point at – so it fetches them. A page that is not marked all-visible is the other way into the same counter; the two are not alternatives, and a table can be in both states at once. The plan counts both as Heap Fetches. In the measurement above, 10,108 heap fetches appeared after 1,977 updates and fell to 17 after VACUUM, with the count query going from 5.26 ms to 2.914 ms. It is not always zero: later update-and-vacuum cycles on the same table left 0, 1,941 and 0. Where a plain VACUUM leaves them behind, its own verbose report says so – index scan bypassed means the index pass was skipped and the dead item identifiers are still there (1,839 of them in experiment 30, which a plain VACUUM afterwards did not clear and INDEX_CLEANUP ON did). Run VACUUM (VERBOSE) on that table before touching the index.
Is a bigger connection pool always better?
No. A pool bounds concurrency; the database executes the queries, and its cores are the real limit. In this measurement a pool of 20 made each query 4.7 times more expensive inside the database and produced no more throughput than a pool of 5 (469.2 against 423.4 queries per second). The request latencies were not separable: the median moved from 70.453 ms to 101.711 ms but the interquartile bands overlap, and the 95th percentile moved by 1.07 of its old value. Size the pool to a small multiple of database cores and make the wait visible.
How do I find a query that is never slow alone but expensive in total?
Per-statement timing cannot show it, because each execution is fast. You need aggregation by normalised statement text, which is what pg_stat_statements provides with total_exec_time and calls; this build does not ship the extension, so no number for it appears in this article. Without it, compare pg_stat_database.tup_returned against your request rate to see whether the database is doing far more row work than the API implies.
Does work_mem need to be raised globally?
Rarely. It is per sort or hash node, so a global increase multiplies by the number of concurrent nodes, not by the number of queries. Set it per session for the reporting queries that need it: in the measurement above, 64 MB turned an external merge into an in-memory quicksort and cut the query from 628.2 ms to 479.8 ms, while 64 kB made it 30073.7 ms.
How do I stop a plan regression from coming back after a schema change?
Assert the plan. Wrap EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) in a test, check that the expected index is named and that no sequential scan appears on the large table, and run it in CI against a database with realistic row counts. The module in section 14 ships exactly that helper, and the test suite fails if the plan changes shape – which is the only reliable way to notice a regression before your users do.
16. The order to do this in
- Reproduce the slow call with a parameter that matches production skew, not with the smallest id in the table.
- Capture
EXPLAIN (ANALYZE, BUFFERS)and write down the node that does the most work, its row count and its buffer counts. - Fix the query shape first: sargable predicates, keyset pagination, one round trip per page instead of one per row.
- Then fix the index: equality column, sort column, returned columns in
INCLUDE. - Re-run the same measurement and keep both numbers. A change you cannot compare is a change you cannot defend.
- Check the write path: batch size, COPY where appropriate, and the index maintenance cost you just added.
- Check the pool: every acquisition through a context manager, a deadline on every call, a retry classifier that refuses deterministic errors.
- Put the plan under test so the next migration cannot undo it silently.
- Only then look at settings, and change one at a time.
If you take one thing away. The plan is the specification of the work, and the measurement is the only thing that tells you whether the work changed. Everything else in this article – indexes, pools, timeouts, settings – is a way of changing what the plan does.
Related runbooks
This guide belongs to a series on failures that the traceback does not explain. Its closest neighbours are the ones that call the database from Python: SQLAlchemy 2.0 async in production, where the same N+1 and pool questions appear through the ORM, and httpx AsyncClient in production, where the retry and timeout decisions live on the other side of the socket.
For the layers around the database: FastAPI on Gunicorn and UvicornWorker for the workers that own the pool, Redis caching and distributed locks for the lock problem one layer up, Celery production architecture for the batch writers, and Kubernetes pod resources and OOMKilled for the limits that work_mem multiplies against.
For the Python side of the same discipline: memory leaks in Celery and asyncio workers, pytest-asyncio in production CI, ProcessPoolExecutor and broken pools, asyncio for high-volume API work and Docker multi-stage builds for Python. The tooling these runbooks assume is collected in The TechBobby Stack.
