How I Cut PostgreSQL p95 Latency from 1.8s to 0.9s
A practical playbook for PostgreSQL query tuning: pg_stat_statements, EXPLAIN (ANALYZE, BUFFERS), index redesign, autovacuum tuning and lock analysis.
At HHAeXchange I led a PostgreSQL optimization effort that brought read-heavy p95 latency from roughly 1.8 seconds down to 0.9 seconds. No single trick did it. It was a repeatable loop: measure, explain, fix, verify. This is that loop, written so you can run it against your own database.
1. Measure before you touch anything
Averages hide pain. Start by finding where the database spends its total time, not which single query is slowest. A moderately slow query that runs a million times a day usually matters more than a terrible one that runs twice. Enable pg_stat_statements and rank by total execution time:
SELECT queryid,
calls,
round(total_exec_time::numeric, 1) AS total_ms,
round(mean_exec_time::numeric, 2) AS mean_ms,
rows,
left(query, 80) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 20;
Record this baseline together with your application-side p95. You cannot claim an improvement you did not measure.
2. Read the plan, not the query
For each top offender, run EXPLAIN (ANALYZE, BUFFERS) on a realistic parameter set. Look for the same few smells every time:
- Sequential scans on large tables where a selective filter exists.
- Estimated vs actual rows that differ by 10x or more. That points to stale statistics or correlated columns.
- High shared read vs hit buffers, meaning the working set is not staying in cache.
- Sorts and hashes spilling to disk (
Sort Method: external merge), which is awork_memor query-shape problem.
3. Fix indexes: add the right ones, remove the dead ones
Most wins come from a composite index that matches the filter and sort order, or a partial index for a hot subset. Always build in production without blocking writes:
CREATE INDEX CONCURRENTLY idx_orders_customer_created
ON orders (customer_id, created_at DESC);
Indexes cost writes and storage, so audit for ones nobody uses (check that they are not backing a constraint first):
SELECT relname, indexrelname, idx_scan,
pg_size_pretty(pg_relation_size(indexrelid)) AS size
FROM pg_stat_user_indexes
WHERE idx_scan = 0
ORDER BY pg_relation_size(indexrelid) DESC
LIMIT 20;
Bloated indexes can be rebuilt online with REINDEX INDEX CONCURRENTLY (PostgreSQL 12+).
4. Tune autovacuum per table
The default autovacuum_vacuum_scale_factor of 0.2 means a 100-million-row table accumulates about 20 million dead rows before vacuum even starts. Bloat then slows scans and wastes cache. Check where dead tuples pile up:
SELECT relname, n_live_tup, n_dead_tup,
round(100.0 * n_dead_tup / nullif(n_live_tup + n_dead_tup, 0), 1) AS dead_pct,
last_autovacuum
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC
LIMIT 10;
Then tighten thresholds on the hot, large tables instead of changing the global default:
ALTER TABLE orders SET (
autovacuum_vacuum_scale_factor = 0.02,
autovacuum_vacuum_threshold = 1000,
autovacuum_analyze_scale_factor = 0.01
);
If vacuum runs but cannot clean up, look for long-running transactions or abandoned replication slots holding back the xmin horizon.
5. Rule out lock contention
Sometimes the query is fast and it simply waits. This shows who is blocked and by whom:
SELECT pid, pg_blocking_pids(pid) AS blocked_by, state,
wait_event_type, wait_event,
now() - query_start AS waiting,
left(query, 80) AS query
FROM pg_stat_activity
WHERE cardinality(pg_blocking_pids(pid)) > 0;
Set lock_timeout and idle_in_transaction_session_timeout so one forgotten transaction cannot stall everything behind it.
6. Verify and make it stick
- Re-run the baseline query and compare p95 from the application side, not just database time.
- Reset
pg_stat_statementsbetween experiments so numbers are comparable. - Add the slow-query and bloat checks to your dashboards so regressions are caught early.
- Write down what changed and why. Future you will thank present you.
The one-page checklist
- Rank by total time with
pg_stat_statements. EXPLAIN (ANALYZE, BUFFERS)the top offenders.- Fix estimates (
ANALYZE), then indexes, then query shape. - Tune autovacuum on the hot tables.
- Check locks and long transactions.
- Verify end to end, then monitor.
Want a starting point for server-level settings? Try the PostgreSQL Config Starter, and always benchmark against your own workload.
Enjoyed this?
I write about PostgreSQL, AWS and database reliability. Have a question or a similar problem to solve?