Sub topic 14
Monitoring bloat and building a maintenance routine
Earlier chapters covered how bloat forms, how VACUUM and autovacuum clean it up, and how to reclaim space when they cannot. This chapter turns those tools into a routine: what to watch, how often, which thresholds to alert on, and what to do when an alert fires.
I assume you can read pg_stat_user_tables, know what pgstattuple does, and have run VACUUM (VERBOSE) before. Superuser or pg_monitor membership is needed for some of the queries below.
What to monitor
Bloat is a symptom. The causes are usually one of three things: autovacuum is not keeping up, something blocks cleanup, or the write pattern generates more dead rows than the settings expect. A useful monitoring setup therefore watches the symptom and the causes.
| Signal | Where to read it | What it tells you |
|---|---|---|
| Dead tuples and dead percentage | `pg_stat_user_tables` | Whether cleanup keeps up with churn |
| Time since last autovacuum | `pg_stat_user_tables` | Whether autovacuum reaches the table at all |
| Oldest snapshot age | `pg_stat_activity`, `pg_replication_slots`, `pg_prepared_xacts` | Whether something blocks cleanup |
| Table and index size over time | `pg_relation_size`, `pg_total_relation_size` | Real growth, which statistics can miss |
| HOT update ratio | `pg_stat_user_tables` | Whether updates create index churn |
| Transaction ID age | `pg_database`, `pg_class` | Distance from wraparound |
| Autovacuum duration and activity | server log, `pg_stat_progress_vacuum` | Whether runs are slow or constantly restarting |
Routine checks
Dead tuples per table
Start with the cheap statistics view. It reads counters the server already maintains, so you can run it every few minutes.
SELECT relname,
n_live_tup,
n_dead_tup,
round(100.0 * n_dead_tup / nullif(n_live_tup + n_dead_tup, 0), 1) AS dead_pct,
last_vacuum,
last_autovacuum
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC
LIMIT 10;These counts are estimates updated by the statistics system. They reset after a crash or a call to pg_stat_reset(), so a table that looks clean right after a restart may not be. A high dead_pct on a small table is rarely worth attention. A moderate percentage on a table with hundreds of millions of rows is.
Exact figures when estimates disagree
When the estimates look wrong, or before you decide on a rewrite, measure the table directly. pgstattuple reads the whole table, so run it off-peak and on one table at a time.
CREATE EXTENSION IF NOT EXISTS pgstattuple;
SELECT table_len,
tuple_count,
dead_tuple_count,
dead_tuple_percent,
free_space,
free_percent
FROM pgstattuple('public.orders');Large free_percent with a small dead_tuple_percent means VACUUM already did its work. The space is reusable but not returned to the operating system. That is normal for a table that will be written to again, and it is not a reason to rewrite.
Size over time
Neither query above shows growth. Record sizes on a schedule, in a small history table or in your metrics system, and compare against row counts.
SELECT c.relname,
pg_size_pretty(pg_table_size(c.oid)) AS table_size,
pg_size_pretty(pg_indexes_size(c.oid)) AS index_size,
s.n_live_tup
FROM pg_class c
JOIN pg_stat_user_tables s ON s.relid = c.oid
ORDER BY pg_total_relation_size(c.oid) DESC
LIMIT 10;A table whose size grows while its live row count stays flat is the clearest sign of bloat. Indexes on that table usually follow it.
HOT update ratio
HOT (heap-only tuple) updates avoid creating new index entries. A low ratio on a heavily updated table is a cue to look at fillfactor and at which columns are indexed.
SELECT relname,
n_tup_upd,
n_tup_hot_upd,
round(100.0 * n_tup_hot_upd / nullif(n_tup_upd, 0), 1) AS hot_pct
FROM pg_stat_user_tables
WHERE n_tup_upd > 10000
ORDER BY n_tup_upd DESC
LIMIT 10;Blockers
When dead tuples keep growing even though autovacuum runs, look for old snapshots. Check all three sources, because any one of them can hold back cleanup for the whole database.
SELECT pid,
state,
xact_start,
age(backend_xmin) AS xmin_age,
left(query, 60) AS query
FROM pg_stat_activity
WHERE backend_xmin IS NOT NULL
ORDER BY age(backend_xmin) DESC
LIMIT 5;SELECT slot_name,
active,
age(xmin) AS xmin_age,
age(catalog_xmin) AS catalog_xmin_age
FROM pg_replication_slots
ORDER BY greatest(age(xmin), age(catalog_xmin)) DESC NULLS LAST;
SELECT gid,
prepared,
age(transaction) AS xid_age
FROM pg_prepared_xacts
ORDER BY prepared;An inactive replication slot or a forgotten prepared transaction is the usual culprit when no session looks old. These do not show up in pg_stat_activity.
Wraparound distance
Freezing keeps transaction ID age under control. Alert well before the hard limit of about 2 billion. A common warning point is when age passes the point where autovacuum starts anti-wraparound runs (autovacuum_freeze_max_age, 200 million by default) and keeps climbing.
SELECT datname,
age(datfrozenxid) AS xid_age
FROM pg_database
ORDER BY xid_age DESC;
SELECT relname,
age(relfrozenxid) AS xid_age
FROM pg_class
WHERE relkind IN ('r', 'm', 't')
ORDER BY xid_age DESC
LIMIT 10;Autovacuum in the log and in progress
By default, autovacuum is silent. Make it log any run that takes longer than a second so you can see how long runs take, how many pages they scan, and whether they were cancelled.
ALTER SYSTEM SET log_autovacuum_min_duration = '1s';
SELECT pg_reload_conf();To see a run that is happening now, use the progress view.
SELECT pid,
relid::regclass AS table_name,
phase,
heap_blks_total,
heap_blks_scanned,
heap_blks_vacuumed
FROM pg_stat_progress_vacuum;If the same big table is always in this view, autovacuum is spending its capacity there. Raise the cost limit or the worker count, as covered in the tuning chapter.
Index checks
Indexes bloat separately from their tables, and VACUUM does not shrink them. Track index size and use. An index that is large, rarely scanned, and growing is a candidate for dropping or rebuilding.
SELECT s.relname AS table_name,
s.indexrelname AS index_name,
s.idx_scan,
pg_size_pretty(pg_relation_size(s.indexrelid)) AS index_size
FROM pg_stat_user_indexes s
ORDER BY pg_relation_size(s.indexrelid) DESC
LIMIT 10;For the indexes that you decide to rebuild, use the concurrent form so writes continue.
REINDEX INDEX CONCURRENTLY public.orders_customer_id_idx;Deciding what to do
Alerts need a response. The flow below puts the earlier chapters in order. It starts with the cheapest and least risky action.
Fix blockers first. Running VACUUM FULL or a repack while an old snapshot exists wastes effort, because new dead rows pile up again as soon as the rewrite finishes.
Rewrite options at a glance
When the flow ends in a rewrite, the tools differ mainly in locking and prerequisites.
pg_repack --dbname=mydb --table=public.orderspg_repack needs its extension installed and a primary key or a unique index on NOT NULL columns. It also needs free disk space roughly equal to the table plus its indexes. Test it on a copy first. The built-in REPACK public.orders; command exists only in versions that ship it, and its default form can take a strong lock. Read your version's documentation before relying on it.
A maintenance routine
Group tasks by how often they happen. The cadence below is a starting point. Adjust it to your write volume.
| Frequency | Task | Action if it fails |
|---|---|---|
| Continuous | Alert on oldest snapshot age, inactive slots, prepared transactions, and XID age | Page someone. These grow without bound |
| Every few minutes | Collect dead tuples, table size, and autovacuum counts into your metrics | Review per-table settings |
| Daily | Review the top tables by dead tuples and by size growth | Tune autovacuum for the tables that lead |
| Weekly | Review index size and `idx_scan`, plus the HOT ratio on hot tables | Drop unused indexes, adjust fillfactor, or reindex |
| Monthly or before a major change | Run `pgstattuple` on the largest or most worrying tables | Plan a repack if free space stays high and reuse does not help |
| After each incident | Record which blocker or setting caused it | Add an alert so you catch it earlier next time |
Some starting thresholds for alerts, to be tuned against your own baseline:
- Oldest transaction or snapshot older than 15 to 60 minutes on an OLTP system.
- Any replication slot inactive for longer than your tolerance for retained WAL and held-back cleanup.
- Any prepared transaction older than a few minutes.
- XID age above the freeze trigger and still growing.
- Dead tuple percentage above 20 on a large table, or dead tuples growing across several samples.
- Table size growth with flat live row counts across a week.
Common errors
- Trusting
n_dead_tupalone. The figure is an estimate and can be stale or reset. Confirm withpgstattuplebefore taking action. - Rewriting a table that is not bloated. Free space inside a table is reused by future writes. A rewrite there only costs a lock or heavy I/O.
- Ignoring replication slots and prepared transactions. They hold back cleanup without appearing as sessions.
- Monitoring tables but not indexes. A table can be clean while its indexes keep growing.
- Fixing symptoms repeatedly. If the same table needs a rewrite every quarter, change its autovacuum settings, fillfactor, or the application's transaction behavior.
Exercise
A table's size has doubled over a month while its live row count is flat. pg_stat_user_tables shows last_autovacuum was this morning, yet n_dead_tup keeps climbing. Which three queries do you run first, and what do you decide from them?
Show answer
Run the snapshot query against pg_stat_activity (oldest age(backend_xmin)), the pg_replication_slots query (inactive or old xmin/catalog_xmin), and the pg_prepared_xacts query. Autovacuum is running, but dead tuples are still growing, so something is probably holding back cleanup. If one of them shows an old snapshot, end that transaction, drop or repair the slot, or resolve the prepared transaction. Then let VACUUM run and watch whether n_dead_tup falls. Only if size stays high after that, check pgstattuple and consider a repack.
Exercise
You find that public.orders has free_percent of 40 and dead_tuple_percent near 0 according to pgstattuple, and the table's size has been stable for months. Should you run VACUUM FULL? Explain.
Show answer
Probably not. The low dead percentage means VACUUM has already cleaned the rows, and the stable size means the free space is being reused by new writes. A rewrite would take an ACCESS EXCLUSIVE lock and only shrink the file temporarily. Rewrite only if you need to return space to the operating system, for example after a one-off bulk delete, and then prefer an online tool such as pg_repack if the lock is unacceptable.