In-Place Writes: WAL, Buffer Pool, Latches

Why in-place updates need a WAL at all

Unlike LSM trees, which write immutable files, B-trees overwrite pages in place. A crash mid-write leaves a page half-updated — and unlike a torn WAL entry (see WAL), a torn page is not a discardable tail; it is corruption of live data:

Page 47 before the update holds valid data. Power fails while the page is being overwritten in place. After restart page 47 is half new bytes and half old bytes: corrupt, and unlike a torn WAL tail it cannot be discarded, because it is live data.
Overwriting in place can leave a page that is neither old nor new
  1. Append the intended change to the WAL file — a sequential write, fast.
  2. Modify the page in the buffer pool (RAM) → mark it dirty. The client is acknowledged here — WAL on disk is enough for durability.
  3. Later, the background checkpointer flushes the dirty page to disk.

The page is never written synchronously per write. The WAL is the durability guarantee: crash before the dirty page flushes and WAL replay reconstructs it. The checkpointer batches flushes for efficiency.

Both LSM trees and B-trees use a WAL — for different failures. LSM uses it to protect the in-memory memtable (data that exists nowhere on disk yet). B-trees use it to protect against partial in-place page writes (data that exists on disk in a corrupted state). Same mechanism, different threat model — this is one half of the answer to the guide's Central Question.

How the DB knows what WAL has been flushed

LSNmonotonically increasing 64-bit id, stamped on every WAL record
pageLSNLSN of the last WAL record that modified this page, stored in its header
pg_controlsmall file holding the LSN of the last completed checkpoint
WAL record:   LSN=1042  "set page 47, slot 3, age=25"
Buffer pool:  page 47 header → pageLSN = 1042   (dirty, not yet on disk)

Checkpointer flushes page 47 to disk
→ page 47 on disk now carries pageLSN = 1042 in its header

✓ Checkpoint

1. Checkpointer flushes all dirty pages to disk
2. Writes a checkpoint WAL record:
   "as of LSN=X, all pages are flushed"
3. Updates pg_control: lastCheckpointLSN = X

✓ Crash recovery — ARIES redo

1. Read pg_control → find lastCheckpointLSN
2. Scan WAL forward from that LSN
3. For each WAL record with LSN Y:
     if page.pageLSN >= Y → already flushed, skip
     else                 → redo the change

The buffer pool

Reading a page into the OS page cache does not update the disk file — it only means the file's bytes are now cached in RAM. The buffer pool is a separate, fixed-size region of RAM the database manages itself, holding buffer frames each sized to one page:

Disk pages 47 and 12 are each copied into a buffer-pool frame in RAM. A frame holds the page bytes plus three pieces of bookkeeping: a pin count, a dirty bit and a latch. A third frame is free.
A buffer frame is one page of bytes plus three pieces of bookkeeping Here page 47 is pinned by two operations and dirty — it cannot be evicted, and when it is, it must be flushed first. Page 12 is clean and unpinned, so it can be dropped instantly.
  • Cache hit — the page is already in a frame; use it, no disk I/O.
  • Cache miss — read from disk into a free frame, evicting a clean (or already-flushed) page if the pool is full.
  • pin count — how many active operations are using this frame; a pinned frame cannot be evicted.
  • dirty bit — the in-memory copy has been modified but not yet written back.
  • latch — mutex protecting the frame from concurrent modification.

The buffer pool is why a database can acknowledge a write before data hits disk: durability comes from the WAL, and the page is flushed later.

A page’s round trip. Read in: the disk page goes through the OS page cache into the database buffer pool, where it is modified in RAM and becomes a dirty page. Write back: first the WAL is fsynced, then the page is flushed, the OS writes it back, and the disk copy is updated.
A page’s round trip — and the WAL has to reach disk before the page does

The full write timeline — when is a write actually "done"?

Three different things finish at three very different times. Conflating "write acknowledged," "data physically on disk," and "vacuum has cleaned up after it" is one of the most common sources of wrong mental models here. They are strictly ordered and fully decoupled:

