MVCC and Visibility

Every row carries two hidden fields

FieldMeaning
xminID of the transaction that created this version
xmaxID of the transaction that deleted this version (0 = still alive)

Think of them as "born in txn X, killed in txn Y." The payoff of keeping both versions around: readers and writers never block each other, because they are looking at different versions.

✓ UPDATE — writes a new row, stamps the old

Initial (inserted by txn 100):
  row A:  xmin=100  xmax=0    age=25   ← alive

After UPDATE by txn 200:
  row A:  xmin=100  xmax=200  age=25   ← old, "killed" by 200
  row B:  xmin=200  xmax=0    age=26   ← new version, alive

✗ DELETE — nothing is physically removed

After DELETE by txn 200:
  row A:  xmin=100  xmax=200  age=25   ← still on disk, "killed"

Dead rows are cleaned up later by VACUUM (Section 14).

Transactions, XIDs, and what "committed" physically means

A transaction is a group of operations treated as one unit — all of them happen or none do. Every transaction gets an XID: a monotonically increasing integer assigned the moment it does any write. A global timestamp, except it's a counter, not a clock.

txn starts  → assigned XID 200
txn works   → reads, writes
txn commits → pg_xact marks XID 200 as COMMITTED (or ABORTED on rollback)

XIDs are global across all tables and sessions, so txn 201 definitively started after txn 200.

How XIDs connect to rows on disk

The key link: every row on disk is stamped with the XID of the transaction that wrote it, permanently, in the page bytes alongside the data.

Page 47 on disk holds four tuples, each stamped with xmin and xmax. Row 1, Alice: xmin 98, xmax 0. Row 2, Bob: xmin 100, xmax 200, the old version killed by transaction 200. Row 3, Bob: xmin 200, xmax 0, the new version made by transaction 200. Row 4, Carol: xmin 99, xmax 0. Rows 2 and 3 are two versions of the same logical row, sitting in the same page.
Old and new versions of a row live side by side in the same page Which version a reader sees is decided purely by comparing these XID stamps with its own snapshot — the bytes are the same for everyone.

One page holds multiple versions of the same logical row. There is no separate "version store" — old and new coexist in the same page (or spill to nearby ones). Same bytes, different readers, different answers — decided purely by XID stamps versus each reader's snapshot.

pg_xact — two bits per transaction

IN_PROGRESS = 00
COMMITTED   = 01
ABORTED     = 10

A committing transaction flips its bits to 01 here before telling the client "success." The visibility check ultimately reduces to: look up xmin/xmax in pg_xact.

row on disk → xmin/xmax (XIDs) → pg_xact lookup → committed? → visible?

What a snapshot is

When your transaction starts it takes a snapshot — a record of which transactions had committed at that exact moment. Not a copy of any data: three small pieces of metadata in your backend's local memory.

FieldMeaning
snapshot.xminLowest XID still running when the snapshot was taken. Everything below this is definitely finished (committed or aborted).
snapshot.xmaxThe next XID not yet assigned. Everything at or above this doesn't exist yet.
snapshot.xip[]The XIDs actively running when the snapshot was taken — the "grey zone" between xmin and xmax.

The snapshot is frozen for the lifetime of your transaction. It never updates to reflect what commits while you run: txn 101 committing mid-query is invisible to you; txn 200 deleting a row you're reading is ignored, because your snapshot recorded it as in-progress.

Where it comes from:

Global shared memory (visible to all backends):
  - current XID counter   → becomes snapshot.xmax
  - ProcArray             → list of running backends and their XIDs
                            → becomes snapshot.xip[] and snapshot.xmin

Your backend's local memory:
  - SnapshotData { xmin, xmax, xip[] }  ← frozen copy, lives until txn ends

The ProcArray is a shared-memory structure where every active backend registers itself and its current XID. Taking a snapshot is reading it and freezing it — no disk I/O, no table scan, just copying a few integers.

Three layers of visibility checking, fast → slow

The naive approach — look up every xmin/xmax in pg_xact on disk — would mean a disk read per row scanned. Three layers avoid that.

Layer 1 — snapshot range check (pure math, zero I/O)

The XID number line, divided by a snapshot. XIDs below snapshot.xmin finished before the snapshot was taken, so whether they committed or aborted is decided by hint bits in layer 2. XIDs from snapshot.xmin up to snapshot.xmax are a mix: those listed in xip[] are still running and not visible, the rest committed before the snapshot and are visible. snapshot.xmin itself is the lowest running XID, so it is always in xip[]. XIDs at or above snapshot.xmax have not been assigned yet and are not visible.
Layer 1 is arithmetic: a snapshot cuts the XID line into three zones

