Part 15 / Topic 5 of 7
MVCC on disk: watching a table bloat
Part 12 told you UPDATEs write new row versions. Here is the bill. Update every row of our 100k table and look at the addresses:
UPDATE readings SET value = value + 1;
SELECT ctid, id FROM readings WHERE id <= 2;
UPDATE 100000
ctid | id
---------+----
(639,1) | 1
(639,2) | 2
(2 rows)
The rows moved — new ctids, because these are new tuples; the old 100,000 are still in the file as dead tuples, invisible but occupying pages. The bookkeeping view (pg_stat_force_next_flush() just nudges the statistics out immediately so the demo is instant):
SELECT pg_stat_force_next_flush();
SELECT pg_sleep(0.2);
SELECT n_live_tup, n_dead_tup,
pg_size_pretty(pg_relation_size('readings')) AS heap_size
FROM pg_stat_user_tables
WHERE relname = 'readings';
pg_stat_force_next_flush
--------------------------
(1 row)
pg_sleep
----------
(1 row)
n_live_tup | n_dead_tup | heap_size
------------+------------+-----------
100000 | 99991 | 10208 kB
(1 row)
100k live, 100k dead, the table roughly doubled. That growth is bloat — MVCC's deferred cost, and the single most common "why is this table 40 GB with 2 GB of data" answer in production.
🧪 Quick quiz — answer from memory, then check.
- After updating all 100k rows once, how many tuples does the heap hold?
- What is bloat?
Show the answers
- ~200,000 — the live versions plus the dead originals.
- Space held by dead row versions (and empty page slots) that the table's live data doesn't need.
Done here? The practice set for Part 15 — 5 exercises with solutions — is on the part page.