Skip to main content

Postgres Doesn’t Look Back

How MVCC, WAL and one bit in pg_xact keep transactions atomic without undoing a single byte.

Updated 14 min readMarkdown
Part of seriesACID, Connected
Postgres Doesn’t Look Back

Every textbook explains atomicity the same way: if a transaction fails, the database goes back and undoes what it did. Rollback means looking back.

So when I started reading the Postgres docs, it came as a shock: Postgres refuses to look back. It writes your uncommitted rows to disk without hesitation, and when you hit ROLLBACK it doesn't undo a single byte. Yet a Postgres transaction is still all-or-nothing, even across a crash.

The short answer is that atomicity in Postgres is not a feature living in one module. It falls out of four mechanisms working together: MVCC tuple headers, the buffer manager, the write-ahead log (WAL), and a tiny file called pg_xact. HOT updates then test the whole design. Let's build it up one piece at a time.

What atomicity actually promises

Atomicity is the A in ACID: a transaction's changes either all happen or none of them do. Nobody, not a concurrent reader and not the database after a crash, should ever see half a transaction.

Take the classic example:

BEGIN;
UPDATE accounts SET balance = balance - 500 WHERE id = 1;  -- Saumya
UPDATE accounts SET balance = balance + 500 WHERE id = 2;  -- Mohit
COMMIT;

These two rows may live on two different 8 KB pages. Disks write pages one at a time. So the database must make two physically separate writes look like one indivisible event.

Pause. The machine can lose power between any two disk writes. What single thing could the database write that, by itself, decides whether the whole transaction happened?

Why the naive approaches fail

There are two obvious ways to get atomicity, and both are too slow or too restrictive for a real database.

Naive idea 1: never let uncommitted data reach disk ("no-steal"). Keep every page a transaction touched pinned in memory until COMMIT. Then the disk only ever holds committed data.

This breaks the moment a transaction is bigger than memory. An UPDATE over a 200 GB table cannot keep 200 GB of dirty pages pinned in a 4 GB buffer pool. The buffer manager must be allowed to evict, or "steal", a dirty page even when its owner hasn't committed.

Naive idea 2: write every touched page to disk at COMMIT ("force"). Then a committed transaction is always fully on disk.

This is painfully slow. A transaction that touches 1,000 rows scattered over 1,000 pages now needs 1,000 random writes before COMMIT can return. And it still isn't atomic: a crash halfway through those 1,000 writes leaves half a transaction on disk.

