Which table changed its habits? An hour-of-day baseline for pg_stat_user_tables
At 2 p.m. somebody says the database feels slow. pg_stat_statements can tell you which statements took the time, if it's installed and if the guilty query is one statement and not a few hundred slightly different ones. There's a question underneath that one that's often quicker to answer: which table started being read differently today?
PostgreSQL already counts that for you, per table, in pg_stat_user_tables. The counters are cumulative since the last reset, so on their own they say little. Snapshot them every hour, take the differences, and compare each hour with the same hour of the day over the last two weeks, and you get a table-level baseline that catches things like these:
- a plan that flipped from an index scan to a sequential scan after an ANALYZE or a parameter change
- an index somebody dropped, or one that was never created on the new partition
- a new report or ORM change that reads a big table end to end every few minutes
- a batch job that suddenly writes ten times its usual rows
It's three pieces of SQL, uses only the cumulative statistics system, and runs on PostgreSQL 12 and later. I tested it on 16.
1. Every hour, copy the counters
CREATE TABLE table_snap (
taken_at timestamptz NOT NULL,
relid oid NOT NULL,
relname text NOT NULL,
seq_scan bigint NOT NULL,
seq_tup_read bigint NOT NULL,
idx_scan bigint NOT NULL,
writes bigint NOT NULL, -- inserted + updated + deleted rows
n_dead_tup bigint NOT NULL,
stats_reset timestamptz, -- when this database's counters were last zeroed
PRIMARY KEY (relid, taken_at)
);
INSERT INTO table_snap
SELECT date_trunc('hour', now()), t.relid, t.schemaname || '.' || t.relname,
t.seq_scan, t.seq_tup_read, coalesce(t.idx_scan, 0),
t.n_tup_ins + t.n_tup_upd + t.n_tup_del, t.n_dead_tup,
d.stats_reset
FROM pg_stat_user_tables t
CROSS JOIN pg_stat_database d
WHERE d.datname = current_database()
ON CONFLICT DO NOTHING;
Run it a minute past every hour from cron or pg_cron. pg_stat_user_tables only shows the database you're connected to, so it has to run in each database you care about. pg_cron lives in one database, so use cron.schedule_in_database() (pg_cron 1.4+) for the others.
Keeping stats_reset from pg_stat_database is cheap insurance: it changes when someone runs pg_stat_reset(), and step 2 uses it to skip that hour.
2. Turn snapshots into one row per table per hour
CREATE TABLE table_hourly (
hour_start timestamptz NOT NULL,
relid oid NOT NULL,
relname text NOT NULL,
seq_scan bigint NOT NULL,
seq_tup_read bigint NOT NULL,
idx_scan bigint NOT NULL,
writes bigint NOT NULL,
n_dead_tup bigint NOT NULL, -- a level, not a counter: as of the end of the hour
PRIMARY KEY (relid, hour_start)
);
INSERT INTO table_hourly
SELECT prev_at, relid, relname,
seq_scan - prev_seq,
seq_tup_read - prev_seq_read,
idx_scan - prev_idx,
writes - prev_writes,
n_dead_tup
FROM (SELECT s.*,
lag(taken_at) OVER w AS prev_at,
lag(seq_scan) OVER w AS prev_seq,
lag(seq_tup_read) OVER w AS prev_seq_read,
lag(idx_scan) OVER w AS prev_idx,
lag(writes) OVER w AS prev_writes,
lag(stats_reset) OVER w AS prev_reset
FROM table_snap s
WHERE taken_at >= now() - interval '1 day' -- recent snapshots are enough
WINDOW w AS (PARTITION BY relid ORDER BY taken_at)) d
WHERE taken_at = prev_at + interval '1 hour' -- consecutive snapshots only
AND stats_reset IS NOT DISTINCT FROM prev_reset -- nobody ran pg_stat_reset() in between
AND seq_scan >= prev_seq -- and no counter went backwards
AND seq_tup_read >= prev_seq_read -- (crash, single-table reset)
AND idx_scan >= prev_idx
AND writes >= prev_writes
ON CONFLICT DO NOTHING;
Run it right after step 1. Unlike a statement baseline, this one keeps the quiet hours: a table that wasn't touched gets a row of zeros. That matters, because "this table is normally never sequentially scanned" is exactly the history you want the next step to see.
3. Flag the table that's reading far more than usual for this hour
WITH h AS (
SELECT relid, relname, hour_start, seq_scan, seq_tup_read, idx_scan,
extract(hour FROM hour_start AT TIME ZONE 'America/Denver') AS hod -- your users' time zone
FROM table_hourly
), base AS (
SELECT relid, hod,
percentile_cont(0.5) WITHIN GROUP (ORDER BY seq_tup_read) AS usual_rows,
percentile_cont(0.9) WITHIN GROUP (ORDER BY seq_tup_read) AS p90_rows,
percentile_cont(0.5) WITHIN GROUP (ORDER BY seq_scan) AS usual_scans,
percentile_cont(0.5) WITHIN GROUP (ORDER BY idx_scan) AS usual_idx,
count(*) AS samples
FROM h
WHERE hour_start >= date_trunc('day', now()) - interval '14 days'
AND hour_start < date_trunc('day', now())
GROUP BY relid, hod
)
SELECT h.relname,
h.seq_scan AS seq_scans,
round(b.usual_scans) AS usual_seq_scans,
h.idx_scan AS idx_scans,
round(b.usual_idx) AS usual_idx_scans,
h.seq_tup_read AS rows_read,
round(b.usual_rows) AS usual_rows_read,
round(h.seq_tup_read - b.usual_rows) AS extra_rows
FROM h
JOIN base b USING (relid, hod)
WHERE h.hour_start = date_trunc('hour', now()) - interval '1 hour'
AND b.samples >= 7 -- enough history to trust
AND h.seq_tup_read > greatest(2 * b.usual_rows, b.p90_rows) -- well above its usual range
AND h.seq_tup_read - b.usual_rows >= 1000000 -- and at least a million extra rows
ORDER BY extra_rows DESC;
On my test data (16 days of hourly snapshots for three tables, one with a nightly 02:00 report, one with a normal 9-to-5 swing, one tiny lookup table that's scanned all day, plus a pg_stat_reset() in the middle) it returned one row:
relname | seq_scans | usual_seq_scans | idx_scans | usual_idx_scans | rows_read | usual_rows_read | extra_rows
---------------+-----------+-----------------+-----------+-----------------+-----------+-----------------+------------
public.orders | 40 | 0 | 500 | 20656 | 8000000 | 0 | 8000000
That's the shape of a plan flip: sequential scans out of nowhere, index scans down to almost nothing, eight million rows read that normally aren't. The 9 a.m. jump on the busy table and the nightly report didn't show up, because they're normal for their hour. The reset hour was skipped instead of showing up as a giant negative number.
From here, pg_stat_statements (filter on the table name in query) or auto_explain tells you which statement it was. The table baseline just tells you where to look first.
The same query works for writes: swap seq_tup_read for writes to catch the job that's suddenly updating a million rows an hour.
Things that will bite you
- Stats land when the transaction ends. Backends report their table counters after a transaction finishes, not while it runs. A three-hour sequential scan shows up in the hour it ended, not spread across the three.
- Resets.
pg_stat_reset(),pg_stat_reset_single_table_counters(), a crash or an immediate shutdown, and a major-versionpg_upgradeall zero the counters. Step 2 skips hours where any counter went backwards orstats_resetchanged. Clean shutdowns keep the stats. - Partitions. Stats are per partition. To see the parent, group by
pg_partition_root(relid)(PG 12+) in step 3. A new monthly partition also has no history, so it won't be flagged until it has seven samples for that hour. - Small tables are supposed to be scanned. A 40-row lookup table is cheaper to scan than to index. The million-row floor keeps them out. Tune it to your sizes.
- n_live_tup and n_dead_tup are estimates and levels. Don't diff them. Comparing n_dead_tup with its usual for the hour is still a decent "autovacuum is falling behind on this table" signal.
- Median, not mean. One terrible hour last Tuesday shouldn't move what counts as normal. percentile_cont handles that, and Postgres has it built in.
- Weekly cycles. If Mondays are different, add day of week to the group, or compare with the same hour seven days ago. You'll need more history for that.
- Normal isn't good. A table that's been sequentially scanned every hour for a month has a baseline full of sequential scans. This finds changes. It doesn't find problems that were already there.
- Housekeeping. Keep a couple of days of table_snap and five or six weeks of table_hourly. At 2,000 tables that's about two million rows, which is nothing, but delete the old ones anyway.
How do you catch a plan flip on your systems: table stats like this, pg_stat_statements, auto_explain, or something else? I'd like to hear what works.
Brett Rosenblatt is a DBA and performance engineer and a co-founder of Bandlei, which makes ReinDB, a read-only performance monitor for PostgreSQL and other databases. This post is adapted from chapter 12 of his free tuning guide, Rein In Your Database.