Three stages of a write, strictly ordered and decoupled. Stage 1, write acknowledged, synchronous: heap page and index pages modified in the buffer pool and marked dirty, WAL records for both appended and fsynced, which is where durability comes from, then the ACK. Afterwards only the WAL is on disk; a crash is repaired by WAL replay. Stage 2, pages flushed, in the background, milliseconds to minutes later: the checkpointer or background writer flushes dirty heap and index pages in no particular order, but never a page before its WAL record. Stage 3, VACUUM, triggered by a dead-tuple threshold: dead heap rows and their index entries removed once no snapshot can see them, visibility-map bits set back to 1, old tuples frozen against XID wraparound.
Acknowledged, flushed, vacuumed — three finish lines, strictly ordered and decoupled

Net effect: "write complete" only ever means Stage 1. Whether the heap page, the index page or the visibility map reflects that write on disk is a separate, later, background concern — sometimes seconds later, sometimes not until the next autovacuum run.

Walkthrough: UPDATE users SET age=26 WHERE id=1

First, the correct mental model. A common misconception is that a write goes "WAL → B-tree → heap" as three sequential disk writes. It does not. The heap is not downstream of the B-tree — they are siblings.

StructureHoldsModified on writeGenerates WALFlushed to disk
HeapThe actual rowIn RAMYesLazily
B-treekey → TID pointing into the heapIn RAMYesLazily

Step 1. Step 0 — the transaction gets an XID. Assignment is lazy: it happens at the first write, exactly when pages are about to be dirtied. Read-only transactions never consume a real XID — they get a lightweight virtual XID, so SELECTs don't burn through the counter.

Step 2. Step 1 — modify the HEAP page in the buffer pool.

Heap page 42 (RAM):
  old tuple: xmin=100, xmax=200, age=25   ← xmax stamped = "deleted by txn 200"
  new tuple: xmin=200, xmax=0,   age=26   ← new version
Page 42 → DIRTY

