CAPSTONE: THE SLOW QUERY

Everything in this path, in one 4-second SELECT

L320 MINDATABASES
PREDICT

A report job opened a transaction, read orders, and has been idle for 30 s. A migration runs ALTER TABLE orders ADD COLUMN. What happens to new SELECTs on orders?

A slow query has three usual suspects. The plan can be wrong for the data: a seq scan where an index would read 50 pages. The plan can be right for data that no longer exists: the planner costs plans from statistics, and stale statistics pick the wrong index. Or the plan is fine and the query is waiting: on a lock held by someone else’s transaction.

EXPLAIN shows the first two. Only pg_stat_activity and pg_locks show the third. The sim walks one incident through all three, with the p99 and the estimate on the invariant strip.

▶ 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

Step THE INCIDENT and watch the strip. The first run is a seq scan. Stale stats break both invariants: the planner expected 1 open order and got 300,000. The sim shows that on the Bitmap Index Scan node. If the plan were a plain Index Scan with customer_id as a Filter, the node would report rows after the filter (1 against 5), and the tell would be the Rows Removed by Filter line. With default settings autovacuum re-analyzes after a load this size within about a minute; stats stay stale for hours only when autovacuum is off, behind or blocked, as it is here. Lock waits break p99 while the plan stays perfect. HARDENED runs the same bulk load and the same ALTER with ANALYZE after every load and a report that commits every 100 ms. Nothing turns red.

BREAK IT NOT YET

This workload is healthy. Inject one fault so that p99 goes above 200 ms while EXPLAIN still shows the good plan: Index Scan using idx_customer with an accurate estimate. That is the slow query that looks fine in every query-plan tool.

GOAL: p99 > 200 ms with Index Scan using idx_customer and an estimate within 10×

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.

Mental model:

a query’s latency is wait + plan. EXPLAIN only shows the plan, and the plan is only as good as the statistics under it. So diagnose in order: is it waiting (who holds the lock, and for how long), are the estimates within 10× of the actuals, and only then is the access path right for the selectivity. Every fix you make should also prevent the next one: an index, ANALYZE after bulk loads, and short transactions with timeouts.

IN PRODUCTION

Dashboards that slow down after a nightly import, plans that flip overnight, migrations that take the site down while a forgotten psql session sits idle in transaction. Tools: EXPLAIN (ANALYZE, BUFFERS), pg_stat_statements, pg_stat_activity, pg_locks, pg_blocking_pids().

IN INTERVIEWS

“This query was fast yesterday and is slow today. Walk me through it.” Check for lock waits first, then compare estimated and actual rows in EXPLAIN ANALYZE, then check the access path against the selectivity. Name the fix for each (end the blocker and add timeouts, ANALYZE, add or fix the index) and how to keep it from coming back.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.

USED IN

Chapters that build on this lesson.