PostgreSQL Enterprise (50 Qs)•Part 3: Advanced Internals, Scale & Production Patterns (Senior / Lead)
PostgreSQL `VACUUM` & `AUTOVACUUM` Tuning.
senior LevelDatabases & SQLPostgreSQL
In Simple Words:
VACUUM reclaims storage space occupied by dead tuples and prevents Transaction ID (XID) Wraparound:
- Standard
VACUUM: Scans pages, reclaims dead tuple space for future inserts in the table without acquiring an exclusive table lock. VACUUM FULL: Rewrites the entire table into a new disk file to return space to the OS; requires an exclusive table lock (ACCESS EXCLUSIVE) that blocks all reads and writes!- Transaction ID Wraparound: PostgreSQL transaction IDs are 32-bit integers ($\approx 4\text{ Billion}$). If
VACUUM FREEZEdoes not advance the oldest XID before 2 billion transactions pass, Postgres halts all write operations to prevent catastrophic data corruption. - Tuning
autovacuum: For large tables, lowerautovacuum_vacuum_scale_factorfrom0.2(20%) to0.02(2%) so vacuuming runs in smaller, frequent batches.