WORKINGPROJECTCHAPTER 18

Project: diagnose five slow queries under load

Five queries against the shop, five different reasons they are slow, and one diagnostic sequence that finds each of them

180 MINDATABASESUPDATED 2026-11-02

You have met each of the five causes in this module: the planner’s statistics, MVCC and vacuum, the lock queue, B+ tree indexes, and the planner’s cost model. This project is about telling them apart under pressure, when all you have is “the query is slow” and a database under load.

Warm up with the simulation

The capstone simulation from the Storage path runs one dashboard query through three of the five causes in a row. Watch the invariant strip under it: p99 ≤ 200 ms and planner estimate within 10× of actual rows. Each incident breaks one or both, and the evidence that tells you which is on screen each time.

▶ SIMULATION
APP · 100 queries per run
no run yet
clock 0.0 s · —
EXPLAIN ANALYZE (last run)
—
orders
1,000,000 rows · 10,000 pages · open 30.0%
stats say open 30.0% (ANALYZE @ 0.0 s)
indexes: idx_status
locks: none held long
Seq Scan on ordersestimated 10,000 pages, actual 10,000 (4,000 ms)
Bitmap Index Scan on idx_statusestimated 11,502 pages, actual 11,502 (4,601 ms)
✓ p99 ≤ 200 ms✓ planner estimate within 10× of actual rows
SCHEDULE
01[APP]run the workload: 100 × SELECT … WHERE customer_id = 42 AND status = 'open'
02[DBA]CREATE INDEX idx_customer ON orders (customer_id)
03[APP]run the workload: 100 × SELECT … WHERE customer_id = 42 AND status = 'open'
04[JOBS]02:00 nightly job closes every open order, auto-ANALYZE runs; 06:00 bulk load of 300,000 open orders; autovacuum is behind and does not re-analyze
05[APP]run the workload: 100 × SELECT … WHERE customer_id = 42 AND status = 'open'
06[DBA]ANALYZE orders
07[APP]run the workload: 100 × SELECT … WHERE customer_id = 42 AND status = 'open'
08[JOBS]report job: BEGIN, read orders, stay open; migration: ALTER TABLE orders ADD COLUMN note text
09[APP]run the workload: 100 × SELECT … WHERE customer_id = 42 AND status = 'open'
10[DBA]terminate the report; rewrite it to commit every 100 ms
11[JOBS]report job (now 100 ms transactions) + the migration's ALTER TABLE, again
12[APP]run the workload: 100 × SELECT … WHERE customer_id = 42 AND status = 'open'
Start of the incident scenario. 12 steps.
SELECT * FROM orders WHERE customer_id = 42 AND status = 'open';
-- Seq Scan on orders  (rows=1000000)              4 s: no index on customer_id
-- Bitmap Index Scan on idx_status (rows=1 actual=300000)  stats taken when the queue was empty
--   (a plain Index Scan with a Filter would show rows=1 actual=5 and
--    Rows Removed by Filter: 299995: read that line too)
-- ...then fast, then 30 s: waiting on a lock, plan unchanged

What to notice. When the estimate goes wrong, EXPLAIN shows it: the plan is chosen for a number that is not true. When the query waits on a lock, EXPLAIN looks perfect and the query still takes 30 seconds, because EXPLAIN measures execution and the time was spent queued. Then write the on-call runbook as a function; the harness checks it against nine cases, including two causes at once.

FIX IT NOT YET

Write the on-call runbook. Return the actions to take, in order, from ['END_BLOCKER', 'ANALYZE', 'CREATE_INDEX'] (empty if nothing is wrong). END_BLOCKER if the query waited on a lock held by a blocker. ANALYZE if estimated and actual rows differ by more than 10×. CREATE_INDEX if it is a Seq Scan returning under 1% of the table and the filter column has no index. Order: a lock wait first (nothing else matters while you wait), then statistics (the planner cannot choose until its estimates are right), then indexes.

The order the exercise insists on, lock waits then statistics then indexes, is the order you use below.

The brief

You will plant five conditions in the shop database, run a mixed workload against it with pgbench, and diagnose each slow query from the database’s own evidence. For each one, write down three things before you open its solution: the evidence (the exact row or plan line that convinced you), the cause, and the fix. Then apply the fix and show the evidence change.

The five queries, as the application sends them:

