← Back to SQL, page 18

sql-0357 · Hard senior

A PostgreSQL table with heavy updates keeps growing on disk although its row count is stable. What is going on?

PostgreSQL's MVCC writes a new row version on every UPDATE and leaves the old one as a dead tuple until VACUUM reclaims it. If autovacuum cannot keep up, or a long-running transaction prevents cleanup, dead tuples pile up and the table and its indexes bloat. Tune autovacuum for the table, end long transactions and, if needed, rebuild with pg_repack or VACUUM FULL.

Full answer

How to confirm:

  • pg_stat_user_tables shows n_dead_tup and the last autovacuum time for the table.
  • pg_stat_activity shows old transactions (xact_start) or sessions idle in transaction; their snapshot keeps dead rows visible, so VACUUM cannot remove them.
  • Abandoned replication slots and prepared transactions have the same effect.

Fixes:

  • Lower autovacuum_vacuum_scale_factor for the hot table so vacuum runs after a fixed number of changes rather than 20 percent of the table.
  • Kill or fix long transactions; set idle_in_transaction_session_timeout.
  • Reclaim existing bloat: plain VACUUM makes space reusable but rarely shrinks the file; VACUUM FULL rewrites the table under an exclusive lock, while pg_repack does it online.
  • Reduce churn: HOT updates (when no indexed column changes and the page has free space) avoid index bloat, so a lower fillfactor can help.

These are PostgreSQL-specific behaviours described here, not run.

Key points

  • UPDATE creates dead row versions
  • VACUUM reclaims them, unless old snapshots block it
  • Tune autovacuum per hot table
  • VACUUM FULL locks; pg_repack works online
  • HOT updates reduce index churn

Common mistakes

  • Running VACUUM FULL at peak time
  • Ignoring idle-in-transaction sessions

Follow-ups

  • What is transaction ID wraparound?
  • How does fillfactor help HOT updates?

Tips

  • Name the long-transaction cause