How does MVCC work in PostgreSQL, and why do VACUUM and autovacuum matter?
MVCC in PostgreSQL
Each row version (tuple) stores the transaction ids that created it (xmin) and deleted or replaced it (xmax). An UPDATE does not overwrite the row: it marks the old version dead and writes a new version. Each transaction sees only the versions visible to its snapshot, so readers never block writers.
The cost: dead tuples
Old versions stay in the table until no running transaction can see them. VACUUM marks that space reusable, updates the visibility map (which enables index-only scans) and freezes old transaction ids to prevent transaction ID wraparound. Autovacuum runs this automatically based on how many rows changed.
Problems seen in production
- Bloat: tables and indexes grow because dead tuples pile up (autovacuum too slow, or blocked).
- Long-running transactions or idle-in-transaction sessions, abandoned replication slots and long queries on a hot standby with feedback all hold back the cleanup horizon.
- Very frequent updates of the same rows (queues, counters).
Fixes
Kill or time out idle transactions (idle_in_transaction_session_timeout), tune autovacuum per hot table (lower autovacuum_vacuum_scale_factor), use HOT updates (leave free space with fillfactor and avoid updating indexed columns), and rebuild bloated indexes with REINDEX CONCURRENTLY. VACUUM FULL rewrites the table but takes an exclusive lock; pg_repack does it online.
Example
-- Which tables have many dead tuples, and when were they last vacuumed?
SELECT relname, n_live_tup, n_dead_tup, last_autovacuum
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC
LIMIT 10;
-- Sessions holding back cleanup
SELECT pid, state, xact_start, now() - xact_start AS age, left(query, 60)
FROM pg_stat_activity
WHERE xact_start IS NOT NULL
ORDER BY xact_start
LIMIT 5;
-- Vacuum a hot queue table more aggressively
ALTER TABLE job_queue SET (autovacuum_vacuum_scale_factor = 0.01, fillfactor = 80);Follow-up questions interviewers ask
Try answering each one before you open it.
Why can a long report on a replica cause bloat on the primary?
With hot_standby_feedback = on, the replica tells the primary which old row versions its queries still need, so the primary cannot vacuum them while the report runs. Without feedback, the replica instead cancels the query when replay conflicts. Run long analytics on a separate replica or a warehouse.