Video in progress
Postgres CPU hit 100% on prod and the application slowed down. What do you do in the first 15 minutes?
First I determine who and what is eating the CPU: active queries in pg_stat_activity, recent changes in pg_stat_statements, whether a deploy or the traffic changed. Then I limit the damage (cancel the heavy query, a feature flag, a rollback), and I analyze the cause in depth later.
📖 Answer
The order matters: restore the service first, investigate after.
-
Context (1-2 minutes). The latest deploy, migration, the traffic graph, cron jobs. In 80% of cases the answer is here.
-
What is running right now:
SELECT pid, now() - query_start AS runtime, state, wait_event_type, wait_event,
left(query, 120)
FROM pg_stat_activity
WHERE state <> 'idle' AND backend_type = 'client backend'
ORDER BY runtime DESC;
Hundreds of identical queries that are active with an empty wait_event mean pure CPU. If most of them are waiting on Lock, it isn't a CPU problem, it's a lock problem.
-
A delta, not an absolute number. I take a
pg_stat_statementssnapshot, take another a minute later, and sort by the difference intotal_exec_time. Absolute values have been accumulating for months. -
Limit the damage:
- a single runaway query:
pg_cancel_backend(pid), andpg_terminate_backendif needed; - if new code is the cause: a rollback or a feature flag;
- if the plan changed (statistics got refreshed and the query picked a different plan):
ANALYZE, or a quick index; - if the number of connections exploded: cap the pool on the application side and stop the retry storm.
- Then the analysis: the
auto_explainlogs, the plan before and after, and why monitoring didn't warn earlier.
Typical causes from my experience: a new query without an index, stale statistics leading to a bad plan, an N+1 blowing up when traffic rises, a cache collapsing so every request hits the DB, and an "innocent" dashboard doing count(*). The key is not to raise max_connections in a panic: that makes a CPU problem worse.
Sign up to mark studied questions and save your progress.