Video in progress

How do you find out which queries are slow on prod?

The pg_stat_statements extension collects the call count and total time for each query shape, and I start by sorting by total_exec_time. In addition, log_min_duration_statement writes slow queries to the log, and auto_explain adds their plans too.

📖 Answer

The most useful tool is pg_stat_statements. It replaces parameters with $1 and merges queries of the same shape:

SELECT calls,
       round(total_exec_time) AS total_ms,
       round(mean_exec_time, 1) AS avg_ms,
       rows,
       left(query, 120) AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 15;

Why by total and not mean? A 3-second monthly report runs once a day. A 4 ms query gets called 2,000 times a second and eats half the database's CPU. Optimization often starts with the second kind.

Writing slow queries to the log:

log_min_duration_statement = 500ms
shared_preload_libraries = 'pg_stat_statements,auto_explain'
auto_explain.log_min_duration = 1s
auto_explain.log_analyze = on

auto_explain.log_analyze adds extra overhead to every query; on a very busy system, turn it on with log_timing = off.

To see the queries running right now, use pg_stat_activity: state, wait_event_type, now() - query_start. If a query is slow and shows wait_event_type = 'Lock', the problem isn't in the plan, it's in a lock.

Then I check the query I found with EXPLAIN (ANALYZE, BUFFERS) on data close to prod. On an empty dev database the plan comes out completely different.