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:
- Append the intended change to the WAL file — a sequential write, fast.
- Modify the page in the buffer pool (RAM) → mark it dirty. The client is acknowledged here — WAL on disk is enough for durability.
- 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
| LSN | monotonically increasing 64-bit id, stamped on every WAL record |
|---|---|
| pageLSN | LSN of the last WAL record that modified this page, stored in its header |
| pg_control | small 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 changeThe 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:
- 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.
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:
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.
| Structure | Holds | Modified on write | Generates WAL | Flushed to disk |
|---|---|---|---|---|
| Heap | The actual row | In RAM | Yes | Lazily |
| B-tree | key → TID pointing into the heap | In RAM | Yes | Lazily |
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 clientAt 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.
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 yetThat 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:
| Heap | B-tree index | |
|---|---|---|
| Carries xmin/xmax? | Yes, in every tuple header | No — no visibility info at all |
| Knows which version is visible? | Yes, per transaction | No — it just hands out TIDs |
| Duplicate entries are… | True MVCC versions | A 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.
| Latch | Lock | |
|---|---|---|
| Duration | Microseconds to milliseconds | Entire transaction (seconds or longer) |
| Held by | The database engine (internal) | A transaction (user-visible) |
| Purpose | Structural integrity of a page | Logical data consistency across operations |
| Visibility | Invisible to queries/users | Visible — 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."
| Mutex | Latch | |
|---|---|---|
| Where used | General OS / application programming | Database engine internals specifically |
| What it protects | Any shared resource | In-memory DB structures (pages, buffer pool, B-tree nodes) |
| Duration | Varies — can be held long | Always very short |
| Deadlock handling | OS / runtime may detect | Usually not tracked — strict ordering rules prevent it |
| Blocking behaviour | Thread sleeps, context switch | Often 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.
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.
| Latch | Row lock | |
|---|---|---|
| Protects | Physical data structure (B-tree page, buffer frame) | Logical data (a row/tuple) |
| Duration | Microseconds — released when the operation completes | Entire transaction — seconds, minutes, longer |
| Held by | A single thread doing a page read/write/split | A transaction |
| Deadlock detection | No — too brief to deadlock | Yes — transactions can wait on each other |
| Released by | End of the physical operation | COMMIT 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 releasedA 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.