Full answer
Approach:
- 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.
- 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;- 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.
- 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