Sub topic 11
Dead tuples, VACUUM and autovacuum
This chapter assumes you know that an UPDATE or DELETE in PostgreSQL leaves the old row version in the table (see the chapters on row versions and on xmin/xmax). It also assumes you can run psql and open two sessions. Here you will see why those old versions pile up, how VACUUM reclaims their space, and how autovacuum decides when to run.
Why dead tuples exist
An UPDATE writes a new row version and sets xmax on the old one. A DELETE only sets xmax. Neither removes anything from the heap page. The old version must stay because a transaction with an older snapshot may still need to see it.
A dead tuple is a row version that no current or future snapshot can see. Once a version is dead, nothing needs it, but its space is still occupied until something reclaims it. That something is vacuum.
A version becomes dead when both conditions hold:
- Its
xmaxbelongs to a transaction that committed (or its creatorxminaborted). - No running transaction has a snapshot old enough to still treat it as visible.
The second condition uses the xmin horizon: the oldest transaction ID that any snapshot or transaction in the cluster may still need. Versions deleted before the horizon can be removed. The next chapter covers what holds the horizon back.
Observing dead tuples
Run an update and look at the statistics view:
CREATE TABLE accounts (id int PRIMARY KEY, balance int NOT NULL);
INSERT INTO accounts VALUES (1, 100);
UPDATE accounts SET balance = balance + 1 WHERE id = 1;
SELECT relname, n_live_tup, n_dead_tup, last_autovacuum
FROM pg_stat_user_tables
WHERE relname = 'accounts';n_dead_tup is an estimate maintained by the statistics system, not an exact count. It can lag by a moment after the statement runs. To see the real tuples, use pageinspect, which needs superuser by default:
CREATE EXTENSION IF NOT EXISTS pageinspect;
SELECT lp, t_xmin, t_xmax, t_ctid
FROM heap_page_items(get_raw_page('accounts', 0));The old version shows a nonzero t_xmax, and its t_ctid points at the newer version. Until vacuum runs, both versions occupy space on the page.
What VACUUM does
Plain VACUUM works table by table and does not take a lock that blocks reads or writes. It takes a SHARE UPDATE EXCLUSIVE lock, which conflicts only with other schema changes and other vacuums on the same table. For each table it does roughly the following:
- Scans heap pages (skipping pages the visibility map marks as all-visible) and collects the item pointers of dead tuples.
- Removes the index entries that point to those tuples, in every index on the table.
- Marks the dead heap tuples' slots as unused, so the space can be reused by later inserts and updates on the same page.
- Updates the free space map, which tells future writers where room exists.
- Updates the visibility map and freezes old tuples where needed.
- Updates planner statistics counters such as the estimated live row count.
The order matters. Index entries must go before the heap slot is freed. Otherwise an index could point to a slot that a new, unrelated row now occupies.
VACUUM (VERBOSE) accounts;The verbose output reports how many dead item identifiers were removed and how many pages were scanned. Read it to confirm that vacuum actually removed tuples and was not blocked by an old snapshot. A line saying tuples are "dead but not yet removable" means the horizon is holding them back.
Space is reused, not returned
Plain VACUUM makes space inside the file reusable. It usually does not make the file smaller. The one exception is when the pages at the very end of the table are completely empty. Vacuum can then truncate them, though it only does so after briefly taking an ACCESS EXCLUSIVE lock and skips the attempt if it cannot get the lock quickly.
This means a table that was bloated once keeps its size on disk even after vacuum. New rows fill the freed space, so the table stops growing, but it does not shrink.
| Command | Locks | Shrinks the file? | Typical use |
|---|---|---|---|
| `VACUUM` | `SHARE UPDATE EXCLUSIVE`, reads and writes continue | Only empty pages at the end | Routine cleanup |
| `VACUUM FULL` | `ACCESS EXCLUSIVE`, blocks all access | Yes, rewrites the table | Recovering space after severe bloat |
| `VACUUM (ANALYZE)` | Same as `VACUUM` | Same as `VACUUM` | Cleanup plus fresh statistics |
VACUUM FULL writes a complete new copy of the table and its indexes, so it needs enough free disk for that copy and blocks every query on the table while it runs. Avoid it on busy production tables. Extensions such as pg_repack rewrite tables with much shorter locks.
Autovacuum
Running vacuum by hand does not scale, so PostgreSQL ships with autovacuum, a background facility. A launcher process wakes regularly and starts worker processes for databases that need attention. Each worker checks the tables in one database and vacuums those that cross a threshold.
A table is vacuumed when:
dead tuples > autovacuum_vacuum_threshold
+ autovacuum_vacuum_scale_factor * number of rowsThe defaults are a threshold of 50 and a scale factor of 0.2. A table of 1,000,000 rows is vacuumed after about 200,050 dead tuples. For large tables, 20% is a lot of waste. Inserts also trigger vacuum in recent versions through separate insert thresholds, so that the visibility map and freezing stay current.
The diagram below shows the life of a row version as vacuum sees it.
Tuning per table
You can override the settings on a single table with storage parameters. This is the usual fix for large, frequently updated tables:
ALTER TABLE accounts SET (
autovacuum_vacuum_scale_factor = 0.01,
autovacuum_vacuum_threshold = 1000
);Other settings that matter:
autovacuum_naptime: how often the launcher checks (default 1 minute).autovacuum_max_workers: how many tables can be vacuumed at once (default 3). These workers share one cost budget, so adding workers does not by itself add throughput.autovacuum_vacuum_cost_limitandautovacuum_vacuum_cost_delay: throttle vacuum I/O. If vacuum falls behind on a busy system, these limits are the usual cause.log_autovacuum_min_duration: logs each autovacuum run that exceeds the given time, which helps you see what vacuum actually did.
Common problems
- Autovacuum runs but bloat grows. Vacuum can only remove tuples behind the horizon. An old open transaction, a stale replication slot or a forgotten prepared transaction keeps tuples alive. The next chapter shows how to find the session responsible.
- Autovacuum never finishes on a huge table. It is being throttled, or it keeps being cancelled. Autovacuum yields if it blocks a conflicting lock request, so frequent
ALTER TABLEorLOCK TABLEstatements can starve it. - Stale statistics.
n_dead_tupandlast_autovacuumare only as fresh as the statistics system. Checklast_autovacuumandautovacuum_countto confirm vacuum is running at all. - Disabling autovacuum. Turning it off for a table to "speed things up" makes bloat and transaction ID age grow without limit. Tune it instead of disabling it.
- Indexes bloat too. Vacuum removes dead index entries, but B-tree pages that are mostly empty are not always merged. A heavily churned index may need
REINDEX (CONCURRENTLY).
Exercise
A table with 10,000,000 rows has default autovacuum settings and is updated constantly. Roughly how many dead tuples build up before autovacuum starts a run, and what single change would make vacuum start sooner? After a successful plain VACUUM, will the table file on disk normally get smaller?
Show answer
With the defaults, the trigger is 50 + 0.2 * 10,000,000, which is about 2,000,050 dead tuples. Lowering autovacuum_vacuum_scale_factor for that table with ALTER TABLE ... SET (autovacuum_vacuum_scale_factor = 0.01) makes it start at about 100,000 dead tuples. A plain VACUUM normally does not shrink the file. It makes the freed space reusable inside the file, and only completely empty pages at the end can be truncated. VACUUM FULL would shrink it but locks the table exclusively.
Exercise
In what order does VACUUM handle index entries and heap slots for a dead tuple, and why?
Show answer
It removes the index entries first and then marks the heap slot unused. If the slot were freed first, an index entry could still point to it, and a new row stored there would be returned for the wrong key.