← Back to SQL, page 24

sql-0466 · Medium mid

CPU on the database server is at 100 percent and the application is slow. How do you find the cause?

Look at what is running now (pg_stat_activity: active queries, their duration and wait events) and at cumulative query statistics (pg_stat_statements sorted by total time). Usually a few query shapes dominate, often because of a missing index, a plan change or a sudden increase in call volume. Fix the top offender, and cancel runaway queries if needed.

Full answer

Steps:

  1. 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;
  2. Top statements: from pg_stat_statements, order by total_exec_time to find the shapes consuming most CPU overall, and by calls to spot a query that suddenly runs thousands of times per second (often an N+1 or a cache outage).
  3. Plans: EXPLAIN (ANALYZE, BUFFERS) the top shape with realistic parameters.
  4. Recent changes: deploys, new indexes dropped, statistics, traffic spikes, a batch job started.
  5. 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