Sharon Ben-Moshe is the founder of sqlfmt, a browser-based SQL formatter and validator with misspelled-keyword suggestions across PostgreSQL, MySQL, SQLite, SQL Server, and BigQuery.
Understand how PostgreSQL MVCC creates dead tuples, why autovacuum falls behind, and how to eliminate table and index bloat safely in production.
Quick answer
PostgreSQL VACUUM removes dead row versions created by UPDATE and DELETE statements, marking page space as reusable for future inserts. Without regular vacuuming, dead tuples accumulate, causing table bloat, slow sequential scans, degraded cache efficiency, and emergency shutdowns caused by transaction ID wraparound.
FAQs
Does standard VACUUM lock tables in PostgreSQL?
No. Standard VACUUM runs concurrently with read and write operations. Only VACUUM FULL acquires an exclusive lock that blocks reads and writes.
Why does table disk space not decrease after running VACUUM?
Standard VACUUM marks dead space in pages as reusable for future inserts, but does not return pages to the operating system unless trailing pages are completely empty.
What is the difference between VACUUM and ANALYZE?
VACUUM cleans dead tuples and freezes old transaction IDs. ANALYZE collects column data distribution statistics used by the query planner to choose optimal query execution plans.
How can I tell if autovacuum is currently running on my table?
Query pg_stat_progress_vacuum to see currently active vacuum workers, their progress phase, and the number of pages processed.
Implement distributed locks and cron leader election in PostgreSQL using advisory locks. Compare session vs transaction locks and non-blocking try locks.
Discover 7 dangerous SQL anti-patterns that degrade query performance and corrupt results. Learn how to refactor non-SARGable predicates and NULL pitfalls.
Compare natural keys, auto-increment surrogate keys, and UUIDs for primary keys. Learn how UUIDv7 and sequential IDs impact B-tree index fragmentation.
PostgreSQL relies on Multi-Version Concurrency Control (MVCC) to provide high concurrency. When you update or delete a row, PostgreSQL does not overwrite the existing data on disk. Instead, it marks the old row version as dead and writes a new row version to the table. This design allows readers to scan tables without locking writers.
The consequence of MVCC is that tables and indexes accumulate dead tuples over time. Reclaiming that space falls to the VACUUM process. When autovacuum is misconfigured or blocked by long-running transactions, tables bloat to multiples of their true size, query performance degrades, and databases risk catastrophic shutdown from transaction ID wraparound. Read the official PostgreSQL concurrency control documentation for architectural background on visibility maps.
How MVCC produces dead tuples and table bloat
Every table heap page in PostgreSQL is 8KB. When an UPDATE executes, PostgreSQL inserts the updated row version (tuple) into an available page and updates the internal header pointer (xmax) on the old tuple. Until the transaction commits and all concurrent transactions that could observe the old row version complete, that dead tuple remains on disk.
A standard VACUUM scans pages, locates dead tuples that are no longer visible to any active transaction, and marks that space as free in the Free Space Map (FSM). Future INSERT statements reuse that space. However, standard VACUUM never returns unused disk space to the operating system unless pages at the very end of the file are completely empty. If empty space is scattered across thousands of pages, the table file size never shrinks.
Why autovacuum falls behind on busy databases
PostgreSQL includes an internal background daemon called autovacuum. By default, autovacuum wakes up periodically and checks whether tables have exceeded their bloat thresholds. Default settings designed for small hardware instances often throttle autovacuum so severely that it cannot keep pace with modern production workloads.
Checking autovacuum bloat thresholds
-- Default autovacuum triggers when:-- dead_tuples > autovacuum_vacuum_threshold + (autovacuum_vacuum_scale_factor * table_tuples)-- On a 100-million-row table with default scale_factor = 0.2:-- Autovacuum will not trigger until 20 MILLION rows are updated or deleted!-- Fix this by tuning table-level scale factors:ALTER TABLE high_churn_queue SET ( autovacuum_vacuum_scale_factor = 0.01, autovacuum_vacuum_threshold = 1000, autovacuum_vacuum_cost_limit = 2000);
When an autovacuum worker runs, it is constrained by autovacuum_vacuum_cost_limit and autovacuum_vacuum_cost_delay. Whenever the worker performs disk I/O, it accumulates cost points and sleeps. On modern NVMe drives, default cost settings throttle vacuuming to a fraction of the hardware throughput. Review the official PostgreSQL routine vacuuming guide for cost formulas.
The three blockers that prevent dead tuple cleanup
Even when autovacuum runs constantly, it cannot clean dead tuples if an active transaction holds an older snapshot. The three most common vacuum blockers are:
Long-running queries: A report running for two hours pins the database horizon. No tuples modified after that report started can be cleaned anywhere in the database.
Abandoned transactions: An application connection that opens a transaction with BEGIN and never issues COMMIT or ROLLBACK blocks vacuuming indefinitely.
Unused replication slots: A stale replication slot configured for an offline replica retains WAL and dead tuples to prevent catalog drift.
Detecting transactions blocking vacuum cleanup
SELECT pid, now() - xact_start AS transaction_age, state, queryFROM pg_stat_activityWHERE state != 'idle' AND xact_start IS NOT NULLORDER BY xact_start ASCLIMIT 5;
Transaction ID (TXID) wraparound: the hard database ceiling
PostgreSQL uses 32-bit transaction IDs, which provides roughly four billion unique transactions. To prevent transaction numbers from rolling over and making old data appear in the future, PostgreSQL freezes old transaction IDs during vacuuming by setting a special flag (FrozenTransactionId).
If autovacuum is blocked or fails to freeze rows before the database reaches the autovacuum_freeze_max_age threshold (typically 200 million transactions), PostgreSQL enters emergency protective mode. It logs urgent warnings, refuses to accept new write transactions, and forces the database into read-only mode until a standalone VACUUM FREEZE completes.
Fixing bloat: VACUUM FULL vs pg_repack
When a table has bloated to ten times its natural size due to a spike in updates, running standard VACUUM will not shrink the physical file size on disk. You must rewrite the table.
Comparing VACUUM FULL and pg_repack
-- Method 1: VACUUM FULL (Reclaims all disk space, but locks table exclusively!)-- WARNING: Blocks all SELECT, INSERT, UPDATE, DELETE queries until completeVACUUM FULL orders;-- Method 2: pg_repack (Third-party extension, rebuilds table online with NO exclusive lock)-- Run from shell:-- pg_repack --table=orders -d production_db
Never run VACUUM FULL on a busy production table during business hours. It acquires an ACCESS EXCLUSIVE lock, queuing all application reads and writes until it finishes rewriting the entire table to a new file. Use tools like pg_repack to reclaim space online without locking.
Actionable checklist for managing PostgreSQL vacuum and bloat
Tune autovacuum settings: raise autovacuum_vacuum_cost_limit to 1000 or 2000 on modern SSD/NVMe infrastructure.
Lower scale factors: set autovacuum_vacuum_scale_factor = 0.05 or lower on large transactional tables.
Enforce statement timeouts: set statement_timeout and idle_in_transaction_session_timeout to kill abandoned sessions.
Monitor dead tuple percentages: query pg_stat_user_tables to detect tables where n_dead_tup exceeds ten percent.
Inspect replication slots: drop obsolete replication slots in pg_replication_slots that retain older WAL segments.
Track transaction age: monitor datfrozenxid in pg_database to detect wraparound risks before reaching emergency thresholds.
Wrapping up
Maintaining a healthy PostgreSQL database requires an active, well-tuned vacuum strategy. By understanding how MVCC creates dead tuples, adjusting autovacuum thresholds for high-churn tables, and terminating long-running idle transactions, you prevent disk bloat and ensure fast query execution. When drafting administrative migration scripts and schema changes, keep your SQL organized by using sqlfmt or our Pro plans.