The insight about xip[]: XIDs between xmin and xmax are a mix of committed and still-running. xip[] lists only the still-running ones, so anything in that range and absent from xip[] must already have committed.

Layer 2 — hint bits (reading the row header, zero I/O)

Layer 1 can prove "this XID is finished" but not whether it committed or aborted. Normally that needs pg_xact. Hint bits cache the answer inside the row itself.

Why not set the hint bit at commit time? A committing transaction may have touched thousands of rows across many pages. Going back to write "yes, I committed" on every one of them would dirty all those pages for pure bookkeeping. So it's done lazily — the first reader pays the pg_xact cost once and caches the result for everyone after.

txn 50 inserts row A → xmin=50 stamped on row, no hint bit
txn 50 commits       → only pg_xact[50] flips to COMMITTED; row A untouched

First reader of row A:
  sees xmin=50, no hint bit → "don't know if 50 committed or aborted"
  → reads pg_xact[50] → COMMITTED
  → writes HEAP_XMIN_COMMITTED into row A's header
  → returns the row

Every subsequent reader:
  sees the flag → skips pg_xact entirely → returns the row

It is unusual that a read writes something — and intentional: pay the lookup once per row, never again.

Layer 3 — pg_xact lookup (disk read)

Reached only when hint bits aren't set yet — i.e. the very first read of a row since its transaction finished. After that one lookup the hint bit is written and layer 3 never runs for that row again.

Decision flow for one XID on a row. Layer 1, the snapshot range check, is pure math with zero I/O: an XID at or above snapshot.xmax is not visible; an XID in the xip list is not visible; an XID between xmin and xmax but not in xip is visible. An XID below snapshot.xmin has finished but may have committed or aborted, so it drops to layer 2: if the hint bit is set on the row, the cached answer is used, with zero I/O. If not, layer 3 reads pg_xact from disk, gets the answer and writes the hint bit, so the next reader of that row stops at layer 2.
Most visibility checks never leave layer 1 or 2 — pg_xact is read once per row

Full worked example