# name query what the team says
Q1 customer order history SELECT id, status, total_cents, created_at FROM orders WHERE customer_id = $1 ORDER BY created_at DESC LIMIT 20 slow for everyone, all the time
Q2 fulfilment worker poll SELECT id, order_id FROM fulfilment_queue WHERE status = 'pending' ORDER BY enqueued_at LIMIT 50 was 1 ms, slow since the history import
Q3 low-stock report SELECT count(*) FROM inventory WHERE on_hand < 10 gets slower every minute, nothing deployed
Q4 product page SELECT id, name, price_cents FROM products WHERE id = $1 a primary-key lookup that suddenly takes seconds, then all at once is fine
Q5 brand revenue report a three-table join filtered by category, brand and supplier slow since the catalogue backfill

The causes, in no particular order: a missing index on a filter column; stale statistics after a bulk load; table bloat behind an idle transaction; a lock wait behind an ALTER TABLE; a join planned for one row that returns thousands, because three correlated columns were treated as independent. Do not match them up from the table. Match them from the evidence.

The diagnostic sequence

Apply the same sequence to every slow query, in this order. Each step answers one question and rules out a class of causes.

1. Is it waiting? pg_stat_activity and pg_locks. A query that is waiting shows wait_event_type = 'Lock' and pg_blocking_pids(pid) returns who it is behind. If it is waiting, stop: nothing about its plan matters until the wait ends.

SELECT pid, state, wait_event_type, wait_event, pg_blocking_pids(pid) AS blocked_by,
       now() - xact_start AS xact_age, backend_xmin, left(query, 70) AS query
FROM pg_stat_activity
WHERE datname = 'shop' AND backend_type = 'client backend' AND state <> 'idle'
ORDER BY xact_start NULLS LAST;

2. Which query costs the most? pg_stat_statements. Total time, not mean time, is what the database spends: a 40 ms query called 50 times a second costs more than a 10 s report run once an hour.

SELECT left(query, 60) AS query, calls, round(total_exec_time) AS total_ms,
       round(mean_exec_time::numeric, 2) AS mean_ms, shared_blks_hit + shared_blks_read AS blocks
FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 10;

3. Is the plan built on true numbers? EXPLAIN (ANALYZE, BUFFERS). Compare rows= estimated with rows= actual on every node, from the bottom up. More than 10× apart, in either direction, means the plan was chosen for a different query than the one that ran. Buffers: tells you how many 8 KB pages each node touched, which is the honest measure of work.

4. Is the table what you think it is? pg_stat_user_tables. n_dead_tup against n_live_tup for bloat, n_mod_since_analyze and last_autoanalyze for stale statistics, seq_scan against idx_scan for a missing index, and pg_relation_size for a table far larger than its rows.

SELECT relname, n_live_tup, n_dead_tup, n_mod_since_analyze, last_autovacuum, last_autoanalyze,
       seq_scan, idx_scan, pg_size_pretty(pg_relation_size(relid)) AS size
FROM pg_stat_user_tables WHERE relname IN ('orders','fulfilment_queue','inventory','products')
ORDER BY relname;

5. What does the planner believe? pg_stats and pg_stats_ext. The per-column most_common_vals, most_common_freqs and n_distinct that the estimate in step 3 came from, and any extended statistics on column groups.

Only after all five do you reach for an index. Indexes are the fix most often applied and the fix most often wrong.

LAB Plant five slow queries, find them under load, fix each one ~180 MIN
YOU NEEDDocker Compose with labs/databases running: docker compose up -d (Postgres 17 on 5432, service db)the shop loaded at scale=1; at scale=0.1 divide the random() upper bounds in the query files by 10pg_stat_statements in shared_preload_libraries (step 1 checks and sets it)three terminals open in labs/databases, about 4 GB of free disk for the bulk load and the bloat

Every command runs from labs/databases. The query files go in shop/queries/d2-project/ so you keep them, and are copied into the container for pgbench. Part A plants three conditions that stay put (Q1, Q2, Q5) and finds them under load. Part B creates the two that need a live session (Q3, Q4), one at a time.

1. Turn on pg_stat_statements and reset the baseline.

