Quick Summary / Direct Answer: To diagnose a PostgreSQL query that suddenly degraded, run EXPLAIN (ANALYZE, BUFFERS) to compare the active execution plan against expected execution paths. Check for stale table statistics in pg_stat_user_tables, inspect active lock contention using pg_locks, and evaluate memory pressure or autovacuum lag. Sudden degradations usually stem from plan flips, missing statistics, or lock blocking.
blockquote>Key Takeaways:
- Execute
EXPLAIN (ANALYZE, BUFFERS)to spot plan flips, mismatched row estimations, and heavy disk read operations. - Inspect
pg_stat_user_tablesto verify whenANALYZElast ran and check for high dead tuple counts. - Investigate
pg_locksandpg_stat_activityto rule out hardware resource saturation or blocking transactions.
Isolate Execution Plan Shifts with EXPLAIN ANALYZE
Queries do not randomly slow down without cause. The database engine altered its plan, resource availability dropped, or concurrent transactions built a wall. Your primary diagnostic tool is the execution plan itself.
Never rely on a bare EXPLAIN statement. It only shows what the query planner thinks will happen based on internal heuristics. You need runtime reality. Execute EXPLAIN (ANALYZE, BUFFERS) in your staging or production read-replica environment using the exact parameters that triggered the slowdown.
EXPLAIN (ANALYZE, BUFFERS, TIMING, COSTS)
SELECT o.id, o.created_at, c.email
FROM orders o
JOIN customers c ON o.customer_id = c.id
WHERE o.status = 'pending'
AND o.created_at >= NOW() - INTERVAL '7 days';
Look directly at the output nodes. Compare estimated row counts against actual row counts. A dramatic mismatch—such as an estimated 10 rows versus an actual 500,000 rows—signals an optimizer failure. When the planner drastically underestimates rows, it selects a Nested Loop join instead of a Hash Join or Merge Join. Nested loops on large datasets cause immediate response degradation.
Pay close attention to the Buffers: line in the plan output:
- Shared hit: Data pages retrieved directly from memory (RAM).
- Shared read: Data pages fetched from disk because they were absent from
shared_buffers. - Shared dirtied: Pages modified in memory by this query that must be written to disk.
If a query suddenly shows millions of disk reads where hit counts used to dominate, cache eviction or a bad index path is active.
Detect Stale Statistics and Autovacuum Lag
The PostgreSQL query planner relies entirely on table statistics stored in pg_statistic and exposed via pg_stats. If a table undergoes heavy updates or bulk inserts, the histogram of data distribution changes. If the background autovacuum process fails to keep up, the planner works with obsolete data.
Run this diagnostic query to inspect table statistics freshness and dead tuple density:
SELECT
schemaname,
relname,
n_live_tup,
n_dead_tup,
ROUND((n_dead_tup::float / NULLIF(n_live_tup + n_dead_tup, 0)) * 100, 2) AS dead_tuple_percent,
last_vacuum,
last_autovacuum,
last_analyze,
last_autoanalyze
FROM pg_stat_user_tables
WHERE relname = 'your_target_table';
High dead tuple percentages (above 10-15%) cause severe index degradation. Indexes must scan through dead tuple pointers before checking row visibility against the MVCC transaction horizon. This adds massive overhead.
If last_analyze or last_autoanalyze shows an outdated timestamp, force an inline statistic update immediately:
ANALYZE VERBOSE your_target_table;
Re-run your EXPLAIN ANALYZE test. If performance recovers instantly, adjust your table-level autovacuum settings so statistics refresh more aggressively in production.
Identify Lock Contention and Blocking Queries
Sometimes the query plan is optimal, but the execution thread spends its lifetime waiting on hardware or transactional locks. A query stuck in a waiting state looks identical to a slow query on application dashboards.
Query pg_stat_activity to identify blocked sessions and their corresponding blockers:
SELECT
blocked_locks.pid AS blocked_pid,
blocked_activity.usename AS blocked_user,
blocking_locks.pid AS blocking_pid,
blocking_activity.usename AS blocking_user,
blocked_activity.query AS blocked_statement,
blocking_activity.query AS blocking_statement
FROM pg_catalog.pg_locks blocked_locks
JOIN pg_catalog.pg_stat_activity blocked_activity ON blocked_activity.pid = blocked_locks.pid
JOIN pg_catalog.pg_locks blocking_locks
ON blocking_locks.locktype = blocked_locks.locktype
AND blocking_locks.database IS NOT DISTINCT FROM blocked_locks.database
AND blocking_locks.relation IS NOT DISTINCT FROM blocked_locks.relation
AND blocking_locks.page IS NOT DISTINCT FROM blocked_locks.page
AND blocking_locks.tuple IS NOT DISTINCT FROM blocked_locks.tuple
AND blocking_locks.virtualxid IS NOT DISTINCT FROM blocked_locks.virtualxid
AND blocking_locks.transactionid IS NOT DISTINCT FROM blocked_locks.transactionid
AND blocking_locks.classid IS NOT DISTINCT FROM blocked_locks.classid
AND blocking_locks.objid IS NOT DISTINCT FROM blocked_locks.objid
AND blocking_locks.objsubid IS NOT DISTINCT FROM blocked_locks.objsubid
AND blocking_locks.pid != blocked_locks.pid
JOIN pg_catalog.pg_stat_activity blocking_activity ON blocking_activity.pid = blocking_locks.pid
WHERE NOT blocked_locks.granted;
If this query returns records, your query is not executing slowly due to plan issues. It is waiting for access to a table or row held by an uncommitted transaction or an unindexed foreign key update.
Compare PostgreSQL Query Failure Modes
The following table outlines common causes for sudden query performance degradation, their key indicators, and immediate diagnostic paths.
| Failure Mode | Primary Indicator | Diagnostic View / Tool | Remediation Path |
|---|---|---|---|
| Statistics Drift | Actual vs Estimated row count mismatch in plan | pg_stat_user_tables |
Run ANALYZE; increase default_statistics_target |
| Lock Blocking | Query state shows active but CPU usage is 0% |
pg_locks join pg_stat_activity |
Terminate blocking PID; fix application transaction scope |
| Prepared Statement Plan Cache Flipping | Fast when run ad-hoc, slow inside application ORM | pg_stat_statements |
Set plan_cache_mode = force_custom_plan |
| Disk I/O Saturation | High shared read buffers in execution plan |
pg_statio_user_tables |
Adjust shared_buffers; add covering index |
| Work Memory Spills | Plan logs show Sort Method: external merge Disk |
EXPLAIN (ANALYZE, BUFFERS) |
Increase session-level work_mem |
Analyze Prepared Statement Parameter Sniffing
Does the query execute in milliseconds when tested manually in psql, but stall when called from application code? This discrepancy points to prepared statement plan caching.
By default, PostgreSQL executes a prepared statement using a custom plan for the first five runs. On the sixth run, it evaluates the generic plan cost against the average custom plan cost. If the generic plan appears cheaper on average, PostgreSQL saves CPU by reusing the generic plan indefinitely.
Generic plans ignore specific parameter distributions. If a parameter matches 99% of table rows on one call, but 0.001% on another call, the generic plan fails catastrophically for selective parameters.
Force custom planning for problematic sessions or queries by overriding the parameter:
SET plan_cache_mode = 'force_custom_plan';
If performance normalizes, your application driver is suffering from generic plan cached regressions. Keep force_custom_plan enabled for that specific query path.
Review Buffer Spills and Memory Allocation
Queries that perform sorts, aggregations, or hash operations require internal memory governed by the work_mem configuration. If a query requires more memory than allocated by work_mem, PostgreSQL silently writes temporary work files to physical disk storage.
Disk-based sorting is orders of magnitude slower than in-memory sorting. Inspect your plan output for warnings like this:
Sort Method: external merge Disk: 45820kB
Fix this instantly for a single long-running query by increasing local memory context without modifying global system defaults:
BEGIN;
SET LOCAL work_mem = '256MB';
-- Execute your query here
COMMIT;
Frequently Asked Questions
Why does my PostgreSQL query run fast manually but slow in my application?
This is almost always caused by prepared statement plan caching or parameter misinterpretation. Applications use prepared statements where PostgreSQL switches to generic execution plans after five executions. Manually running queries in psql generates a custom plan every time. Override this behavior by setting plan_cache_mode = force_custom_plan.
How can I find which query is causing sudden high CPU usage right now?
Query pg_stat_activity sorted by execution duration. Filter out idle connections to isolate running statements: SELECT pid, now() - query_start AS duration, query, state FROM pg_stat_activity WHERE state != 'idle' ORDER BY duration DESC LIMIT 5;.
Can index bloat cause a query to suddenly slow down?
Yes. Heavy update or delete workloads leave dead index entries behind. If autovacuum cannot clear them fast enough, index scans read bloated index pages from disk, consuming unnecessary I/O budget. Reindex the affected structure using REINDEX TABLE CONCURRENTLY table_name;.
Actionable Next Steps for Emergency Triage
Follow this checklist when responding to a degraded query incident:
- Check current locks: Ensure the query isn’t simply waiting on an uncommitted transaction.
- Run
EXPLAIN (ANALYZE, BUFFERS): Compare actual row counts against estimated values. Look for disk sorts or sequential scans. - Check stats: Query
pg_stat_user_tables. Iflast_analyzeis old, executeANALYZEon target tables immediately. - Inspect system memory: Determine if temporary disk files are created due to low
work_mem. - Check prepared plan caching: Test
SET plan_cache_mode = force_custom_planin your application session.

