Full answer
Steps:
- Current activity:
SELECT pid, now() - query_start AS runtime, state, wait_event, left(query, 80) FROM pg_stat_activity WHERE state <> 'idle' ORDER BY runtime DESC; - Top statements: from
pg_stat_statements, order bytotal_exec_timeto find the shapes consuming most CPU overall, and bycallsto spot a query that suddenly runs thousands of times per second (often an N+1 or a cache outage). - Plans:
EXPLAIN (ANALYZE, BUFFERS)the top shape with realistic parameters. - Recent changes: deploys, new indexes dropped, statistics, traffic spikes, a batch job started.
- Relief:
pg_cancel_backend(pid)stops a query;pg_terminate_backend(pid)ends the session. Rate-limit the offending endpoint if needed.
Then fix: add the missing index, rewrite the query, restore the cache, or move the batch job off-peak. CPU-bound databases are rarely solved by more CPU alone. These views are PostgreSQL-specific; described here, not run.
Key points
- Check current activity first
- Rank query shapes by total time
- Look for call volume spikes
- Explain the top offender
- Cancel before terminate
Common mistakes
- Restarting the database without finding the cause
- Optimising rare queries while a frequent one dominates
Follow-ups
- What does pg_stat_statements normalise?
- When would you terminate instead of cancel?
Tips
- Sort by total time, not average