docker compose exec db psql -U atlas shop -c "SHOW shared_preload_libraries;"
# if the result does not include pg_stat_statements:
docker compose exec db psql -U atlas shop -c "ALTER SYSTEM SET shared_preload_libraries = 'pg_stat_statements';"
docker compose restart db && sleep 5
docker compose exec db psql -U atlas shop -c "CREATE EXTENSION IF NOT EXISTS pg_stat_statements;" -c "SELECT pg_stat_statements_reset();"
The last command returns a timestamp: the moment the statistics were cleared. From now on every query the workload runs is counted, normalised with $1, $2 for its parameters.

2. Plant Q1, the missing index.

The D1 project may have left an index on orders(customer_id). This drops every index whose first column is customer_id, which is what a well-meaning cleanup of “unused” indexes does on a replica where the history page is never served:

docker compose exec -T db psql -U atlas shop <<'SQL'
DO $$
DECLARE r record;
BEGIN
  FOR r IN SELECT indexrelid::regclass AS idx FROM pg_index
           WHERE indrelid = 'orders'::regclass
             AND indkey[0] = (SELECT attnum FROM pg_attribute WHERE attrelid = 'orders'::regclass AND attname = 'customer_id')
  LOOP
    RAISE NOTICE 'dropping %', r.idx;
    EXECUTE format('DROP INDEX %s', r.idx);
  END LOOP;
END $$;
SQL
DO, with a NOTICE: dropping … line for each index that existed. No notice means there was none to drop, which is also fine.

3. Plant Q2, the stale statistics.

A fulfilment queue is created with 2,000 pending rows and analysed, which is what autovacuum does to a small new table within a minute. Then a history import adds 1.7 million rows that are all done. Autovacuum is turned off for this table so the condition holds while you work; in production it is a busy autovacuum (three workers by default, autovacuum_max_workers) occupied with larger tables, which can leave a table unanalysed for hours.

docker compose exec -T db psql -U atlas shop <<'SQL'
DROP TABLE IF EXISTS fulfilment_queue;
CREATE TABLE fulfilment_queue (
  id bigserial PRIMARY KEY,
  order_id bigint NOT NULL REFERENCES orders,
  status text NOT NULL,
  enqueued_at timestamptz NOT NULL DEFAULT now()
) WITH (autovacuum_enabled = off);
CREATE INDEX fulfilment_queue_status ON fulfilment_queue (status);
CREATE INDEX fulfilment_queue_enqueued ON fulfilment_queue (enqueued_at);
INSERT INTO fulfilment_queue (order_id, status)
  SELECT id, 'pending' FROM orders WHERE status = 'paid' ORDER BY id DESC LIMIT 2000;
ANALYZE fulfilment_queue;
-- the history import
INSERT INTO fulfilment_queue (order_id, status, enqueued_at)
  SELECT id, 'done', coalesce(shipped_at, created_at) FROM orders WHERE status = 'shipped';
SQL
INSERT 0 2000, ANALYZE, then after 10 to 60 seconds INSERT 0 1700634 at scale 1 (INSERT 0 169945 at 0.1; 85 percent of orders are shipped).

4. Plant Q5, the correlated columns.

The catalogue team backfills two columns from category: every category has one house brand and one supplier. Three columns now carry the same fact. The report also needs an index on order_items(product_id), created if D1 did not.

docker compose exec -T db psql -U atlas shop <<'SQL'
ALTER TABLE products ADD COLUMN IF NOT EXISTS brand text, ADD COLUMN IF NOT EXISTS supplier text;
UPDATE products SET brand = 'house-' || category, supplier = 'supplier-' || category;
CREATE INDEX IF NOT EXISTS order_items_product_id ON order_items (product_id);
VACUUM ANALYZE products;
ANALYZE order_items;
SQL
CAT=$(docker compose exec -T db psql -U atlas shop -Atc "SELECT category FROM products GROUP BY 1 ORDER BY count(*) DESC LIMIT 1")
echo "report category: $CAT"
UPDATE 50000 (5000 at scale 0.1), the index build (a few seconds on 6 million rows if it did not exist), and the name of the largest category: electronics, with 4,225 of the 50,000 products. Keep this terminal: $CAT is used in the next step.

5. Write the workload and start it.

mkdir -p shop/queries/d2-project && cd shop/queries/d2-project
printf '%s\n' '\set cid random(1, 500000)' \
  'SELECT id, status, total_cents, created_at FROM orders WHERE customer_id = :cid ORDER BY created_at DESC LIMIT 20;' > q1.sql
