0%
PostgreSQL Deep Dive: MVCC, Vacuum, Plans, and Replication
Architecture and Storage
Indexes and Query Planning
Concurrency and Schema
Vacuum and Autovacuum
Vacuum is the process that turns the deferred costs of MVCC into reclaimed space and fast scans. It removes dead tuple versions and their index entries, records free space for reuse, sets visibility map bits, freezes old transaction identifiers and updates statistics about the table. Most of the time it runs invisibly as autovacuum, and teams only notice it when it falls behind, which shows up as bloat, slow queries, replication lag or, in the worst case, a database that refuses writes to protect itself from wraparound. This lesson explains how vacuum works internally, when autovacuum decides to run, how it is throttled, and how to tune and diagnose it.
Plain vacuum versus VACUUM FULL
Plain VACUUM, the kind autovacuum runs, works alongside normal traffic. It takes a share update exclusive lock that allows reads and writes but blocks other vacuums and schema changes on the table, removes dead tuples in place, and makes the space available for reuse inside the same file. It does not normally shrink the file, except for empty pages at the very end. VACUUM FULL is a completely different operation: it rewrites the entire table and its indexes into new files under an access exclusive lock, blocking all access, and returns all free space to the operating system. Plain vacuum is routine maintenance; VACUUM FULL is a rare repair.
Phase one, scanning the heap
Vacuum begins by scanning the table heap page by page, skipping pages the visibility map marks all visible unless it is an aggressive vacuum. On each page it prunes, removing tuples that are dead to every snapshot by comparing their xmax with the oldest xmin horizon, and records the tuple identifiers of the dead items in memory. It also freezes tuples old enough to freeze and notes whether every tuple on the page is now visible to everyone. The dead tuple identifiers are kept in memory bounded by maintenance_work_mem, or autovacuum_work_mem for autovacuum, and in version 17 in a much more compact radix tree structure.
Phase two, vacuuming indexes
Dead heap tuples cannot be fully removed while index entries still point at them, since a later index scan would follow a pointer to a reused slot. So after collecting dead identifiers, vacuum scans every index on the table in full and deletes the entries that point at any of them. For B-tree indexes this is a complete pass over the index, regardless of how few dead tuples there are, which makes index vacuuming the dominant cost on tables with many large indexes. If the dead identifier memory fills before the heap scan ends, vacuum must stop, vacuum all indexes, and continue, so too little memory means multiple full passes over every index.
Phase three, vacuuming the heap again
After the indexes are clean, vacuum returns to the heap pages that held dead items and marks their line pointers unused, so new tuples can take those slots. It updates the free space map for each page and sets visibility map bits where every remaining tuple is visible to all. This second visit touches only the pages that had dead items, so it is much cheaper than the first scan. Pages pruned earlier by ordinary queries, through on page pruning, may already have dead line pointers waiting just for this step.
Truncation and statistics
At the end, if the last pages of the table are completely empty, vacuum tries to take a brief access exclusive lock to truncate them, giving the space back to the operating system. If it cannot get the lock quickly, it skips the step. Vacuum then updates relpages, reltuples and relallvisible in pg_class, used by the planner, and advances relfrozenxid if it scanned every page that could hold unfrozen tuples. VACUUM ANALYZE additionally samples rows to refresh column statistics, which autovacuum does as a separate decision driven by its own thresholds.
Index cleanup can be skipped
Because index vacuuming is so expensive, version 12 added the INDEX_CLEANUP option, and version 14 made vacuum skip index cleanup automatically when very few pages have dead items, under the bypass threshold. Skipping leaves dead line pointers in the heap, which still occupy four bytes each and prevent the page from being marked all visible, but avoids full scans of every index for a handful of dead tuples. In an emergency, VACUUM with INDEX_CLEANUP off is also the fastest way to freeze a table close to wraparound, since freezing needs only the heap.
Vacuum and the WAL
Vacuum generates WAL for every page it changes: prune records, freeze records, visibility map changes and index deletions. On a large table, a vacuum that freezes most pages can generate WAL close to the size of the table, especially right after a checkpoint when full page images are needed. This WAL is also shipped to standbys, so a big vacuum shows up as replication lag. Spreading freezing over time, rather than letting it accumulate into one huge anti wraparound vacuum, keeps both WAL volume and replica lag smooth.
Vacuum on standbys
Standbys do not run vacuum. They replay the vacuum work done on the primary through the WAL. When a replayed prune or vacuum record removes tuples that a query on the standby still needs, the replay must either wait or cancel the query, which is the classic conflict with recovery error on hot standbys. This is why vacuum on the primary can cause errors on replicas, and why hot_standby_feedback exists, letting the standby hold back the primary horizon instead.
On page pruning between vacuums
Vacuum is not the only process that removes dead tuples. Any query that reads a heap page and finds it nearly full may prune it on the spot, removing the storage of tuples that are dead to every snapshot and compacting the page, as described in the storage lesson. Pruning cannot remove index entries or free line pointers, so it does not replace vacuum, but it reclaims most of the space on frequently read pages long before vacuum arrives. This is why hot pages often stay compact while cold pages accumulate dead tuples until vacuum visits them.
Ring buffers protect the cache
A vacuum that read an entire large table through shared buffers would evict the working set of every other query. To prevent that, vacuum uses a small ring buffer, a few hundred kilobytes by default, and recycles its own buffers as it scans, so it touches only a small slice of shared buffers. The trade off is that vacuum itself benefits little from caching and must write dirty pages from its ring frequently. Version 16 made the ring size configurable with vacuum_buffer_usage_limit, so a manual vacuum in a quiet window can use a much larger share and run faster.
What vacuum cannot fix
Vacuum removes dead tuples, but it does not reorder rows, rebuild indexes, or shrink files in the middle. A table that once held ten times its current data keeps its large file and its sparse pages until a rewrite. An index whose pages have been split and partially emptied stays large, apart from reuse of fully empty pages. And vacuum cannot remove anything the horizon protects. These limits define when other tools are needed: REINDEX for index bloat, pg_repack or VACUUM FULL for heap bloat, and fixing the horizon holder for cleanup that never happens.
Vacuum and sequences of updates
On a row updated many times between vacuums, the chain of dead versions can be long. Pruning collapses chains of HOT updates into a single redirect pointer, while non HOT chains leave a dead tuple and index entries per version. Vacuum handles both, but the work it does scales with the number of versions, not the number of rows, which is why update frequency matters more than table size for vacuum cost.
Vacuum scans the heap for dead ids, scans every index to remove matching entries, then frees the heap pointers and updates the maps. Give it enough maintenance memory for one index pass, and reserve VACUUM FULL for rare repairs.