Worked example. Transactions 50, 98, 99 and 101 have committed; 100, 102 and 103 are in progress; 104 and above are not assigned yet. Your snapshot is xmin 100, xmax 104, xip 100, 102, 103. Transaction 101 committed just before the snapshot, so it is visible. Five row versions on the page: Row A, Alice old, xmin 50, xmax 101, not visible because its deletion committed. Row B, Alice new, xmin 101, xmax 0, visible with age 26. Row C, Bob, xmin 98, xmax 102, visible with age 30 because the deleting transaction 102 is still running. Row D, Carol, xmin 99, xmax 0, visible with age 35. Row E, xmin 100, not visible because transaction 100 is still running.
One snapshot, five row versions — colour each XID, and the verdicts follow
Rowxmin checkxmax checkVerdict
A (Alice old)50 < 100 → finished; hint bit says committed ✓101 in 100–104, not in xip[] → committed → the deletion is realNOT VISIBLE
B (Alice new)101 in 100–104, not in xip[] → committed ✓0 → not deletedVISIBLE — age 26
C (Bob)98 < 100 → committed ✓102 in 100–104 and in xip[] → still running → ignore this deletionVISIBLE — age 30
D (Carol)99 < 100 → committed ✓0 → not deletedVISIBLE — age 35
E (txn 100's insert)100 is in xip[] → still running—NOT VISIBLE

Result: Alice(26), Bob(30), Carol(35). Bob shows up even though he is being actively deleted right now — because his deleter hadn't committed when your snapshot was taken. No locks were taken anywhere during any of this.

The XID counter: in memory, durable across restart

The live counter nextXid is a global integer in shared memory, incremented atomically per assignment. It is not fsynced per transaction — that would add a dedicated disk write to every transaction. Durability is achieved indirectly, and it is important that this is a different piece of data from the WAL commit record:

nextXid counter   = "what number do I hand out next"  (a single integer)
WAL commit record = "txn 200 committed"                (names the XID, written
                                                        for the txn's durability)

Nothing ever writes "nextXid is now 201" to disk. The counter is reconstructed from XIDs already in the WAL for other reasons:

Normal operation:  nextXid in shared memory, atomic increment per assignment
At each checkpoint: current nextXid snapshotted into pg_control (cheap, once)
Every WAL record is tagged with the XID that produced it.

Crash recovery:
  1. Read pg_control → nextXid as of last checkpoint = a FLOOR (e.g. 5000)
  2. Replay WAL forward; for every XID seen, advance the counter past it
       sees 5001 → ≥5002 ... sees commit for 5247 → ≥5248
  3. Set nextXid = 5248

So the commit record is a real per-transaction disk write (for the transaction's durability), and because it carries the XID, the counter's durability comes for free — no extra dedicated write.

Why "never reuse an XID" matters: every tuple is stamped with its writer's XID. If the counter restarted lower and reused 200, a new txn 200 would be indistinguishable from the old one that stamped existing tuples — visibility chaos. Rolling nextXid past everything in the WAL guarantees a fresh XID is always strictly newer than anything on disk.

XID wraparound and freezing — why VACUUM is mandatory

XIDs are 32-bit (~4.2 billion values), then the counter wraps. But visibility compares XIDs ("was this created before me?"), so Postgres compares modulo 2³¹: for any current XID, ~2 billion XIDs "behind" count as past and ~2 billion "ahead" count as future.

The fix — freezing: VACUUM finds old tuples that are committed and visible to everyone and marks their xmin frozen. A frozen tuple is unconditionally visible, exempt from the modulo comparison, so it can never be lapped.

Historically: xmin physically overwritten with FrozenTransactionId (value 2)
Modern PG:    a frozen hint flag is set (HEAP_XMIN_FROZEN); original xmin preserved
Either way:   "visible to all, forever — ignore this tuple's XID"

Why VACUUM is not optional: without it, un-frozen old tuples pile up. As the oldest un-frozen XID nears ~2 billion behind the counter, Postgres forces emergency autovacuums; within the last few million it refuses new writes (ERROR: database is not accepting commands to avoid wraparound data loss) until you vacuum.

VACUUM has two distinct jobs: reclaim space from dead tuples (the xmax side, see VACUUM and free space) and freeze old live tuples before the counter laps them (the xmin side). The second is the existential one — and it is the job people forget exists.

WAL vs pg_xact — why both exist

They look redundant (both record that a transaction committed) but serve different lifetimes and access patterns:

WAL commit recordpg_xact
ShapeSequential redo log of page changesCompact map: XID → 2 bits
Answers"What page edits do I redo, and which txns committed in this recovery window?""Did XID N commit — ever, at any time?"
AccessSequential scan onlyRandom access by XID, O(1)
LifetimeRecycled/deleted after checkpointRetained as long as any tuple could reference that XID

They interact: the commit record is in the WAL, and replaying it during recovery is what writes pg_xact[XID]=COMMITTED. WAL drives pg_xact during recovery — they agree because one feeds the other.

But WAL can't replace pg_xact, because the commit record is temporary while the question it answers is permanent:

Today:          Txn 200 commits, inserts a row (tuple xmin=200)
                → WAL commit record written; pg_xact[200]=COMMITTED
Hours later:    checkpoint → that WAL segment recycled → commit record GONE
6 months later: SELECT reads that row
                → tuple xmin=200, no hint bit (page long evicted)
                → "did txn 200 commit?" — the WAL from 6 months ago is gone
                → pg_xact[200] still says COMMITTED ✓
                → row visible; hint bit now set so it never asks again

Without pg_xact, that later query would have no way to know the row is valid — short of keeping all WAL forever (absurd) or scanning it (impossibly slow).

WAL commit record → makes commit durable + drives redo during recovery
                    (sequential, short-lived, deleted after checkpoint)
pg_xact           → permanent, random-access "XID → did it commit?" map
                    (2 bits/XID; the visibility hot path depends on it)
hint bits         → per-tuple cache of pg_xact's answer
                    (the first read must consult pg_xact to populate them)

WAL tells you how to rebuild recent state after a crash; pg_xact tells you, forever, whether any given past transaction succeeded. Different lifetime, different access pattern — that is why both exist.

When is pg_xact cleaned up?

It is organized as segment files, each covering a range of XIDs. An entry can only be discarded when no live tuple on disk still needs to look up that XID. A tuple stops needing it in two ways: its xmin is frozen (always visible, ignore the XID), or the tuple is dead and vacuumed away.

Postgres tracks the oldest XID any live un-frozen tuple might still look up: datfrozenxid in pg_database (per database) and relfrozenxid in pg_class (per table).

pg_xact segment covers XIDs 1,000–131,072
VACUUM freezes all old tuples → datfrozenxid advances past 131,072
→ no live tuple needs any XID in this segment
→ VACUUM deletes the segment file

This is the second reason VACUUM is mandatory: freezing is what advances datfrozenxid, which is what allows old pg_xact segments to be reclaimed. Without VACUUM, pg_xact grows without bound.

The Invariants

  • Guarantees: Readers never block writers and writers never block readers; every transaction sees a consistent point-in-time view derived from two tuple fields and three snapshot integers, with no locks taken.
  • Does not guarantee: Bounded storage. Every version ever written stays on disk until VACUUM proves nobody can see it — and a single long-running transaction is enough to make that proof impossible indefinitely (see VACUUM and free space).