printf '%s\n' "SELECT id, order_id FROM fulfilment_queue WHERE status = 'pending' ORDER BY enqueued_at LIMIT 50;" > q2.sql
printf '%s\n' 'SELECT count(*) FROM inventory WHERE on_hand < 10;' > q3.sql
printf '%s\n' '\set pid random(1, 50000)' 'SELECT id, name, price_cents FROM products WHERE id = :pid;' > q4.sql
printf '%s\n' "SELECT p.id, p.name, sum(i.qty) AS units, sum(i.qty * i.unit_price_cents) AS revenue FROM products p JOIN order_items i ON i.product_id = p.id JOIN orders o ON o.id = i.order_id WHERE p.category = '$CAT' AND p.brand = 'house-$CAT' AND p.supplier = 'supplier-$CAT' AND o.status = 'shipped' GROUP BY p.id, p.name ORDER BY revenue DESC LIMIT 10;" > q5.sql
printf '%s\n' '\set pid random(1, 50000)' 'UPDATE inventory SET on_hand = on_hand - 1, updated_at = now() WHERE product_id = :pid;' > stock.sql
cd ../../..
docker compose cp shop/queries/d2-project db:/tmp/d2p

Start the load in the second terminal and leave it running for the whole of Part A:

docker compose exec db pgbench -U atlas -n -c 8 -j 4 -T 1800 -P 10 \
  -f /tmp/d2p/q1.sql@20 -f /tmp/d2p/q2.sql@10 -f /tmp/d2p/q3.sql@5 \
  -f /tmp/d2p/q4.sql@50 -f /tmp/d2p/q5.sql@1 -f /tmp/d2p/stock.sql@50 shop
A progress line every 10 seconds: progress: 10.0 s, N tps, lat X ms stddev Y. TPS is low, tens to a few hundred, and the latency standard deviation is larger than the mean: a few slow queries are holding the eight clients. The @ weights make the product page and the stock update the common case, as in a real shop, and the report rare.

6. Find the expensive queries.

After a minute of load, in the first terminal, run step 2 of the diagnostic sequence:

docker compose exec db psql -U atlas shop -c "
SELECT left(query, 60) AS query, calls, round(total_exec_time) AS total_ms,
       round(mean_exec_time::numeric, 2) AS mean_ms, shared_blks_hit + shared_blks_read AS blocks
FROM pg_stat_statements WHERE query NOT LIKE '%pg_stat%' ORDER BY total_exec_time DESC LIMIT 8;"
Three statements dominate total_ms: the order history (Q1, tens of milliseconds mean, called often), the queue poll (Q2, hundreds of milliseconds mean) and the brand report (Q5, around a second or more mean, called rarely). The product page and stock update have means well under a millisecond and huge call counts. The blocks column is the clue: tens of thousands of pages per call for something that returns 20 or 50 rows. Now take each of the three through steps 3 to 5 of the sequence before opening its solution.

7. Diagnose Q1.

docker compose exec db psql -U atlas shop -c "EXPLAIN (ANALYZE, BUFFERS) SELECT id, status, total_cents, created_at FROM orders WHERE customer_id = 4242 ORDER BY created_at DESC LIMIT 20;"
Write down the scan node, its Rows Removed by Filter, the buffers, and the estimate against the actual before reading on.
Solution

Evidence. Parallel Seq Scan on orders, Filter: (customer_id = 4242), Rows Removed by Filter of about 666,000 per process (three processes), about 18,400 buffers (the whole table), and around 25 ms at scale 1. The estimate is close to the actual (17 rows estimated, 2 returned for customer 4242), so the planner is not confused: it is choosing the only plan it has. pg_stat_user_tables shows seq_scan on orders climbing with every call.

Cause. No index has customer_id as its leading column, so finding a customer’s handful of rows (2 for customer 4242, about 60 for a heavy customer such as 4201) means reading all 2 million.

Fix. An index that matches both the filter and the sort, so the database reads the 20 newest entries for the customer and stops:

CREATE INDEX CONCURRENTLY orders_customer_created ON orders (customer_id, created_at DESC);

CONCURRENTLY builds it without blocking writes, which matters because the load is running. Re-run the EXPLAIN: a Bitmap Index Scan on orders_customer_created and a sort of the customer’s two rows (for a customer with more than 20 orders, an Index Scan using orders_customer_created that stops after 20), under ten buffers, around 0.05 ms. That is hundreds of times faster and about 2,000 times less I/O. This is the only one of the five that an index fixes.

8. Diagnose Q2.

