What VACUUM does and why Postgres needs it
Postgres uses MVCC: an UPDATE does not change a row in place. It writes a new version and marks the old one as dead once no transaction can still see it. A DELETE only marks the row. The dead versions stay in the table file until something cleans them.
That something is VACUUM. According to the PostgreSQL documentation it does four jobs: it recovers or reuses the space of dead rows, it can update the planner statistics, it updates the visibility map that index-only scans depend on, and it protects old data from transaction ID wraparound.
Plain VACUUM does not shrink the file in the general case. It marks the space as reusable inside the table, so new rows fill the holes. It runs next to normal reads and writes. The only thing it blocks is schema changes such as ALTER TABLE on that table.
VACUUM, VACUUM FULL, ANALYZE and autovacuum
| Command | What it does | Lock |
|---|---|---|
| VACUUM | Marks dead row space reusable, updates the visibility map, freezes old rows | Does not block reads or writes |
| VACUUM (ANALYZE) | The same, then refreshes planner statistics | Does not block reads or writes |
| ANALYZE | Only refreshes the statistics the planner uses to pick plans | Does not block reads or writes |
| VACUUM FULL | Rewrites the whole table into a new file and returns space to the operating system | ACCESS EXCLUSIVE: nothing else can use the table |
| Autovacuum | A background process that runs VACUUM and ANALYZE when a table crosses a threshold | Same as plain VACUUM |
VACUUM (VERBOSE, ANALYZE) public.orders;Keep autovacuum on. The documentation says explicitly to use plain VACUUM and avoid VACUUM FULL where possible. Most teams that turn autovacuum off to save I/O pay for it later in bloat and in slow queries.
How to tell autovacuum is falling behind
The view pg_stat_user_tables keeps, per table, the estimated live and dead rows and the time of the last vacuum. Look for tables where dead rows are a large share of the total and the last autovacuum is old or empty.
SELECT schemaname || '.' || relname AS table_name, 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_autovacuum, last_autoanalyze, autovacuum_countFROM pg_stat_user_tablesWHERE n_live_tup + n_dead_tup > 1000ORDER BY n_dead_tup DESCLIMIT 25;A dead share above roughly 20% on a table that is read often is worth attention. The numbers are estimates from the statistics collector, so treat them as a signal, not an exact count. A single snapshot tells you little. The trend tells you more: a table whose n_dead_tup climbs every day is one autovacuum cannot keep up with.
To see what autovacuum is doing right now, query pg_stat_progress_vacuum. For table size and bloat suspects, sort by pg_total_relation_size.
SELECT pid, relid::regclass AS table_name, phase, heap_blks_scanned, heap_blks_totalFROM pg_stat_progress_vacuum; SELECT relname, pg_size_pretty(pg_total_relation_size(relid)) AS total_sizeFROM pg_stat_user_tablesORDER BY pg_total_relation_size(relid) DESCLIMIT 15;The settings that matter
Autovacuum starts a VACUUM on a table when dead rows pass this threshold: autovacuum_vacuum_threshold plus autovacuum_vacuum_scale_factor times the number of rows. With the defaults, 50 rows and 0.2, a table of 100 million rows waits for about 20 million dead rows. That is the usual reason a big table bloats.
| Setting | Default | What to do with it |
|---|---|---|
| autovacuum_vacuum_scale_factor | 0.2 | Lower it on large tables, per table, to 0.01 to 0.05 |
| autovacuum_vacuum_threshold | 50 | Raise it on tiny, busy tables to avoid constant vacuums |
| autovacuum_analyze_scale_factor | 0.1 | Lower it where plans go bad after bulk changes |
| autovacuum_vacuum_cost_delay | 2ms | Lower it if vacuum is too slow on fast storage |
| autovacuum_vacuum_cost_limit | -1 (uses vacuum_cost_limit, 200) | Raise it; the budget is shared by all running workers |
| autovacuum_max_workers | 3 | More workers only help if the cost limit rises too; needs a restart |
| autovacuum_naptime | 1min | Rarely needs a change |
Change the large, hot tables first, and do it per table rather than for the whole server. Most of these settings can be set as storage parameters. The exceptions are autovacuum_naptime and autovacuum_max_workers, which are server-wide.
ALTER TABLE public.orders SET (
autovacuum_vacuum_scale_factor = 0.02,
autovacuum_vacuum_threshold = 1000,
autovacuum_analyze_scale_factor = 0.01
);If autovacuum runs often but dead rows still grow, the cost limit is the next suspect. Workers pause to respect the cost budget, and the budget is split among all workers. Raise autovacuum_vacuum_cost_limit before you add workers.
Long transactions stop the cleanup
VACUUM can only remove a dead row version when no open transaction could still need to see it. One session left in "idle in transaction" for hours holds the cleanup horizon back for the whole database. Autovacuum runs, finds nothing it may remove, and dead rows keep growing.
SELECT pid, usename, state, now() - xact_start AS xact_age, left(query, 80) AS queryFROM pg_stat_activityWHERE xact_start IS NOT NULLORDER BY xact_startLIMIT 10;Replication slots that nobody reads and prepared transactions hold the horizon in the same way. Check pg_replication_slots and pg_prepared_xacts if the list above looks clean and dead rows still grow. A safety net for application bugs is idle_in_transaction_session_timeout.
Transaction ID wraparound, in plain words
Transaction IDs are 32-bit numbers, and Postgres compares them in a circle. For any ID, about two billion IDs count as older and two billion as newer. If a row version is never cleaned and two billion transactions pass, it would suddenly look like it is in the future and vanish.
VACUUM prevents this by freezing old row versions, which marks them as older than every normal ID. Tables that have not been vacuumed for autovacuum_freeze_max_age transactions (200 million by default) are autovacuumed even if autovacuum is switched off. If you ignore the warnings, the server starts warning roughly 40 million transactions before the limit and finally refuses to assign new IDs.
SELECT datname, age(datfrozenxid) AS xid_age, current_setting('autovacuum_freeze_max_age')::int AS freeze_max_ageFROM pg_databaseORDER BY age(datfrozenxid) DESC;If xid_age is far above freeze_max_age on a database, something is blocking the freeze. The usual cause is the long transaction, replication slot or prepared transaction from the previous section.
When VACUUM FULL is worth its lock
VACUUM FULL builds a fresh copy of the table and swaps it in. It returns space to the operating system, and it takes an ACCESS EXCLUSIVE lock for the whole run, so even SELECT waits. It also needs free disk space for the new copy.
- Worth it: after a one-off mass delete or a bad bloat incident, on a table that is mostly empty space, in a maintenance window.
- Not worth it: as a weekly job, or to fix a table that will bloat again tomorrow. Fix the autovacuum settings or the long transaction first.
- Alternatives that avoid the long lock: the pg_repack extension, or partitioning so you can drop old partitions instead of deleting rows.
Always check the size of the table and the free disk before VACUUM FULL. It needs room for a second copy.
Watching it without opening psql every time
The queries above are plain SQL, which makes them easy to schedule. In DataRunner you can connect the database, save the dead-tuples query and run it every morning, delivered to e-mail or Slack. A rule that skips the send when the result is empty means you only hear about it when a table crosses your limit.
- Connect the PostgreSQL database in DataRunner. For a private network, use the bridge agent.
- Start from the dead-tuples, open-transactions and largest-tables templates, or paste the queries from this guide.
- Add a WHERE clause for your limit, for example dead_pct > 20.
- Schedule it daily in your time zone and choose Slack or e-mail.
- Turn on the rule that skips the send when no row comes back.
This is a daily check of the numbers, not a live metrics system. It does not draw time series. If you need minute-by-minute graphs of vacuum activity, pair it with a metrics stack.