Video in progress
The row count in a table hasn't changed, but its size has tripled. What is going on, and how do you fix it?
This is bloat: autovacuum isn't getting around to cleaning up the dead rows left by UPDATE/DELETE, or some long transaction is preventing the cleanup. I find the cause and tune autovacuum to be more aggressive for that table; to give the space back to the OS I'll need pg_repack.
📖 Answer
First I measure:
SELECT relname, n_live_tup, n_dead_tup,
last_autovacuum, autovacuum_count
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC LIMIT 10;
If n_dead_tup is large and last_autovacuum is old, autovacuum isn't starting or can't finish. Common causes:
- A long transaction or an old snapshot. VACUUM can't remove versions that someone might still see. In
pg_stat_activity, look for sessions with an oldxact_startor inidle in transaction. A forgotten replication slot, or a long query on a replica withhot_standby_feedbackon, has the same effect. - The threshold doesn't fit a big table. The default
autovacuum_vacuum_scale_factor = 0.2: on a table with 100 million rows, it waits until 20 million dead rows pile up. - Autovacuum is too slow. The cost limit throttles it, and under heavy load it can't keep up.
A separate setting for a hot table:
ALTER TABLE orders SET (
autovacuum_vacuum_scale_factor = 0.02,
autovacuum_vacuum_cost_limit = 2000
);
An important subtlety: a regular VACUUM frees space for reuse inside the table, but doesn't shrink the file (it only trims empty pages at the end). VACUUM FULL does shrink it, but it locks the table with ACCESS EXCLUSIVE, which on prod is downtime. That's why I use pg_repack: it builds a copy and swaps it in at the end with a short lock.
Sign up to mark studied questions and save your progress.