docker compose exec db psql -U atlas shop -c "EXPLAIN (ANALYZE, BUFFERS) SELECT id, order_id FROM fulfilment_queue WHERE status = 'pending' ORDER BY enqueued_at LIMIT 50;"
docker compose exec db psql -U atlas shop -c "SELECT n_live_tup, n_mod_since_analyze, last_analyze, last_autoanalyze FROM pg_stat_user_tables WHERE relname = 'fulfilment_queue';" \
  -c "SELECT attname, most_common_vals, most_common_freqs FROM pg_stats WHERE tablename = 'fulfilment_queue' AND attname = 'status';"
Compare the estimated rows on the scan node with the actual rows, then read what pg_stats believes about status.
Solution

Evidence. Index Scan using fulfilment_queue_enqueued with about 1.67 million rows estimated, 50 actual, and Rows Removed by Filter about 1.7 million: it walked the whole time index to find the 50 pending rows at its far end. About 1.7 million buffers, 300 to 600 ms. pg_stats says most_common_vals = {pending}, most_common_freqs = {1}. n_mod_since_analyze is about 1.7 million, the same as the table.

Cause. The statistics describe the table as it was before the import: 100 percent pending. With that belief, walking the enqueued_at index and stopping after 50 matches is the cheapest plan, because the first 50 entries should all match. In fact the first 1.7 million entries are done. The index exists; the planner is using the wrong one because it believes yesterday’s data.

Fix.

ANALYZE fulfilment_queue;

Re-run the EXPLAIN: Index Scan using fulfilment_queue_status estimating about 2,000 rows, a top-N sort, around 0.3 ms. Then fix the reason autovacuum did not: here, ALTER TABLE fulfilment_queue RESET (autovacuum_enabled);. In production, add ANALYZE as the last step of every bulk load, and for a hot queue table set a per-table autovacuum_analyze_scale_factor low enough (for example 0.01) that a large change triggers a re-analyse in seconds rather than when 10 percent of the table has changed.

9. Diagnose Q5.

docker compose exec db psql -U atlas shop -c "EXPLAIN (ANALYZE, BUFFERS) $(cat shop/queries/d2-project/q5.sql)"
docker compose exec db psql -U atlas shop -c "SELECT attname, n_distinct FROM pg_stats WHERE tablename = 'products' AND attname IN ('category','brand','supplier');" \
  -c "SELECT * FROM pg_stats_ext WHERE tablename = 'products';"
Find the lowest node that reads products. Compare its estimate with its actual, then follow that row count up the tree and watch what the planner did with it.
Solution

Evidence. Seq Scan on products (parallel at scale 1) with three filters, about 30 rows estimated and 4,225 actual (one category’s worth). Above it a Nested Loop into order_items through the product_id index, run 4,225 times, and another Nested Loop into orders_pkey run about 495,000 times, the loops= figure on that node. About 2.5 million buffers and around 1.5 seconds. A sort node above spills to disk (Sort Method: external merge) because it was sized for about 2,000 rows and got 420,000. pg_stats shows each column with about 40 distinct values; pg_stats_ext is empty.

Cause. The planner assumes the three filters are independent and multiplies their selectivities: electronics is about 8.5% of products, and 0.085 × 0.085 × 0.085 × 50,000 products is about 30 rows. In fact the three columns are the same fact written three times, so the combined filter is as selective as one of them. Planned for 30 products, a nested loop is the cheapest plan. Executed for 4,225, it does about 495,000 index probes into orders.

Fix. Tell the planner the columns are correlated:

CREATE STATISTICS products_category_brand_supplier (dependencies, mcv) ON category, brand, supplier FROM products;
ANALYZE products;

Re-run the EXPLAIN: the products estimate is about 4,200, and the plan switches to parallel hash joins between products, order_items and orders, about 64,000 buffers instead of 2.5 million. On a laptop with the whole shop in memory, the gain is two to three times for this query, not 100 times; measure it with pgbench -f /tmp/d2p/q5.sql -c 8 -T 20 before and after. On a server where orders does not fit in memory, those 495,000 probes are random reads from disk and the nested-loop plan is the difference between milliseconds and many seconds. The estimate was wrong by more than 1,000 times, and that is what you fix; the time saved depends on your hardware. Functional dependencies help only with equality and IN conditions on constants, which is what this report uses.

10. Part B: plant Q3, the bloat behind an idle transaction.

