VACUUM, autovacuum & bloat
Explain why vacuum exists and check autovacuum is keeping up.
By Invicly Tech, , in SQL & PostgreSQL. About 11 minutes to read.
In short
Because of MVCC, UPDATE and DELETE leave old row versions behind as dead tuples. VACUUM marks that space reusable and ANALYZE refreshes planner statistics; autovacuum runs both in the background so tables do not bloat.
Explained simply
In Postgres an UPDATE does not change a row in place. It writes a new version of the row and leaves the old one behind, because another transaction might still be reading it. A DELETE also just marks the row as gone. These leftovers are called dead tuples (tuple is the database word for a row version).
If nobody cleaned them up, tables would grow forever and queries would wade through more and more junk. VACUUM is the cleaner. It finds dead row versions that no transaction can see any more and marks their space as free, so new rows can reuse it.
You rarely run it by hand. Autovacuum is a background helper that watches how many rows each table has changed and vacuums it when enough have piled up. It also runs ANALYZE, which refreshes the statistics the planner uses to choose good plans.
Your job is mostly to make sure autovacuum can keep up: never switch it off, avoid transactions that stay open for hours, and tune it for very busy tables.
Press Play on a diagram to walk through it one step at a time.
- 1UPDATE / DELETE
Old row version becomes a dead tuple
- 2Dead tuples pile up
Table and indexes grow: bloat
- 3Autovacuum triggers
After enough rows changed
- 4VACUUM cleans
Marks space free and updates visibility map
- 5Space reused
New rows fill the freed slots
- Back to step 1
- Space reusable, file rarely shrinks
- Reads and writes continue
- Runs automatically
- The normal routine
- Rewrites a compact copy
- ACCESS EXCLUSIVE: blocks all
- Needs space for the copy
- Maintenance window only
- Extension, rebuilds online
- Brief locks at start and end
- Needs a primary key or unique index
- Fix bloat without downtime
In depth
What VACUUM actually does
VACUUM visits the table's pages, finds row versions whose deleting transaction is older than every running snapshot, and removes them. It first deletes index entries pointing to those rows, then frees the space in the table pages. The free space is recorded in the free space map, so the next INSERT or UPDATE can reuse it.
It also updates the visibility map, which marks pages where every row is visible to all transactions. That makes later vacuums skip those pages and enables index-only scans.
Plain VACUUM takes only a SHARE UPDATE EXCLUSIVE lock, so reads and writes continue. It normally does not shrink the file on disk: it can only cut off completely empty pages at the very end. VACUUM FULL rewrites the whole table into a new compact file, which does return space to the operating system, but it holds an ACCESS EXCLUSIVE lock for the whole time and needs room for a full copy.
- 1Scan heap pages
Skip pages the visibility map says are clean
- 2Collect dead tuples
Versions no snapshot can still see
- 3Clean indexes
Remove entries pointing to dead rows
- 4Free heap space
Record it in the free space map
- 5Update visibility map
Mark all-visible and frozen pages
- 6Truncate tail
Return only empty end pages to the OS
When autovacuum runs, and tuning it for big tables
Autovacuum vacuums a table when its dead tuples exceed autovacuum_vacuum_threshold (50) plus autovacuum_vacuum_scale_factor (0.2) times the row count. It analyses when changed rows exceed 50 plus 0.1 times the row count. Since PostgreSQL 13 it also vacuums tables that only receive inserts, so their visibility maps stay current.
The 20 percent rule is fine for small tables but too lazy for big ones: a 100 million row table collects 20 million dead rows before cleanup. Lower it per table: ALTER TABLE orders SET (autovacuum_vacuum_scale_factor = 0.01, autovacuum_analyze_scale_factor = 0.02).
Autovacuum is deliberately throttled so it does not hurt foreground work. By default up to 3 workers (autovacuum_max_workers) run, and each pauses after a set amount of I/O (cost-based delay). On a busy server with fast disks, raising autovacuum_vacuum_cost_limit lets it finish sooner. Watch progress in pg_stat_progress_vacuum.
- Trigger: 50 + 0.2 x rows dead tuples
- Per-table scale_factor for large hot tables
- 3 workers by default; raise cost_limit on fast disks
- pg_stat_progress_vacuum shows running vacuums
Transaction ID wraparound and freezing
Transaction IDs are 32-bit numbers, so there are only about 4 billion of them, used in a circle. Postgres compares IDs as "older" or "newer" within a window of about 2 billion. If an old row's xmin fell out of that window, the row would suddenly look as if it came from the future and would vanish.
To prevent that, VACUUM freezes old rows: it marks them as visible to everyone, forever, so their xmin no longer matters. When a table's oldest unfrozen ID reaches autovacuum_freeze_max_age (200 million by default), autovacuum starts an aggressive anti-wraparound vacuum, even if autovacuum is turned off for that table. You may see it in pg_stat_activity as "(to prevent wraparound)".
If freezing falls far behind, Postgres eventually refuses to start new transactions to protect the data, which is an outage. Check SELECT datname, age(datfrozenxid) FROM pg_database; values in the hundreds of millions are normal, values above a billion need attention.
- About 2 billion XIDs before wraparound trouble
- Freezing makes old rows permanently visible
- Anti-wraparound vacuum starts at 200 million by default
- Monitor age(datfrozenxid)
What blocks cleanup, and fixing bloat
VACUUM can only remove a dead row when no snapshot might still need it. Anything holding an old snapshot holds back cleanup for every table: a transaction left idle in transaction, a long report, an abandoned replication slot, a forgotten prepared transaction, or a replica with hot_standby_feedback on running long queries. VACUUM VERBOSE reports how many dead rows were "not yet removable"; if that number is large, look for those causes in pg_stat_activity (backend_xmin), pg_replication_slots and pg_prepared_xacts.
Once a table is bloated, plain VACUUM makes the space reusable but does not shrink it. Options: VACUUM FULL during a maintenance window; the pg_repack extension, which rebuilds a table online with only brief locks; and REINDEX INDEX CONCURRENTLY (PostgreSQL 12+) for bloated indexes. The pgstattuple extension measures real dead and free space.
For tables with many updates, a fillfactor below 100 leaves room in each page so updates can stay on the same page as HOT updates, which skip index changes.
Learn it in 3 short steps
About 40m each. Track them with a timer in your plan.
- 1Explain dead tuples and MVCC bloat~40m
- 2Run VACUUM and ANALYZE~40m
- 3Check autovacuum activity~40m
Key points
- Dead tuples remain until no running transaction can still see them.
- Plain VACUUM does not lock out reads or writes, and rarely shrinks the file.
- VACUUM FULL rewrites the table compactly but takes an exclusive lock.
- Autovacuum also prevents transaction ID wraparound; never disable it.
- Long-running transactions stop vacuum from removing dead rows.
Key terms
Tap a card to flip it. 0/5 known
Examples
VACUUM (VERBOSE, ANALYZE) orders;
SELECT relname,
n_live_tup,
n_dead_tup,
last_autovacuum,
last_autoanalyze
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC
LIMIT 10;Seeing dead tuples appear and disappear
Step 1: create a table with 100,000 rows and turn off autovacuum on it, only for this experiment. Step 2: update every row; the table now has 100,000 dead versions and roughly doubles in size. Step 3: run VACUUM VERBOSE and see it remove them. Step 4: check that the size did not shrink, but the next update reuses the freed space instead of growing the file again.
CREATE TABLE vac_demo AS SELECT g AS id, 0 AS n FROM generate_series(1, 100000) g;
ALTER TABLE vac_demo SET (autovacuum_enabled = false);
SELECT pg_size_pretty(pg_relation_size('vac_demo'));
UPDATE vac_demo SET n = n + 1;
SELECT n_live_tup, n_dead_tup FROM pg_stat_user_tables WHERE relname = 'vac_demo';
SELECT pg_size_pretty(pg_relation_size('vac_demo')); -- about double
VACUUM VERBOSE vac_demo;
UPDATE vac_demo SET n = n + 1; -- reuses freed space
SELECT pg_size_pretty(pg_relation_size('vac_demo')); -- about the same
ALTER TABLE vac_demo RESET (autovacuum_enabled);Autovacuum is not keeping up on a hot table
The events table has 200 million rows and queries keep slowing down. Step 1: pg_stat_user_tables shows 30 million dead tuples and the last autovacuum days ago. Step 2: check for an old snapshot holding cleanup back; a session has been idle in transaction for 6 hours. Step 3: end it. Step 4: lower the table's scale factor so autovacuum runs after 1 percent changes instead of 20, and let a manual VACUUM catch up now.
SELECT relname, n_live_tup, n_dead_tup, last_autovacuum
FROM pg_stat_user_tables ORDER BY n_dead_tup DESC LIMIT 5;
SELECT pid, state, now() - xact_start AS xact_age, backend_xmin
FROM pg_stat_activity
WHERE backend_xmin IS NOT NULL
ORDER BY age(backend_xmin) DESC LIMIT 5;
SELECT pg_terminate_backend(31337); -- the idle-in-transaction session
ALTER TABLE events SET (autovacuum_vacuum_scale_factor = 0.01);
VACUUM (VERBOSE, ANALYZE) events;Quick reference
- VACUUM (VERBOSE, ANALYZE) t; clean, refresh stats, report what happened
- SELECT relname, n_dead_tup, last_autovacuum FROM pg_stat_user_tables ORDER BY 2 DESC;
- ALTER TABLE t SET (autovacuum_vacuum_scale_factor = 0.01); vacuum big tables sooner
- SELECT * FROM pg_stat_progress_vacuum; watch running vacuums
- SELECT datname, age(datfrozenxid) FROM pg_database; wraparound headroom
- VACUUM FULL blocks the table; prefer pg_repack for online bloat fixes
- REINDEX INDEX CONCURRENTLY idx; rebuild a bloated index without blocking writes
- Never disable autovacuum globally
Common mistakes
- Turning off autovacuum to "save resources".
- Leaving idle-in-transaction sessions open, blocking cleanup.
- Running VACUUM FULL on a busy production table during peak hours.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
List the 5 tables with the most dead tuples, with their live tuple count and when autovacuum last ran on them.
- Exercise 2medium
Show the dead-tuple percentage per table and the autovacuum trigger point under default settings, to see which tables are close to their next vacuum.
- Exercise 3hard
Find everything that could be holding back vacuum cleanup on the server: old transactions, replication slots and prepared transactions.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Should I run VACUUM manually every night?
- Usually not; autovacuum handles it. Manual VACUUM ANALYZE is useful after a big bulk load or delete, or before a big report on freshly changed data.
- Is it safe to run VACUUM while the app is running?
- Yes, plain VACUUM and ANALYZE run alongside normal reads and writes. Avoid VACUUM FULL on live tables because it blocks all access.
- Why is my table much bigger than its data?
- That is bloat from dead tuples that were not cleaned up in time, often because of long transactions or a lazy autovacuum setting. Fix the cause first, then shrink it with pg_repack or VACUUM FULL.