Fixing a hot query from its execution plan
A walkthrough of the reasoning behind a common PostgreSQL fix: reading the plan, choosing an index that matches the access pattern, and shipping it without locking writes.
Technical demonstration. Reference architecture written by Fuzzion. Not a client engagement; contains no outcome metrics.
Challenge
A customer-facing "recent shipments" page runs one query per view. As the orders and shipments tables grow, it gets steadily slower and starts to dominate database CPU.
Constraints
- No maintenance window; writes cannot be blocked.
- Index storage and write amplification must be justified.
- The fix must be verifiable before and after on production statistics.
Architecture
Query
SELECT o.id, o.created_at, s.status
FROM orders o
JOIN shipments s ON s.order_id = o.id
WHERE o.customer_id = $1
ORDER BY o.created_at DESC
LIMIT 20;Before
- SortSort Key: o.created_at DESC
- Hash JoinHash Cond: (s.order_id = o.id)
- Seq Scan on shipments s
- Hash
- Seq Scan on orders oFilter: (customer_id = $1)
After
- Limit
- Nested Loop
- Index Scan using orders_customer_created_idx on orders oIndex Cond: (customer_id = $1)
- Index Scan using shipments_order_id_idx on shipments sIndex Cond: (order_id = o.id)
Index change
CREATE INDEX CONCURRENTLY orders_customer_created_idx
ON orders (customer_id, created_at DESC);
CREATE INDEX CONCURRENTLY shipments_order_id_idx
ON shipments (order_id);Engineering approach
- 01
Find the query from statistics
Query statistics rank statements by total time, not by how slow they feel. This one wins by frequency × cost.
- 02
Read the plan
The planner scans every order to find one customer's rows, hashes all shipments, then sorts — work that grows with table size, not with the 20 rows returned.
- 03
Match the index to the access pattern
A composite index on (customer_id, created_at DESC) serves both the filter and the ordering, so the planner can stop after 20 rows. The join key on shipments gets its own index.
- 04
Ship without blocking
Indexes are built CONCURRENTLY, validated, and the plan is re-checked on production statistics. Unused indexes found along the way are candidates for removal.
Technologies
- PostgreSQL
- pg_stat_statements
- EXPLAIN (ANALYZE, BUFFERS)
- PgBouncer
Operational considerations
- Index build monitored for lock waits and replication lag.
- Plan regression check added for the query in CI against a production-like dataset.
- Write latency on orders watched after the index lands.
What we would measure
Success criteria we would agree before work starts. These are not results.
- Total and mean execution time of the statement
- Shared buffers read per call
- Database CPU share attributable to the statement
- Insert latency on the indexed table