Restart the load so the statement counts start fresh (Ctrl-C the pgbench, run SELECT pg_stat_statements_reset();, start pgbench again). Then, in the first terminal, measure the low-stock report and the table while healthy:

docker compose exec db psql -U atlas shop -c "SELECT pg_size_pretty(pg_relation_size('inventory'));" -c "EXPLAIN (ANALYZE, BUFFERS) SELECT count(*) FROM inventory WHERE on_hand < 10;"

In the third terminal, open a report session that forgets to commit, and leave it:

docker compose exec db psql -U atlas shop
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT count(*) FROM orders WHERE id < 100;
-- now leave this session idle; do not COMMIT

Wait three minutes with the load running, then measure again with the same two commands.

Before: about 2.5 MB and around 2 ms, about 320 buffers. After three minutes of stock updates: tens of megabytes and tens of milliseconds, with buffers grown in proportion, and it keeps growing for as long as the session stays open. Nothing about the query changed. Diagnose it with steps 1, 4 and 5 before reading on, and run VACUUM (VERBOSE) inventory; to see what vacuum says.
Solution

Evidence. pg_stat_user_tables shows n_dead_tup for inventory in the hundreds of thousands or millions against 50,000 live rows, and last_autovacuum recent: autovacuum is running and achieving nothing. VACUUM (VERBOSE) inventory prints tuples: 0 removed, ... are dead but not yet removable. pg_stat_activity shows a session idle in transaction with an xact_age of minutes and the oldest backend_xmin in the cluster.

Cause. Every stock update writes a new row version and leaves the old one dead. Vacuum can remove a dead version only when no snapshot can still see it. The idle REPEATABLE READ transaction holds a snapshot from three minutes ago, so every version created since then must be kept, in every table in the database. The low-stock report is a sequential scan, and it now reads every page of a table that is mostly dead rows.

Fix. End the transaction holding the horizon, confirm it has gone, then vacuum:

SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE state = 'idle in transaction' AND datname = 'shop';
SELECT count(*) FROM pg_stat_activity WHERE state = 'idle in transaction' AND datname = 'shop';  -- 0
VACUUM (VERBOSE) inventory;

This time vacuum removes the dead versions. The file usually stays near its bloated size, because vacuum frees space inside pages for reuse but returns it to the operating system only from the end of the file, so the scan still reads every page. To shrink it, VACUUM FULL inventory; rewrites the table back to about 2.5 MB and the report to about 2 ms, at the cost of an ACCESS EXCLUSIVE lock for the duration, which blocks the stock updates. In production use pg_repack, which rewrites the table without holding that lock. Prevent the cause with ALTER SYSTEM SET idle_in_transaction_session_timeout = '60s'; SELECT pg_reload_conf(); and an alert on max(now() - xact_start) from pg_stat_activity.

11. Plant Q4, the lock queue.

In the third terminal, open a report that reads products and then sits idle in its transaction:

BEGIN;
SELECT count(*) FROM products;
-- leave it idle

In the first terminal, run a migration as a deploy pipeline would. It adds a column with a constant default, which in Postgres 11 and later is a metadata-only change that takes milliseconds:

docker compose exec db psql -U atlas shop -c "ALTER TABLE products ADD COLUMN discontinued boolean NOT NULL DEFAULT false;"

Watch the pgbench terminal.

The migration does not return. Within one progress interval pgbench reports TPS falling towards zero and latency climbing into seconds: every product-page lookup (Q4, half the workload) is now stuck, and so are the clients that run them. Q4 is a primary-key lookup with a perfect plan. Leave the ALTER waiting. Diagnose it from a fourth terminal using step 1 of the sequence, and then look at the locks on the table.
docker compose exec db psql -U atlas shop -c "SELECT pid, mode, granted FROM pg_locks WHERE relation = 'products'::regclass ORDER BY granted DESC, pid;"
Solution

Evidence. In pg_stat_activity: the report session is idle in transaction with no wait_event, the ALTER TABLE is active with wait_event_type = Lock, wait_event = relation, blocked_by the report’s pid, and every product-page SELECT is also waiting on relation with blocked_by the ALTER’s pid. In pg_locks: one AccessShareLock granted (the report), one AccessExclusiveLock not granted (the ALTER), and a row of AccessShareLock not granted (the product pages). EXPLAIN ANALYZE on Q4 in a fresh session would itself hang, and if run on a replica would show a 0.05 ms index scan: the plan is not the problem.

