Table bloat

On this page 7

Table bloat is the unused or dead space inside a table’s data files that remains after rows are updated or deleted, so the table occupies far more disk pages than its live data requires. In database performance work, bloat matters because every extra page must be read, cached and backed up, which slows sequential scans, wastes the buffer pool and inflates storage costs.

The term is most closely associated with PostgreSQL and other systems that use multiversion concurrency control (MVCC), where an update writes a new row version and leaves the old one behind until cleanup reclaims it. Similar effects appear in MySQL InnoDB, SQL Server and Oracle, although each engine stores, reuses and reports free space differently.

How table bloat accumulates

Table bloat accumulates whenever the rate of row-version creation exceeds the rate at which the engine can make old space reusable. In PostgreSQL, an UPDATE is internally an insert of a new tuple plus a mark on the old tuple; a DELETE only marks the tuple as dead. These dead tuples stay on disk until the VACUUM process confirms that no running transaction can still see them.

After VACUUM runs, the freed space is recorded in the free space map and new rows can reuse it, but the file normally does not shrink. Only empty pages at the very end of a file are truncated. As a result, a table that once held 100 million rows and now holds 10 million may keep almost its peak physical size indefinitely, a condition often called a high-water mark problem.

Several mechanisms block or slow reclamation. The following table lists the common root causes and how each one keeps dead space from being reused.

CauseMechanismTypical signal
Long-running transactionsOld snapshot keeps dead tuples visibleOld xmin horizon in activity views
Autovacuum lagCleanup thresholds too high for churnDead tuple count grows steadily
Abandoned replication slotsSlot holds back the cleanup horizonGrowing WAL and dead tuples
Mass deletesLarge block of space freed at onceSudden drop in live rows, size unchanged
Wide updates on hot rowsNew versions cannot fit on the same pageLow HOT update ratio
Common causes of table bloat

Measuring bloat and its key indicators

Bloat is measured as the difference between physical size and the size the live rows need, usually expressed as a percentage or as wasted bytes. Exact measurement requires reading every page, so administrators combine quick estimates with occasional precise checks.

In PostgreSQL, the pgstattuple extension scans a table and returns exact live, dead and free space, while estimate queries based on optimizer statistics compute expected size from average row width and row count. Estimates are fast but can be wrong by 10-20 percentage points when statistics are stale or rows contain large variable-length values.

MetricSourceWhat it shows
Dead tuple countpg_stat_user_tables.n_dead_tupRows awaiting cleanup
Free space percentpgstattupleReusable space already reclaimed
Estimated bloat ratioStatistics-based queriesPhysical versus expected size
Last autovacuum timepg_stat_user_tablesWhether cleanup keeps pace
HOT update ration_tup_hot_upd versus n_tup_updEfficiency of in-page updates
Metrics used to assess table bloat

Interpretation depends on workload. A bloat ratio of 20-30% is often normal and even useful for update-heavy tables, because reusable free space lets new versions land without extending the file. Ratios above 50%, or a ratio that rises week after week, indicate that cleanup is losing the race.

Table bloat is distinct from index fragmentation, although the two often appear together. Bloat concerns wasted space in heap pages, whereas fragmentation concerns the physical order and fill level of index pages. Index bloat is a third, related condition in which B-tree pages keep pointers to dead entries and half-empty leaf pages.

ConditionWhere it occursMain effectUsual remedy
Table bloatHeap data pagesMore pages to scan and cacheVACUUM, table rewrite
Index bloatIndex leaf pagesLarger, slower index scansReindex concurrently
Index fragmentationIndex page orderRandom I/O on range scansRebuild or reorganize
Transaction ID wraparound riskRow visibility metadataForced emergency vacuumFreezing via VACUUM
How table bloat differs from neighboring conditions

In MySQL InnoDB, the closest equivalent is fragmented free space within the tablespace together with a growing undo history list, which plays the role of old row versions. SQL Server handles deleted rows through ghost cleanup, and Oracle reuses space below the high-water mark but does not lower it without a segment shrink or move.

Preventing and removing table bloat

The most effective strategy is prevention through well-tuned autovacuum rather than periodic heavy repairs. Default settings trigger cleanup when about 20% of a table has changed, which is far too late for a table with hundreds of millions of rows, so large tables usually get per-table thresholds of 1-5% or a fixed row count.

  • Lower autovacuum_vacuum_scale_factor on large, update-heavy tables.
  • Raise autovacuum cost limits so workers are not throttled on fast storage.
  • Set idle_in_transaction_session_timeout to end forgotten open transactions.
  • Monitor and drop inactive replication slots promptly.
  • Use a lower fillfactor such as 80-90 so updates can stay on the same page.

When a table is already badly bloated, the remedy must physically rewrite it. The choice depends on how much downtime and spare disk space are available, as the following decision table summarizes.

SituationRecommended approachReason
Moderate bloat, steady churnRegular VACUUM and tuningReuses space without locks
Severe bloat, maintenance windowVACUUM FULL or CLUSTERCompact rewrite, exclusive lock
Severe bloat, no downtime allowedpg_repack or pg_squeezeOnline rewrite, brief lock only
Bloat from historical dataPartitioning with dropped old partitionsRemoves space instantly
Choosing a remedy for existing bloat

Every full rewrite needs free disk space roughly equal to the live data size plus its indexes, because the new copy is built before the old one is removed. Running a rewrite on a nearly full volume is a common cause of outages.

Common mistakes and misconceptions

Many bloat incidents result from misreading what VACUUM does. Plain VACUUM marks space as reusable but does not return it to the operating system, so a disk usage graph that stays flat after cleanup does not mean the cleanup failed.

  • Disabling autovacuum on busy tables to save I/O, which guarantees runaway growth.
  • Scheduling VACUUM FULL routinely, which locks the table and adds needless churn.
  • Treating any free space as waste, although moderate free space helps updates.
  • Ignoring connection pooling sessions left idle in a transaction for hours.
  • Fixing the table but not its indexes, which often carry more bloat than the heap.

In everyday language

Imagine a filing cabinet where every corrected document is added as a new copy while the old copy stays in the drawer, merely stamped as outdated. A clerk eventually removes the stamped pages, which frees room in the drawers, but the cabinet itself never gets smaller. Table bloat is that pile of outdated copies and empty drawer space inside a database.

The database still works correctly, but it has to open more drawers to find the current documents. The key takeaway is simple: regular cleanup keeps the cabinet tidy, and only a full reorganization makes it physically smaller.

Seen in the real world

An online retailer stores shopping carts in a PostgreSQL table that receives about 4,000 updates per second during sales. The live data needs about 6 GB, yet the table grew to 48 GB over two months. Checkout queries that scan recent carts slowed from 40 ms to over 300 ms, and the buffer pool hit ratio dropped noticeably.

Investigation showed a reporting session that had stayed idle in transaction for nine days, holding back the cleanup horizon. The team terminated it, set a 15-minute idle transaction timeout, lowered the table’s vacuum scale factor to 0.01 and set fillfactor to 85. They then ran pg_repack overnight without blocking traffic.

The table shrank to about 8 GB, checkout queries returned to roughly 45 ms, and a dashboard alert on dead tuple growth now flags the problem within hours instead of weeks.