So a fast database wants the opposite of both: steal (evict dirty uncommitted pages whenever needed) and no-force (don't flush data pages at commit). Postgres does exactly that.

Pause. With steal + no-force, the disk can hold uncommitted changes, and can be missing committed ones. Most databases fix the first problem with an UNDO log that rolls changes back. Postgres has no UNDO log. How could it possibly get away with that?

Piece 1: MVCC — Never destroy the old truth

In Postgres, an UPDATE does not change a row in place. It writes a brand-new version of the row (a new tuple) and leaves the old one where it was. A DELETE writes nothing new; it just marks the old version as deleted.

Every tuple carries a header with, among other things:

Field Meaning
xmin ID of the transaction that created this version
xmax ID of the transaction that deleted or replaced it (0 if none)
t_ctid Pointer to the newer version, if this one was updated
t_infomask Flag bits, including the hint bits we'll meet soon

So after UPDATE accounts SET balance = 500 WHERE id = 1 run by transaction 101, the heap page holds two versions:

v1: xmin=90   xmax=101  balance=1000  t_ctid -> v2
v2: xmin=101  xmax=0    balance=500

Which version a reader sees is decided at read time, by asking two questions about each tuple: did the creator (xmin) commit? and did the deleter (xmax) commit? A version is visible if its xmin committed and its xmax did not (or there is none).

Notice what this means. The tuple itself never records whether it is "real". It only records who made it. Whether that transaction committed is stored somewhere else entirely.

Pause. If correctness depends only on whether transaction 101 committed, does it matter whether v2 is sitting on disk when 101 aborts?

Piece 2: The Buffer Manager — Where uncommitted data leaks to disk

The shared buffer pool is a cache of 8 KB pages. When a backend needs a page that isn't cached and the pool is full, the clock-sweep algorithm picks a victim. If the victim is dirty, it is written to disk first. The background writer and the checkpointer also write dirty pages on their own schedule.

None of these ask "has the transaction that dirtied this page committed?" They can't even answer it: one page may hold tuples from dozens of transactions, some committed, some running, some aborted. A page is just bytes.

So it is completely normal for v2 (xmin=101) to reach the data file while transaction 101 is still running, or after it aborts. This is the steal policy from earlier, and after Piece 1 it's no longer scary. A tuple on disk is not a claim that the change happened. It is a claim that transaction 101 tried to make this change. Whether 101 succeeded is a separate fact.

The buffer manager obeys exactly one rule when it writes a page, and that rule belongs to the WAL.

Piece 3: The WAL — One sequential write decides everything

Every change to a page is first described in the write-ahead log, an append-only sequential file. Each WAL record gets a position called an LSN, and the page remembers the LSN of the last record that touched it (pd_lsn in the page header).

The WAL rule: before a dirty page is written to the data file, the WAL must be flushed at least up to that page's pd_lsn. The buffer manager enforces this on every page write. So the log always knows about any change that the data file has.

Now look at what COMMIT actually does, in this order:

  1. Write a commit record for the transaction ID into the WAL.
  2. fsync the WAL up to and including that record (with synchronous_commit = on).
  3. Set the transaction's status to committed in pg_xact.
  4. Remove the transaction from the shared list of running transactions, so new snapshots see it as finished.

Step 2 is the atomic moment. Before the commit record is durable, the transaction did not happen. After, it did. One sequential write of a few dozen bytes decides the fate of every row the transaction touched, whether it touched 2 rows or 2 million.

That answers the first Pause: the single thing is the commit record.

And ROLLBACK? Postgres writes an abort record and marks the transaction aborted in pg_xact. That's all. No page is touched. The dead tuples stay where they are until VACUUM removes them later.

Pause. We now have the truth ("101 committed") in one place and the data (v2 with xmin=101) in another. A reader holding only the page sees xmin=101. How does it find out what happened to 101?

Piece 4: pg_xact and Hint Bits — Shifting burden to the reader

pg_xact (called pg_clog before Postgres 10) is the commit log: 2 bits per transaction ID, with four states: in progress, committed, aborted, sub-committed. At 2 bits each, one 8 KB page covers 32,768 transactions, so the recent part of it sits comfortably in a small dedicated cache.

When a reader meets v2 with xmin=101 and no other information, it does roughly this:

  1. Is 101 still running (in my snapshot)? Then v2 is invisible to me. Stop.
  2. Otherwise, look up 101 in pg_xact.
  3. Committed: v2's xmin is good. Aborted, or never finished: v2 never existed.

That lookup costs something on every tuple. And the answer can never change: once 101 commits or aborts, it stays that way forever. So Postgres caches the answer on the tuple itself, in t_infomask:

Hint bit Means
HEAP_XMIN_COMMITTED xmin is known committed
HEAP_XMIN_INVALID xmin is known aborted
HEAP_XMAX_COMMITTED xmax is known committed
HEAP_XMAX_INVALID xmax is known aborted or unset

The first reader that resolves 101 sets the hint bit and marks the page dirty. Every later reader skips pg_xact entirely. This is why the first SELECT after a big load can produce a burst of disk writes: the first read of a tuple is also a write.

Two subtle details are worth knowing:

  • Setting a hint bit is not WAL-logged. Losing it in a crash is harmless; the next reader just checks pg_xact again. (If data checksums or wal_log_hints are on, the first hint change after a checkpoint logs a full-page image, so a torn page can't fail its checksum.)
  • With asynchronous commit, Postgres won't set HEAP_XMIN_COMMITTED until the WAL is flushed past that commit record. Otherwise a hint bit could reach disk claiming a commit that a crash then erases.

So the steal policy and the hint bits fit together. The buffer manager writes v2 to disk whenever it likes. Whoever reads v2 first asks pg_xact, and writes the answer back onto the tuple.

xmin-visibility-check

Only the first reader takes the long path down to pg_xact; everyone after it stops at the first diamond. The xmax check works the same way, with the result flipped.

Piece 5: HOT Chains — Readers only walk forward

MVCC has a cost: every UPDATE creates a new tuple at a new location (a new TID). Normally every index on the table then needs a new entry pointing at it, even if you only changed a column no index cares about.

HOT (heap-only tuple) removes that cost when two conditions hold: no indexed column changed, and the new version fits on the same page. Then:

  • The old version is flagged HEAP_HOT_UPDATED, and its t_ctid points to the new one.
  • The new version is flagged HEAP_ONLY_TUPLE. No index entry is created for it.
  • Indexes keep pointing at the root of the chain, the original line pointer.

An index scan lands on the root and walks the chain forward, old to new, testing each version for visibility. It returns the one version its snapshot can see.

That direction matters. Chains in Postgres only point from older to newer. No reader ever starts at the newest version and walks back to find an older one.

Pause. Transaction 101 HOT-updates row 1 (v1 → v2), the page is evicted to disk, then 101 aborts. A new reader arrives through the index. Which version does it return, and why doesn't it need to "go back"?

Walk the chain:

v1: xmin=90 (committed)   xmax=101 (aborted)   -> visible: xmax doesn't count
v2: xmin=101 (aborted)    xmax=0               -> invisible: never existed

The reader reaches v1 first. Its deleter, 101, aborted, so the deletion never happened and v1 is still the live row. The reader sets HEAP_XMAX_INVALID on v1, then HEAP_XMIN_INVALID on v2 if it looks at it. Nobody went backward. The "older" value was never removed: an aborted xmax is simply ignored.

Later, page pruning (run opportunistically by readers when a page has room to reclaim) cuts dead members like v2 out of the chain. VACUUM handles the rest. Cleanup happens long after the abort, in the background, and correctness never depended on it.

Putting it together: pull the plug

Back to the transfer. Transaction 101 debits Saumya's row on page A and credits Mohit's row on page B. Each update leaves an old version with xmax=101 and a new version with xmin=101. Pull the power cord at three different moments.

Crash before the commit record is durable. Page A was evicted mid-transaction, so A's new version is on disk; B's isn't. Recovery replays the WAL from the last checkpoint and may rebuild B's new version too. But there is no commit record for 101. After restart 101 isn't running, and pg_xact doesn't say committed, so it is treated as aborted. Both new versions are invisible, both old versions are live. The half-written state is on disk, and it doesn't matter.

Crash after the commit record, before any data page was written. This is the no-force case: the committed data is missing from the data files. But the WAL is flushed through the commit record, and by the WAL rule it holds every change 101 made. Redo replays them onto pages A and B, then replays the commit record into pg_xact. Both new versions are visible.

Crash after the commit record, before the pg_xact page was written. pg_xact is cached in memory too, so its update can be lost. Redo replays the commit record and sets the bit again. Same result as above.

In every case both rows move together, because both are judged by the same 2 bits about 101, and those bits are fixed by one WAL record. That's the whole trick. The WAL only ever needs to redo. Postgres has no UNDO log because MVCC never destroyed the old version in the first place. "Undoing" a transaction is just declaring its xid aborted.

One more failure mode for completeness: a power cut in the middle of writing an 8 KB page can leave a torn page, half old and half new. Postgres guards against this with full_page_writes: the first change to a page after each checkpoint logs the whole page image to WAL, so redo can start from a clean copy.

No Free Lunch: The price of never undoing anything

Every system design is a trade-off, and this one is no exception. The costs show up in places every Postgres operator knows:

  • Bloat. Aborted and outdated versions sit in the heap until VACUUM reclaims them. A rolled-back bulk load leaves gigabytes of dead tuples behind.
  • Write amplification on reads. The first read after a big write sets hint bits and dirties pages, and with checksums on it can also log full-page images.
  • Transaction ID wraparound. Visibility leans on 32-bit xids compared against pg_xact, so old tuples must eventually be frozen by VACUUM before the counter wraps.

In exchange, Postgres gets an instant ROLLBACK of any size, a crash recovery that only replays forward, and readers that never block writers.

Recap

Mechanism Its job in atomicity
MVCC tuple headers Store who made each version, never whether it's valid
Buffer manager (steal, no-force) Write any page anytime, without regard to commit status
WAL + commit record Make the commit one durable, sequential write: the atomic moment
pg_xact Hold the 2-bit truth about every transaction
Hint bits Cache that truth on the tuple, so the first read pays once
HOT chains Keep versions on one page; readers walk old → new and pick the visible one

Atomicity in Postgres isn't enforced by cleaning up after failures. It comes from never letting data decide its own validity. Every row points at a transaction, every transaction points at one bit, and that bit is set by one write.

Next in ACID, Connected: how snapshots decide which committed transactions you're allowed to see, which is isolation, the I in ACID.

About the author

  • Storage & database engineer. Database internals, modern C++, concurrency.

No comments yet. Be the first to comment.

ACID, Connected

Part 1 of 2

Atomicity, consistency, isolation, durability: how Postgres keeps each promise, and how its parts connect to do it. One letter at a time, from the problem to the design.

Up nextPostgres Lives in the PastHow snapshots decide which committed transactions you're allowed to see: isolation, the I in ACID