Cause. The report’s open transaction holds ACCESS SHARE on products. The ALTER needs ACCESS EXCLUSIVE, which conflicts with it, so the ALTER waits. Postgres grants locks in queue order, so every new SELECT, which asks for ACCESS SHARE, conflicts with the queued ACCESS EXCLUSIVE and waits behind it. One idle transaction plus one millisecond-long DDL statement freezes the table for as long as the transaction stays open.

Fix. Relief first. Cancelling the ALTER releases the queue at once, because the readers were waiting on it rather than on the report:

SELECT pg_cancel_backend(pid) FROM pg_stat_activity WHERE query LIKE 'ALTER TABLE products%' AND state = 'active';

TPS recovers within one progress interval. Then end the report (COMMIT in its terminal, or pg_terminate_backend). Then re-run the migration the way it should always run, with a lock timeout and a retry, so the next time it fails in two seconds instead of taking the site with it:

docker compose exec db psql -U atlas shop -c "SET lock_timeout = '2s';" -c "ALTER TABLE products ADD COLUMN discontinued boolean NOT NULL DEFAULT false;"

Note the two -c flags run in one session, so SET applies to the ALTER. With the report still open, this fails with canceling statement due to lock timeout after two seconds and the product pages pause for at most that long. With it closed, it succeeds in milliseconds. idle_in_transaction_session_timeout from Q3 prevents the other half.

12. Put the shop back. Do this after the break below if you try it. Stop the load, end any idle session, and undo what this project planted, so the later modules start from the loaded shop and your D1 index set:

docker compose exec -T db psql -U atlas shop <<'SQL'
DROP TABLE IF EXISTS fulfilment_queue;
DROP STATISTICS IF EXISTS products_category_brand_supplier;
ALTER TABLE products DROP COLUMN IF EXISTS brand, DROP COLUMN IF EXISTS supplier, DROP COLUMN IF EXISTS discontinued;
ALTER SYSTEM RESET idle_in_transaction_session_timeout;
SELECT pg_reload_conf();
VACUUM FULL inventory;
VACUUM ANALYZE products;
SQL
docker compose exec -T db psql -U atlas -d shop -f /shop/queries/d1-indexes.sql
DROP TABLE, DROP STATISTICS, ALTER TABLE, then the D1 index file recreates whatever step 2 dropped (an index that already exists is skipped by its IF NOT EXISTS). orders_customer_created from the Q1 fix and order_items_product_id stay: both serve real queries. pg_stat_statements stays loaded; later modules use it.
Stop the load, then make two causes happen at once. Drop the statistics object from Q5 (DROP STATISTICS products_category_brand_supplier;, then ANALYZE products;), reopen the idle report on products from step 11, and start the ALTER again. Now Q5 is both waiting on a lock and, once the wait ends, running a plan built on a wrong estimate. Run the sequence on Q5 and note what each tool shows while the wait is in progress: EXPLAIN without ANALYZE in a new session also queues, pg_stat_statements shows nothing new because the statement has not finished, and only pg_stat_activity tells you the truth. Clear the lock, and only then does the misestimate become visible. That is why the sequence starts with waits. Step 12 puts the shop back.
READING
  1. DOC
    Postgres 17: Using EXPLAIN

    How to read every number in an EXPLAIN (ANALYZE, BUFFERS) node: costs, estimated and actual rows, loops, and buffers. Read sections 14.1.1 and 14.1.2; the rest is reference.

  2. DOC
    Postgres 17: Statistics Used by the Planner

    What pg_stats holds, what ANALYZE samples, and the extended statistics kinds with worked examples of the independence assumption going wrong. Read the extended statistics section for Q5.

  3. DOC
    Postgres 17: Explicit Locking

    The table-level lock modes and the conflict table that explains Q4. Read the table of conflicting lock modes; the advisory lock section can wait.

  4. DOC
    Postgres 17: pg_stat_statements

    The columns you sort by in step 2 of the sequence, how queries are normalised, and what the reset function clears. Skim the column table; read the configuration parameters if you run it in production.

  5. POST
    Zero-downtime Postgres migrations: the hard parts GoCardless

    A real outage from the Q4 lock queue, written up by the team it happened to, with lock_timeout as the fix. Short; read all of it.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Replication: physical, logical, sync and async →