← Back to PostgreSQL, page 5

postgresql-0091 · Hard senior

After a deploy, database CPU doubles but no single query looks slow. How do you find the cause with pg_stat_statements?

pg_stat_statements aggregates execution counts, total and mean time, rows and buffer use per normalised query. Sort by total_exec_time, not mean time: a cheap query whose call count jumped from thousands to millions, often an N+1 loop introduced by the deploy, dominates CPU while each call stays fast. Compare snapshots before and after the deploy, then fix the code path or add caching.

Full answer

Approach:

  1. Ensure the extension is loaded (shared_preload_libraries) and take snapshots of pg_stat_statements periodically, or reset it after the deploy to see the new pattern clearly.
  2. Rank by total time and by calls (illustrative, not run here):
sql
SELECT queryid, calls, round(total_exec_time) AS total_ms, round(mean_exec_time, 2) AS mean_ms,
       rows, shared_blks_hit + shared_blks_read AS blocks, left(query, 80) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 15;
  1. Compare with the previous snapshot: look for queries whose calls per minute rose sharply, new queries, or rising blocks per call, which suggests a plan change or a missing index.
  2. Map the query back to code through application tracing, query comments added by the ORM, or the query text.

Common findings: a new loop issuing one query per item, an ORM relationship loaded lazily inside a serializer, a cache that is no longer hit because of a key change, or a query whose plan changed to a sequential scan after statistics shifted. Each needs a different fix: batching or eager loading, restoring the cache, or an index or statistics change. Track calls per request as a metric so the next regression is caught in staging.

Key points

  • Rank by total time, not mean time
  • Call counts reveal N+1 regressions
  • Compare before and after snapshots
  • Rising blocks per call hint at plan changes
  • Map queries back to code

Common mistakes

  • Looking only at the slowest single queries
  • Resetting statistics without saving a snapshot

Follow-ups

  • How do you track plan changes over time?
  • What does track_io_timing add?

Tips

  • Sort by total_exec_time