CAPSTONE: THE SLOW QUERY
Everything in this path, in one 4-second SELECT
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.
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 unchangedCREATE INDEX idx_customer ON orders (customer_id);
ANALYZE orders; -- and make every bulk load end with it
SELECT pid, state, xact_start FROM pg_stat_activity
WHERE state = 'idle in transaction'; -- find the blocker
SET idle_in_transaction_session_timeout = '60s';
SET lock_timeout = '2s'; -- before any ALTER TABLE 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.
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×
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.
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().
“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.
USED IN
Chapters that build on this lesson.