Finding slow queries with pg_stat_statements and auto_explain
Using pg_stat_statements on Postgres 18 to rank queries by total time, auto_explain to catch the plan of a slow query in the logs while it is slow, and a snapshot table so you never have to reset the stats to see what changed.
"The database is slow" is not something you can fix. You need the query, how often it runs, how long it takes, and what plan it used at the moment it was slow. Postgres ships two extensions for exactly this: pg_stat_statements for the numbers and auto_explain for the plans.
In this blog we will turn both on, run a small mixed workload, find the worst query and catch its plan from the logs. It is an intermediate post and the last one so far in my Postgres in production series, after connection pooling with PgBouncer. If you use PgHero, its query page reads from pg_stat_statements too, so this is what sits underneath it. I used Postgres 18.7 (postgres:18-alpine, extension version 1.12) and the shorty tables from the index design post: 200k links, 2 million clicks.
Turning them on
Both have to be loaded when the server starts, through shared_preload_libraries. With Docker I pass it on the command line:
docker run -d --name pg18 -p 5432:5432 -e POSTGRES_PASSWORD=secret \
postgres:18-alpine -c shared_preload_libraries=pg_stat_statements,auto_explain
On a normal install it goes into postgresql.conf and needs a restart, not a reload. That restart is the annoying part, so I'd put both in on day one, before you need them. Then create the extension in each database you want to query it from:
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
The defaults were fine for me: pg_stat_statements.max is 5000 distinct queries, track is top (statements inside functions are folded into the call), and compute_query_id is auto, which turns on once the extension is loaded.
A workload to look at
I wrote four small pgbench scripts that looks like shorty traffic. The redirect is the busy one:
-- redirect.sql
\set id random(1, 200000)
SELECT url FROM links WHERE code = substr(md5(:id::text), 1, 10) AND deleted_at IS NULL;
-- link_stats.sql
\set id random(1, 200000)
SELECT country, count(*) FROM clicks WHERE link_id = :id GROUP BY country;
-- owner_links.sql
\set owner random(1, 5000)
SELECT id, code, created_at FROM links WHERE owner_id = :owner ORDER BY created_at DESC LIMIT 20;
-- daily_report.sql
SELECT date_trunc('day', clicked_at) AS day, count(*)
FROM clicks WHERE clicked_at > now() - interval '7 days'
GROUP BY 1 ORDER BY 1;
I copied the scripts into the container with docker cp. pgbench takes a weight per script after @. 8 clients for 30 seconds:
docker exec pg18 psql -U postgres -d shorty -c "SELECT pg_stat_statements_reset()"
docker exec pg18 pgbench -U postgres -n -c 8 -j 2 -T 30 \
-f /tmp/redirect.sql@50 -f /tmp/link_stats.sql@10 \
-f /tmp/owner_links.sql@5 -f /tmp/daily_report.sql@1 shorty
number of transactions actually processed: 35507
tps = 1177.703587 (without initial connection time)
Top queries by total time
This is the query I run first, every time:
SELECT queryid,
calls,
round(total_exec_time::numeric, 0) AS total_ms,
round(mean_exec_time::numeric, 2) AS mean_ms,
round((100 * total_exec_time / sum(total_exec_time) OVER ())::numeric, 1) AS pct,
rows,
left(regexp_replace(query, '\s+', ' ', 'g'), 60) AS query
FROM pg_stat_statements
WHERE dbid = (SELECT oid FROM pg_database WHERE datname = current_database())
ORDER BY total_exec_time DESC
LIMIT 6;
queryid | calls | total_ms | mean_ms | pct | rows | query
----------------------+-------+----------+---------+------+-------+--------------------------------------------------------------
8242943872869432028 | 546 | 176178 | 322.67 | 76.9 | 4368 | SELECT date_trunc($1, clicked_at) AS day, count(*) FROM clic
-4749719113751484019 | 2653 | 41761 | 15.74 | 18.2 | 53053 | SELECT id, code, created_at FROM links WHERE owner_id = $1 O
-4248408959356034925 | 5423 | 9717 | 1.79 | 4.2 | 22619 | SELECT country, count(*) FROM clicks WHERE link_id = $1 GROU
-5023262438278785483 | 26885 | 1315 | 0.05 | 0.6 | 24252 | SELECT url FROM links WHERE code = substr(md5($1::text), $2,
Sort by total time only, not by mean. The redirect ran 26885 times and only cost 0.6% of the time. The daily report ran 546 times and ate 77% of it. The constants are replaced by $1, $2 so every owner and every code count as one query.
The second view I use is by blocks read, because time on a laptop is noisy and blocks are not:
query | calls | blocks | blocks_per_call | hit_pct
----------------------------------------------------+-------+---------+-----------------+---------
SELECT date_trunc($1, clicked_at) AS day, count(*) | 546 | 8050483 | 14744 | 89.6
SELECT id, code, created_at FROM links WHERE owner | 2653 | 6791009 | 2559 | 100.0
SELECT url FROM links WHERE code = substr(md5($1:: | 26885 | 104907 | 3 | 79.1
SELECT country, count(*) FROM clicks WHERE link_id | 5423 | 70937 | 13 | 82.7
14744 blocks per call is the whole clicks table. 2559 per call for the owner query is the whole links table. Both are sequential scans, no plan needed to tell. The owner query actually surprised me. There is an index for exactly this, but it is the partial one from the index post, WHERE deleted_at IS NULL, and this query forgot the filter. That's the catch I wrote about there, and it showed up in my own test script.
The query for that view, shared_blks_hit + shared_blks_read divided by calls, is in the code for this post.
Catching the plan with auto_explain
pg_stat_statements tells you which query. It doesn't tell you why. And when you run the query again yourself with EXPLAIN ANALYZE, it is often fast. That is what happened to me. Alone, the daily report took 60 ms:
Execution Time: 60.783 ms
Under load the mean was 322 ms. auto_explain logs the plan of any statement slower than a threshold, at the time it happens. I turned it on without a restart (the library was already preloaded):
ALTER SYSTEM SET auto_explain.log_min_duration = '200ms';
ALTER SYSTEM SET auto_explain.log_analyze = on;
ALTER SYSTEM SET auto_explain.log_buffers = on;
ALTER SYSTEM SET auto_explain.log_timing = off;
SELECT pg_reload_conf();
Small surprise: a SHOW auto_explain.log_min_duration in the same psql call still printed -1. The session that sends the reload doesn't always see the new value straight away, so check from a fresh connection. I ran the report alone a couple of times and nothing was logged, of course, 60 ms is under the threshold. So I ran the pgbench mix for 8 seconds and checked docker logs pg18:
LOG: duration: 334.251 ms plan:
Query Text: SELECT date_trunc('day', clicked_at) AS day, count(*)
FROM clicks WHERE clicked_at > now() - interval '7 days'
GROUP BY 1 ORDER BY 1;
GroupAggregate (cost=35586.89..56266.49 rows=154364 width=16) (actual rows=8.00 loops=1)
Group Key: (date_trunc('day'::text, clicked_at))
Buffers: shared hit=13522 read=1184
-> Gather Merge (cost=35586.89..53565.12 rows=154364 width=8) (actual rows=155441.00 loops=1)
Workers Planned: 2
Workers Launched: 0
Buffers: shared hit=13522 read=1184
-> Sort (cost=34586.86..34747.66 rows=64318 width=8) (actual rows=155441.00 loops=1)
Sort Key: (date_trunc('day'::text, clicked_at))
Sort Method: quicksort Memory: 4096kB
-> Parallel Seq Scan on clicks (cost=0.00..29450.13 rows=64318 width=8) (actual rows=155441.00 loops=1)
Filter: (clicked_at > (now() - '7 days'::interval))
Rows Removed by Filter: 1844559
Workers Planned: 2, Workers Launched: 0. The plan counted on two parallel workers to scan the table and under load got none, most likely because the other sessions had taken them all (max_parallel_workers is 8 and I had 8 clients). That is why it was five times slower than my test by hand. I would never have seen that from a manual EXPLAIN ANALYZE.
Postgres 18 makes this visible in pg_stat_statements too, there are two new columns for it:
SELECT left(regexp_replace(query, '\s+', ' ', 'g'), 40) AS query, calls,
parallel_workers_to_launch AS to_launch,
parallel_workers_launched AS launched
FROM pg_stat_statements
WHERE parallel_workers_to_launch > 0;
query | calls | to_launch | launched
------------------------------------------+-------+-----------+----------
SELECT date_trunc($1, clicked_at) AS day | 789 | 1578 | 882
SELECT id, code, created_at FROM links W | 3817 | 3817 | 2843
A few notes on the settings. log_analyze runs every statement with instrumentation, which costs something; log_timing = off removes most of that and still gives row counts. On a busy server, set auto_explain.sample_rate to something like 0.1. And for a quick look in one session you don't need the logs at all:
SET auto_explain.log_min_duration = 0;
SET auto_explain.log_level = notice;
SELECT id, code FROM links WHERE owner_id = 77 ORDER BY created_at DESC LIMIT 3;
NOTICE: duration: 0.113 ms plan:
Query Text: SELECT id, code FROM links WHERE owner_id = 77 ORDER BY created_at DESC LIMIT 3
Limit (cost=0.42..12.77 rows=3 width=27)
-> Index Scan using links_owner_created on links (cost=0.42..165.12 rows=40 width=27)
Index Cond: (owner_id = 77)
Fixing and checking
Two indexes, built concurrently as in the schema changes post:
CREATE INDEX CONCURRENTLY clicks_clicked_at ON clicks (clicked_at);
CREATE INDEX CONCURRENTLY links_owner_created ON links (owner_id, created_at DESC);
Then I reset the stats for just those two queries, not everything. pg_stat_statements_reset takes user id, database id and query id, and 0 means "any":
SELECT pg_stat_statements_reset(0, 0, queryid)
FROM pg_stat_statements
WHERE query LIKE 'SELECT date_trunc%' OR query LIKE 'SELECT id, code, created_at FROM links%';
Same 30 second run again:
tps = 13784.469418 (without initial connection time)
calls | mean_ms | total_ms | stats_since | query
--------+---------+----------+-------------+----------------------------------------------------
6354 | 30.03 | 190811 | 06:43:15 | SELECT date_trunc($1, clicked_at) AS day, count(*)
70597 | 0.33 | 23608 | 06:41:59 | SELECT country, count(*) FROM clicks WHERE link_id
352961 | 0.01 | 5004 | 06:41:59 | SELECT url FROM links WHERE code = substr(md5($1::
30803 | 0.04 | 1153 | 06:43:15 | SELECT id, code, created_at FROM links WHERE owner
From 1177 to 13784 transactions per second. The owner query went from 15.7 ms to 0.04 ms. The report went from 322 ms to 30 ms, and it is still at the top by total time, because now it runs ten times as often. There is always a top query. The question is whether it is worth fixing, and for a report that gives the same answer all day I'd cache it or keep a daily rollup table rather than add more indexes. stats_since shows which rows were reset, that column exists since Postgres 17.
Don't reset, take snapshots
Calling pg_stat_statements_reset() every time you want fresh numbers throws away history, and if two people do it they basically confuse each other. I prefer copying the view into a table now and then and comparing:
CREATE TABLE IF NOT EXISTS pgss_snapshot AS
SELECT now() AS taken_at, queryid, dbid, userid, calls, total_exec_time, rows, query
FROM pg_stat_statements WITH NO DATA;
INSERT INTO pgss_snapshot
SELECT now(), queryid, dbid, userid, calls, total_exec_time, rows, query
FROM pg_stat_statements;
And the diff between the last two snapshots:
WITH s AS (
SELECT DISTINCT taken_at FROM pgss_snapshot ORDER BY taken_at DESC LIMIT 2
), cur AS (
SELECT * FROM pgss_snapshot WHERE taken_at = (SELECT max(taken_at) FROM s)
), prev AS (
SELECT * FROM pgss_snapshot WHERE taken_at = (SELECT min(taken_at) FROM s)
)
SELECT cur.calls - coalesce(prev.calls, 0) AS calls,
round((cur.total_exec_time - coalesce(prev.total_exec_time, 0))::numeric, 0) AS ms,
left(regexp_replace(cur.query, '\s+', ' ', 'g'), 50) AS query
FROM cur
LEFT JOIN prev USING (queryid, dbid, userid)
WHERE cur.calls - coalesce(prev.calls, 0) > 0
ORDER BY ms DESC
LIMIT 5;
calls | ms | query
--------+------+----------------------------------------------------
20357 | 3228 | SELECT country, count(*) FROM clicks WHERE link_id
102554 | 1412 | SELECT url FROM links WHERE code = substr(md5($1::
That was a 5 second run in between. Run the insert from cron every hour, delete rows older than couple of weeks, and you can answer "what got slower since Tuesday's deploy". Also watch dealloc in pg_stat_statements_info: if it keeps going up, 5000 entries is too few and old queries are being thrown out.
When you are done, docker rm -f pg18. With the numbers from this post and the plans from the EXPLAIN post, you have most of what you need to read a slow database.