PostgreSQL CPU is at 100%. How do you investigate?

IntermediateTroubleshootingPostgreSQL
Answer

Short answer

Find which queries are using the CPU right now and over time, check for missing indexes (sequential scans on big tables), stale statistics, a sudden traffic increase, or something new (deployment, a report, a cron job). Fix the top offenders rather than just adding CPU.

Steps

-- 1. What's running now?
SELECT pid, now() - query_start AS runtime, state, left(query, 100)
FROM pg_stat_activity WHERE state = 'active' ORDER BY runtime DESC;

-- 2. Which queries cost the most overall?
SELECT calls, round(total_exec_time) total_ms, round(mean_exec_time) avg_ms, left(query, 100)
FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 10;

-- 3. Tables being scanned sequentially a lot
SELECT relname, seq_scan, seq_tup_read, idx_scan
FROM pg_stat_user_tables ORDER BY seq_tup_read DESC LIMIT 10;

Then EXPLAIN (ANALYZE, BUFFERS) the worst query.

Common causes and fixes

Cause Fix
New query without index (just deployed) Add index (CONCURRENTLY) or roll back
Bad plan from stale stats ANALYZE table
Traffic spike / N+1 queries from the app Caching, fix the ORM pattern, read replicas
Heavy report on primary Move to a replica
Too many connections thrashing PgBouncer

What to say in the interview

"Live queries from pg_stat_activity, top consumers from pg_stat_statements, tables with heavy sequential scans, then EXPLAIN ANALYZE. I correlate with recent deployments — usually it's a missing index, stale statistics or an N+1 pattern — and fix that before scaling up."

All Databases (MySQL, PostgreSQL, MongoDB) questions Roadmap: PostgreSQL basics

More on PostgreSQL