This is where xmin/xmax come into play — they are fields inside the tuple header on the heap page, so they reach disk as part of that page. (If page 42 isn't in the buffer pool yet, this triggers a read-modify-write — Deep Dive 1.)

Step 3. Step 2 — modify the B-TREE page in the buffer pool. The new tuple is at a new TID, so a new index entry appears:

B-tree leaf (RAM):
  id=1 → TID(42, 3)   ← OLD tuple (age=25, xmax=200)
  id=1 → TID(42, 7)   ← NEW tuple (age=26, xmin=200)
Leaf page → DIRTY

Both entries with key id=1 now physically exist. An index scan finds both, follows each TID to the heap, and the heap tuple'sxmin/xmax decides which is visible.

Step 4. Step 3 — generate WAL records for BOTH changes. As each page is modified a record is appended to the in-memory WAL buffer and the page's pageLSN is stamped.

WAL buffer:
  LSN 5000: heap update, page 42
  LSN 5001: btree insert, leaf, id=1 → TID(42,7)

Step 5. Step 4 — COMMIT: the durability point.

1. Append commit record:  LSN 5002: COMMIT txn 200
2. Flush WAL through LSN 5002   ← fsync; the ONLY blocking disk write
3. Write pg_xact[200] = COMMITTED
4. Return success to the client

At this instant heap page 42 and the B-tree leaf are still only in RAM, dirty. Durability holds anyway — a crash now is repaired by WAL replay.

Step 6. Step 5 — dirty pages flushed (later, async) by the background writer / checkpointer.

Deep dive 1: buffer pool miss — read-modify-write

What happens in Step 1 if page 42 isn't already in the pool?

Step 1. Miss. No frame holds page 42; it must be brought in before anything can touch it.

Step 2. Find a free frame, evicting if needed. Think of the pool as a parking lot with fixed spaces. If full, someone gets kicked out — chosen by clock-sweep: a hand moves around the frames in a circle; each frame has a usage counter incremented on access.

Clock-sweep eviction over four frames arranged in a circle, each with a usage counter. The hand starts at frame A, usage 2, decrements it to 1 and moves on; frame B, usage 1, goes to 0 and is skipped; frame C has usage 0 and is evicted. The sweep stops at the victim, so frame D, usage 3, is not visited on this pass. A clean victim is discarded instantly; a dirty one must be flushed first.
Clock-sweep: decrement until something reaches zero, then stop

This approximates "evict least-recently-used" without maintaining a sorted list. A clean frame is discarded instantly (the on-disk copy is identical); a dirty frame must be flushed first — and that flush has a hard constraint, see Deep Dive 2.

Step 3. Read page 42 from disk into the frame. The actual I/O. All existing tuples, their xmin/xmax stamps, and the page's free-space bookkeeping are copied into RAM.

Step 4. Pin and latch.pin_count++ prevents eviction while in use; the exclusive latch prevents a second writer touching the same page. Both released once the modification completes.

Step 5. Modify in RAM, mark dirty. Stamp the old tuple's xmax, append the new tuple, set the dirty bit so the checkpointer knows to flush it later.

Why writes are never blind: Postgres needs the existing page contents before it can write — the old tuple's xmax field to stamp, and the page's free-space bookkeeping to know where to append. Neither is possible without first reading the current page state into memory.

Deep dive 2: evicting dirty pages — WAL must hit disk first

It's easy to assume "WAL is always written first, so it's always on disk." Two different things are in play:

WAL buffer (RAM)  ← the record is appended here immediately when the page is modified
WAL on disk       ← only happens at COMMIT (or checkpoint)

So at the moment of eviction, the WAL for a page's changes may still be sitting in RAM.

Why this only comes up with long transactions: a short transaction commits quickly, fsyncing WAL before there's any eviction pressure — the write-ahead rule is trivially satisfied. A long one is different:

Buffer pool capacity: 10,000 frames
T200 has been running 10 minutes and has dirtied 50,000 pages
→ the pool fills up long before T200 commits
→ the background writer must evict T200's dirty pages just to make room
   for the pages T200 needs to read next
→ T200's WAL is still accumulating in RAM — no commit yet

That is precisely the scenario the pageLSN check exists for.

Deep dive 3: does the B-tree do MVCC like the heap? No.

Two index entries for the same key looks like MVCC. It is fundamentally different:

HeapB-tree index
Carries xmin/xmax?Yes, in every tuple headerNo — no visibility info at all
Knows which version is visible?Yes, per transactionNo — it just hands out TIDs
Duplicate entries are…True MVCC versionsA side effect of lazy cleanup

The heap does true MVCC. The index hands both TIDs to the executor, which follows each to the heap and checks xmin/xmax there. Visibility is resolved entirely at the heap, never at the index. The old entry sits there until VACUUM removes the dead heap tuple and then cleans up the corresponding index entry.

Practical consequence: an index scan on id=1 must always touch the heap, because the index can't tell you which TID is visible to you. Two exceptions: index-only scans (use the visibility map to skip the heap, but only for pages VACUUM has confirmed all-visible — see VACUUM and free space), and HOT updates (no new index entry at all; the heap chain handles versioning — see VACUUM and free space).

Do B-trees flush to disk periodically? Yes — the same mechanism as the heap

Both heap and index are just pages in the shared buffer pool. The checkpointer and background writer periodically write all dirty pages — heap and index alike — back to their files, and a checkpoint writes a marker ("everything up to LSN X is on disk") that recovery replays from. Nothing about flushing is B-tree-specific. The governing rule is the same write-ahead rule: page.pageLSN ≤ flushed WAL LSN.

Page-level latches, and why they aren't locks

Two transactions writing the same page simultaneously would corrupt it. B-trees prevent this with page-level latches — lightweight mutexes held only for the duration of a single page read/write (microseconds to milliseconds). A writer holding an exclusive latch on page 47 blocks every other reader and writer of that page; reads and writes to different pages proceed fully in parallel.

LatchLock
DurationMicroseconds to millisecondsEntire transaction (seconds or longer)
Held byThe database engine (internal)A transaction (user-visible)
PurposeStructural integrity of a pageLogical data consistency across operations
VisibilityInvisible to queries/usersVisible — e.g. SELECT FOR UPDATE, pg_locks

How a latch is actually implemented

It is not stored inside the on-disk page bytes. It lives in the in-memory buffer frame metadata for that page — alongside pin_count and the dirty bit — typically as a mutex, spinlock, or reader-writer latch, built on atomic CPU instructions (compare-and-swap, test-and-set). "Page 47 is latched" really means "the in-memory control structure associated with page 47 is currently locked."

MutexLatch
Where usedGeneral OS / application programmingDatabase engine internals specifically
What it protectsAny shared resourceIn-memory DB structures (pages, buffer pool, B-tree nodes)
DurationVaries — can be held longAlways very short
Deadlock handlingOS / runtime may detectUsually not tracked — strict ordering rules prevent it
Blocking behaviourThread sleeps, context switchOften spin-waits first, then sleeps — hold time is so short that sleeping + waking costs more than spinning

A latch is a mutex under the hood. Databases coined a separate term because "lock" was already taken for logical, transactional constructs.

What happens to queries hitting a latched page

They wait — a shared-latch request blocks until the exclusive latch is released (typically microseconds to low milliseconds, the duration of one page write or split), then proceeds and sees the fully completed state. Exclusive requests queue the same way. Writers for different pages are never blocked.

Timeline of inserting key 334, which splits page 47. At 0 ms the writer takes an exclusive latch on page 47. Query A tries to read page 47 at 0 ms and is blocked. Query B reads page 12 at 0 ms and proceeds immediately, because it is a different page. At 1 ms the writer finishes the split and releases the latch, and query A unblocks and reads the fully updated page 47.
A latch makes a page split atomic to readers — only that page waits

No query ever sees a partially split page. The latch guarantees page-level atomicity: you see the old state or the new state, never in between. And it works at scale because splits are rare relative to total queries, the latch is held only for the physical write (~1 ms) rather than the whole transaction, and only the pages on the split path are latched.

Row locks — the other kind of waiting

A row lock means a transaction has locked a specific tuple — not the page, not the table. In PostgreSQL this happens with SELECT ... FOR UPDATE, SELECT ... FOR SHARE, UPDATE, DELETE. Other transactions are prevented from modifying that row in conflicting ways, while plain snapshot reads continue unimpeded thanks to MVCC. Row-lock information is associated with the tuple and its transaction metadata, so if session A row-locks a tuple, session B waits on session A's transaction to finish.

LatchRow lock
ProtectsPhysical data structure (B-tree page, buffer frame)Logical data (a row/tuple)
DurationMicroseconds — released when the operation completesEntire transaction — seconds, minutes, longer
Held byA single thread doing a page read/write/splitA transaction
Deadlock detectionNo — too brief to deadlockYes — transactions can wait on each other
Released byEnd of the physical operationCOMMIT or ROLLBACK
Thread doing a B-tree traversal:
  acquire shared latch on root page   ← latch
  read root, find child pointer
  release shared latch on root        ← gone, microseconds later
  acquire shared latch on child ...

Transaction doing an UPDATE:
  acquire exclusive row lock on row 42  ← lock, held until COMMIT
  modify row 42
  ... other work, user input, network calls ...
  COMMIT → lock released

A latch is a mutex protecting the storage engine's physical consistency, held just long enough to read or write a page. A row lock is a semantic contract between transactions about who may modify a piece of data — it can outlive network round-trips and user think-time. You would never hold a latch that long; the buffer pool would stall.

The Invariants

  • Guarantees: No acknowledged write is lost, no partially-written page survives recovery, and no query ever observes a page mid-split — enforced by exactly two rules: fsync WAL before ACK, and flush a page only after its WAL is on disk.
  • Does not guarantee: That data is on disk when the client is told "success," or any bound on how far Stage 2 lags Stage 1. It also does not prevent transaction-level deadlocks — those live at the row-lock layer, where deadlock detection actually exists.