VACUUM, Dead Tuples, and Free Space
What actually happens to index entries on DELETE or UPDATE
The index entry is not removed immediately. Queries that started before the delete do not fail — here is why.
- The heap row's
xmaxis set to the deleting transaction's ID. The row is still physically there. - The B-tree entry (
'john@example.com' → TID) is left completely untouched. The heap slot is still occupied. Nothing is freed. - Any query following that entry arrives at the heap row and checks MVCC visibility there: started before the delete → sees
xmaxas not-yet-committed → reads the row normally; started after → sees it committed → skips the row as invisible. - VACUUM later removes the dead heap row and then the now-dangling index entry.
UPDATE on an indexed column
An UPDATE is internally DELETE + INSERT under MVCC:
- Old heap row:
xmaxset to the updating transaction. - New heap row inserted with
xmin= updating transaction and the new value. - New index entry
'new@example.com' → new TIDadded to the B-tree. - Old index entry
'john@example.com' → old TIDleft in place until VACUUM.
Which entry does a query use? The index doesn't decide — it hands over candidates
In the example above the two entries have different keys, so a scan for one key only ever finds that one. The genuinely ambiguous case is an update leaving the indexed value unchanged (e.g. id=1 stays id=1, only another column changes). Then the B-tree holds two entries with the same key pointing at two different TIDs:
id=1 → TID(42, 3) ← OLD tuple (age=25, xmax=200)
id=1 → TID(42, 7) ← NEW tuple (age=26, xmin=200)A scan for
id=1returns both TIDs. The executor follows each to the heap and checksxmin/xmaxthere. The index never filters — it hands out every candidate and lets heap-level MVCC decide which is visible to the current transaction.
HOT — skipping new index entries entirely
If an update touches no indexed column and the new row fits on the same heap page, PostgreSQL uses a Heap Only Tuple:
- No new index entry is written at all.
- The old index entry still points at the old heap row.
- The heap page stores a forwarding chain: old row → new row.
- A reader follows the index to the old row, sees it is the head of a HOT chain, and follows the chain to the current version.
This avoids index bloat for frequent updates to non-indexed columns — e.g. bumping a last_seen timestamp when only email is indexed.
When VACUUM can actually act: OldestXmin
VACUUM doesn't remove a dead row the moment a delete happens. It waits until it can prove no running transaction will ever need it. PostgreSQL tracks OldestXmin — the xmin of the oldest snapshot held by any currently running transaction. A deleted row with committed xmax < OldestXmin is truly dead.
Transaction A starts at xid=100 ← holds a snapshot from xid=100
Transaction B deletes row at xid=150 → xmax=150 set on the heap row, B commits
OldestXmin = 100 ← A is still running; cannot remove the row yet
A might still follow the index entry and read it
Transaction A finishes
OldestXmin = 200 ← 200 > 150 → safe to removeWhere OldestXmin actually lives
It isn't a counter written to disk — it is computed on demand from shared memory. Every connected backend has a PGPROC entry in the ProcArray, carrying its current transaction id and its snapshot's xmin:
ProcArray (shared memory, one row per active backend):
backend 1: xid=210 xmin=205
backend 2: xid=211 xmin=100 ← long-running transaction
backend 3: xid=212 xmin=211
GetOldestXmin() scans this array → min(205, 100, 211) = 100Not just local backends. The same scan folds in other holders of visibility, because they too can prevent reclamation:
- Physical/logical replication slots (
xmin,catalog_xmin) - Prepared transactions (two-phase commit, not yet committed or rolled back)
- Hot-standby feedback from replicas — "don't vacuum rows I might still query"
Why scanning is cheap: the array is bounded by max_connections, not table size. Scanning a few hundred entries is trivial next to scanning a multi-GB heap — which is why the horizon can be recomputed fresh at the start of every vacuum rather than maintained incrementally.
What triggers autovacuum
trigger when: dead_tuples > autovacuum_vacuum_threshold + autovacuum_vacuum_scale_factor × table_size
defaults: 50 dead rows + 20% of table size
Removal order: index first, then heap
An index entry holds no MVCC data of its own — just key → TID. It has no way to tell "stale" from "live"; it only trusts that whatever TID it points at is a real, current row. That is precisely why order matters:
- Phase 1 — scan heap: collect TIDs of all rows with committed
xmax < OldestXmin. Visibility can only be checked here; the heap tuple is the only placexmin/xmaxactually live. - Phase 2 — for each index: remove entries whose TID is in that dead set. Pure TID matching, no visibility check — the index has nothing to check against.
- Phase 3 — free the heap slots and update the Free Space Map.
Concretely, after VACUUM reclaims "john" from page 891:
slot1 → [FREE] ← space now reusable via the FSM
slot2 → Record 2: jane, 30 (live)
slot3 → Record 3: bob, 35 (live)Regular VACUUM vs VACUUM FULL
Regular VACUUM
Reclaims space within existing pages, marks slots reusable, updates the FSM. Does not rewrite the file or return space to the OS. Runs concurrently with normal traffic.
VACUUM FULL
Rewrites the entire table into a new compact file. Does return space to the OS — but takes an exclusive lock on the table for the whole operation.
The visibility map — how VACUUM avoids scanning every page
Checking every tuple against OldestXmin is only needed for pages that might contain dead tuples. PostgreSQL tracks this per page in the visibility map — a tiny bitmap file (.vm) alongside the table, roughly 2 bits per 8 KB heap page.
The bit means "all-visible," not "vacuumed." A page can be scanned and cleaned and still end at 0 if it holds a tuple not yet visible to every possible transaction.
When is the bit cleared? Any write that could introduce a not-yet-fully-visible tuple clears it immediately, not lazily — INSERT, UPDATE or DELETE on that page. The bit must come off before the new tuple is written, otherwise a concurrent vacuum could wrongly skip the page.
The Free Space Map: inserting into an existing page vs a new one
- Check the FSM for a page with enough free space for the record.
- If found → write into that existing page, filling the gap left by deleted/compacted records.
- If no page has room → allocate a new page, extending the file.
Free Space Map:
Page 100: 2,400 bytes free
Page 101: 180 bytes free
Page 102: 7,800 bytes free
Page 103: 0 bytes free
New record is 300 bytes:
→ Page 100 has room → write there
→ Update FSM: Page 100 now has 2,100 bytes freeVACUUM also updates the FSM after reclaiming space, which is what makes that space visible to future inserts. Without VACUUM, deleted space is wasted and the file keeps growing even when net data size is flat.
Is the FSM update synchronous? How does it handle concurrency?
Not synchronous, and that is intentional. The FSM is a hint, not a source of truth — it stores a coarse, approximate free-space category per page, not an exact byte count.
- FSM updates are not WAL-logged the way heap/index tuple writes are, and needn't be durable before commit. Crash before an FSM update reaches disk and the entry is merely stale afterward — not corrupt, just out of date.
- A stale entry costs a wasted attempt, nothing more: a backend tries a page the FSM claimed had room, finds it doesn't, and falls back. Regular VACUUM recomputes FSM entries as a side effect anyway.
Concurrency works the same way — a fast racy guess, with the real check one level down under a lock:
Backend A reads FSM → "page 42 looks like it has ~2,400 bytes free"
Backend B reads FSM → same page, same stale number, same instant
Both head toward page 42 — which is fine, because:
1. Whoever arrives first takes an exclusive lock on page 42 and re-checks
the page's OWN header (the actual source of truth) before writing.
2. That backend writes its tuple, updates the page header, releases the
lock, and updates the FSM to the new smaller total.
3. The second backend then takes the lock, re-checks the header, finds
less room than the FSM promised, and falls back — next FSM candidate,
or extend the file.The FSM lookup needs no strong locking and no synchronous durability, because the correctness boundary lives one level down — at the individual page, via a real lock and a re-check against that page's own exact numbers at the moment of writing.
Full lifecycle: how a TID like (42, 3) is actually born
page_number × 8192 is a formula — recomputed fresh on demand from a page number you already have. A TID is not a formula's output. It is a fact decided once, at insert time, by two independent local decisions, then simply remembered.
Step 1. Which page? The FSM decides — not the row's content. Heap rows have no required order, so Postgres doesn't compute a page; it asks the FSM "which page has enough free bytes?" and takes whatever qualifies at that moment.
FSM: Page 41 → 50 bytes free (too small) Page 42 → 2,400 bytes free (picked)
New row (300 bytes) → FSM says "page 42"Insert the same value a minute earlier, or into a table with a different delete history, and you get a different page. Nothing about the row determines this — only current free space does.
Step 2. Which slot? Whichever slot-array entry doesn't exist yet on that specific page. Each page tracks its own free space in its own header (slot array growing forward, tuple bytes backward). The FSM is just a cached approximate summary of these per-page numbers, kept in a small separate file (<relfilenode>_fsm) so Postgres needn't open every page to ask "do you have room?"
Page 42 already has slots 0, 1, 2 → the new tuple's bytes go into the free
middle space → ONE new slot entry (index 3) is appended pointing at it
→ TID(42, 3) now exists, purely as a local fact about this one pageStep 3. The FSM entry for page 42 is updated to the new smaller free-byte count, so the next insert makes a fresh decision.
Step 4. The index learns about TID(42, 3) — via a completely different procedure. This is the key asymmetry: the heap doesn't care which page a row lands on, but a B-tree absolutely cares about sorted position, so index insertion never consults the FSM to pick "any page with room."
1. Traverse the B-tree from the root, comparing the key against separator
keys at each level, to find the ONE leaf that owns the sorted range
containing this key. (A key search — not a free-space lookup.)
2. Leaf has room → insert (key → TID(42,3)) in sorted position.
3. Leaf is full → page split: the FSM grabs a fresh page, ~half the
entries move over, the parent gets a new separator
key + pointer. (This is the one place index insertion
DOES touch the FSM — for a blank page to split into,
not for deciding where the key belongs.)write path builds the fact; read path re-derives its meaning
WRITE (once): FSM picks page 42 (free-space search)
→ page 42's slot array appends slot 3 (local counter)
→ index B-tree traversal finds the leaf (key search)
→ leaf stores key → TID(42, 3)
READ (later): index traversal → key → TID(42, 3)
→ byte_offset = 42 × 8192 (logical arithmetic)
→ pread() → OS/filesystem resolve to physical disk
→ within the page: slot[3] → (offset, length) → tuple bytes
(42, 3)cannot be recomputed from the key the waypage_number × 8192can be recomputed from a page number. It is a fact written down exactly once by two unrelated decisions — a free-space search on the heap side, a sorted-key search on the index side — and the index's whole job is to remember that fact so nothing ever has to rediscover it.
Bootstrapping: what happens for the very first row?
A brand-new table has zero heap pages — the file is 0 bytes. The FSM, which only tracks free space per existing page, has zero entries too. An empty FSM and an empty table are the same fact seen from two sides. Run the normal steps through this case and step 3 simply runs — it is not a special case for "first row," it is the same branch that runs whenever the FSM has nothing to offer.
1. Heap file extended by one page: page 0.
Fresh 8 KB block, initialized with just a page header
(empty slot array, empty tuple area) → ~8,168 bytes free.
2. Tuple bytes written into that free space; slot 0 appended to the
(previously empty) slot array → TID(0, 0) now exists.
3. ONLY NOW does the FSM get its first real entry:
"page 0 → (8168 − tuple_size) bytes free"
— written after the insert, as a byproduct, so the NEXT insert
has something to check.How does a brand-new page get numbered — and where does it physically land?
Page numbering is pure counting, not a search:
new_page_number = (current file size in bytes) ÷ 8192
a new relation's file is 0 bytes; 0 ÷ 8192 = 0. "Page 0" isn't chosen — it's simply what first means for an empty file.
Physical placement is a separate question, and genuinely is arbitrary — but at a different layer:
Postgres: "extend the file by 8192 bytes" — purely logical, no physical
address involved
Filesystem: receives the extend request → asks its block allocator for one
free physical block → picks WHATEVER block is free (anywhere on
the device, no relationship to page number 0)
Filesystem: records that choice in this file's extent map:
"logical page 0 (bytes 0–8191) → physical block #X"That extent-map entry is created via the exact mechanism from the SSTables and sparse indexes part. Postgres never sees block #X — it only ever refers to "page 0" again. The clean split: the page number is a deterministic count of pages that came before it; where those bytes physically sit is an arbitrary allocator decision recorded in metadata Postgres never inspects. A table's page 0 and page 5,000 could be physically adjacent or far apart — being page 0 implies nothing about placement.
The Invariants
- Guarantees: A row is never physically removed while any running transaction could still see it, and an index entry is never left pointing at a slot that has already been handed to a different row.
- Does not guarantee: That space is ever returned to the OS (only
VACUUM FULLdoes that), or that VACUUM makes progress at all — one long-running transaction pinsOldestXminand blocks reclamation indefinitely.