Sub topic 3
What table bloat is and why it hurts
This chapter assumes you can read basic SQL and use psql. It also assumes you know what a transaction is and what an index does. The previous chapters covered how MVCC keeps old row versions and how UPDATE and DELETE leave dead tuples behind. This chapter covers what happens to a table when those dead tuples pile up, and which costs you pay for it.
Definition: bloat is space the table holds but cannot use for live data
A PostgreSQL table is stored as a heap, which is a file made of 8 kB pages. Each page holds row versions, called tuples. A tuple is live if some current or future transaction can still see it. A tuple is dead once no transaction can see it.
Table bloat is the part of the table's files that holds dead tuples or unused free space instead of live rows. The table is larger than the data it holds. Bloat can occur in the table's heap and in its indexes. This chapter focuses on the heap and touches on indexes where they affect the costs.
Two distinct things get called bloat:
- Dead tuples that have not been cleaned up yet. These are the cause. The space is occupied until VACUUM processes the page.
- Free space that VACUUM has already reclaimed inside pages but that the file still contains. The space is reusable by new rows, but the file does not shrink.
Both make the file larger than the live data. Only the second is harmless on its own, as the "Healthy versus harmful bloat" section below explains.
How bloat forms
In PostgreSQL an UPDATE does not change a row in place. It writes a new tuple and marks the old one as superseded. A DELETE only marks the tuple as removed. You can see this with the system columns ctid (the tuple's physical location as page and slot), xmin (the transaction that created it), and xmax (the transaction that deleted or replaced it).
CREATE TABLE bloat_demo (
id integer PRIMARY KEY,
payload text NOT NULL
);
INSERT INTO bloat_demo
SELECT g, repeat('x', 100)
FROM generate_series(1, 100000) AS g;
SELECT ctid, xmin, xmax, id FROM bloat_demo WHERE id = 1;
UPDATE bloat_demo SET payload = repeat('y', 100) WHERE id = 1;
SELECT ctid, xmin, xmax, id FROM bloat_demo WHERE id = 1;After the UPDATE, the visible row for id = 1 has a different ctid and a new xmin. The old version still sits at its previous location, and a query cannot see it. That old version is a dead tuple once no open transaction can still see it.
Now update every row and compare the heap size:
SELECT pg_size_pretty(pg_relation_size('bloat_demo')) AS before_update;
UPDATE bloat_demo SET payload = repeat('y', 100);
SELECT pg_size_pretty(pg_relation_size('bloat_demo')) AS after_update;
SELECT count(*) AS live_rows FROM bloat_demo;The table still has 100,000 live rows, but the heap is roughly twice as large. Every row now has one live version and one dead version. Exact sizes depend on your version and settings. A full-table UPDATE needs room for all the new versions while the old ones are still there, so the file roughly doubles unless free space already existed.
Why the file does not shrink
Reclaiming a dead tuple does not return disk space to the operating system. Plain VACUUM marks the space as free inside the page, and later inserts and updates can use it. The file stays the same size. The only exception is that VACUUM can truncate completely empty pages at the very end of the file, and only under conditions that often do not hold on a busy table.
So after a large one-time delete, the table can be half empty and still occupy the same disk space. This is the main reason bloat is persistent: you cannot fix it by waiting.
Why bloat hurts
Wasted disk space
The most visible cost is storage. A 50 GB table with 10 GB of live data costs 50 GB on the primary, on every replica, and in every base backup. Backup time, restore time, and replication traffic all grow with the file size, not with the live data.
Slower sequential scans
A sequential scan reads every page of the heap, whether the page holds live rows or not. The cost is proportional to the file size. A query that scans a table twice as large as it needs to be does twice the I/O. Aggregates, reports, and any query the planner cannot serve from an index feel this directly.
Less efficient index scans and caching
A query that uses an index jumps directly to the heap pages it needs, so it is less sensitive to total file size. It still suffers in two ways.
- Live rows are spread across more pages. Fetching 100 related rows may touch more pages than if the table were compact, so more pages must be read and kept in memory.
- Indexes point at tuples and are bloated by the same churn. Index entries for dead tuples stay until VACUUM removes them, and index pages can end up sparsely filled. Larger indexes mean more pages read per lookup and a lower cache hit rate.
Memory is also affected. shared_buffers and the operating system cache hold pages, not rows. Pages that are mostly dead tuples or free space take cache space away from useful data. A working set that once fit in RAM may no longer fit.
Slower maintenance
VACUUM has to read pages to find dead tuples, and it scans the indexes to remove their entries. Larger tables and indexes make each VACUUM run take longer. Longer runs leave dead tuples around longer, which creates more bloat. ANALYZE and pg_dump also read the larger table.
Worse planner estimates
The planner estimates costs partly from the table's page count and its row count. If statistics are stale or the page count is out of proportion to the row count, plans can shift toward worse choices. This is rarely the first symptom, but it can appear when bloat and stale statistics occur together.
Healthy versus harmful bloat
Not all bloat needs action. A table with steady updates will always contain some dead tuples and free space between VACUUM runs. When VACUUM keeps up, the file reaches a stable size, and the freed space is reused instead of growing the file. That is the normal steady state.
Bloat becomes a problem when the file keeps growing, when the dead space is large compared with live data, or when the extra size makes queries and backups noticeably slower.
What makes bloat worse
Several workload patterns accelerate bloat:
- Frequent updates on wide rows. Each update writes a full new copy of the row, even if one small column changed.
- Large bulk updates or deletes. One statement can leave millions of dead tuples at once, which is the situation in the demo above.
- Cleanup that cannot run. VACUUM can only remove tuples that no transaction can still see. A long-running transaction, a stale replication slot, or an abandoned prepared transaction holds that boundary back, and dead tuples accumulate no matter how often VACUUM runs. A later chapter covers these blockers.
- VACUUM that runs too rarely. Default autovacuum settings can be too relaxed for large, busy tables.
A quick check on your own database
You can see which tables carry dead tuples without extra extensions:
SELECT relname,
n_live_tup,
n_dead_tup,
pg_size_pretty(pg_total_relation_size(relid)) AS total_size
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC
LIMIT 5;pg_total_relation_size includes the heap, indexes, and TOAST data. The counts are estimates maintained by the statistics system, and they can lag behind recent activity. They give you a starting list of suspects, not a measurement of bloat.
Summary of the costs
| Cost | Why it happens | Who feels it |
|---|---|---|
| Extra disk space | Dead tuples and free space stay in the file | Primary, replicas, backups |
| Slow sequential scans | Scans read every page, including dead ones | Reports, aggregates |
| Poor cache use | Pages with little live data occupy memory | All queries |
| Larger indexes | Index entries for dead tuples remain | Lookups, writes |
| Longer maintenance | VACUUM and ANALYZE read more pages | Autovacuum, operators |
Exercise
You update every row of a 100,000-row table once, and the heap file about doubles. After that, SELECT count(*) still returns 100,000. Where is the extra space, and why does it not go away on its own?
Show answer
The extra space holds the old row versions. Each UPDATE wrote a new tuple and left the previous one in place as a dead tuple. The file does not shrink on its own because even after VACUUM marks that space reusable, PostgreSQL keeps it in the file for future rows instead of returning it to the operating system. Plain VACUUM can only truncate empty pages at the end of the file. Until the space is reused or the table is rewritten, the file stays at its larger size.
Exercise
A table has a very high ndeadtup, but its file size has been stable for weeks. Is this bloat growing out of control? What would you check next?
Show answer
Not necessarily. A stable file size means the dead space is being reclaimed and reused as fast as it is created, which is the normal steady state. A high dead tuple count may only mean cleanup is pending at the moment you looked. Check when autovacuum last ran on the table (last_autovacuum in pg_stat_user_tables), and measure the free space and dead tuple percentage more accurately before deciding whether any action is needed.