Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Topic 6 — Buffer Pool & Memory Management

Who decides which pages live in RAM? Four answers: postgres (CLOCK over a shared array), DuckDB (approximate-LRU queue with lazy purging), LeanStore (pointer swizzling — no mapping table at all on the hot path), and mmap (let the kernel decide — the CIDR ’22 paper on why that’s usually wrong). And one question under all of them — who pays for page_id → frame — with three answers on the hot path: delete the table (swizzling, vmcache), or keep it and hide its latency behind the page read (predictive translation). Plus redis’s answer to a different question: not page caching but allocator accounting (zmalloc + jemalloc + active defrag).

The problem, measured (bench lane 1, provided — runs today)

cargo run --release --bin pool_vs_mmap — 1 GiB file, 2 M Zipf(0.99) page reads, 8 bytes touched per page so the access dominates the copy:

mmap    p50 42 ns    p99 1500 ns    p99.9 4459 ns    max 181887 ns

42 nanoseconds at the median, 182 microseconds at the max — a 4300× spread, and all of it lives in the tail. The median is a hit on a page the kernel already had resident, which is essentially free and exactly why mmap is so tempting for a storage engine. The p99.9 and the max are minor page faults: a trap, a read, a TLB shootdown — and, crucially, an event the database cannot see, schedule around, or prefetch ahead of.

That asymmetry is the entire argument of “Are You Sure You Want to Use MMAP in Your DBMS?”, and it is why every serious engine reimplements paging it could have had for free. Note the handicap when you compare your own pool to this row: mmap gets the whole machine’s page cache here, while your pool will be held to 256 MiB against a 1 GiB file. If your pool still wins the tail under that disadvantage, the result is conclusive.

A second provided lane isolates the other half of the translation question, cargo run --release --bin translation_micro — one page access through a direct pointer, through a hash lookup, and through a hash lookup with the page read issued at a guessed frame beside it (predictive translation, §3), over a dependent chain of accesses (each page names the next), M3 Pro, ns per access:

 miss%  workload       direct      hash     predictive
     0  chained          86.9     183.3         99.6
    10  chained           -       181.5        107.0
    50  chained           -       182.7        160.9

A hash lookup in front of a dependent page read doubles the cost — two DRAM misses in series instead of one — and reading the guessed frame beside the lookup gets it back to within 15% of no translation at all, as long as the guess is right. At 50% wrong guesses most of the saving is gone. Two runs, ratios stable; full table in notes.md.

A further provided lane — the unit of caching (cargo run --release --bin heat_scatter_model, provided, deterministic, ~3 s). Every pool above caches whole pages. Bf-Tree caches the hot records of a page; whether that wins depends on whether the heat is scattered across pages. Under the paper’s workload (Zipf 0.9, 200 M records of 32 B, a 2 GiB cache) an oracle page cache reaches a 0.566 hit ratio when popular keys are scattered and 0.812 when they are adjacent, and an oracle record cache 0.73–0.85 (reading-bftree.md, Step 8). Under the same pmf, 80% of requests reach the top 15.1% of records, not the 33% the paper’s §6.1 parenthetical says.

Outcomes

By the end you can:

  1. Walk a page request through hash-lookup → pin → CLOCK victim search and say where every atomic and lock is.
  2. Explain why mmap loses to a buffer pool (TLB shootdowns, no write ordering, page-fault stalls you can’t schedule around) and when it’s fine.
  3. Explain pointer swizzling and the cooling stage — how LeanStore makes an in-memory hit cost ~0 extra instructions — and the alternative that keeps the hash table: predictive translation, which reads a guessed frame beside the lookup.
  4. Build a CLOCK buffer pool for your topic-3 B+tree and beat mmap on a larger-than-RAM workload (or measure exactly why you don’t).

1. The translation problem

Every buffer pool is a map page_id → frame, and every design is a stance on who pays for the translation:

                     lookup cost per hot-page hit
 hash table (postgres, DuckDB)     ~1 hash probe + partition lock/atomics
 swizzling  (LeanStore)            0 — the parent's pointer IS the frame ptr
 page table (mmap/OS)              0-ish until a TLB miss / minor fault
                                   ... then the kernel takes over your latency
 hash table + predicted frame      the probe still happens, but the page read is
 (predictive translation, 2026)    issued at a guessed frame in parallel: the
                                   probe's latency hides behind the read
flowchart LR
    A["request page P"] --> B{"in pool?"}
    B -- "hit" --> C["pin (CAS refcount++)<br/>usage_count↑"]
    B -- "miss" --> D["find victim:<br/>CLOCK sweep"]
    D --> E{"victim dirty?"}
    E -- "yes" --> F["write it out FIRST<br/>(WAL rule: log already flushed)"]
    E -- "no" --> G["evict, relabel frame,<br/>read P from disk"]
    F --> G
    G --> C

The “write it out FIRST” box is synchronous I/O on the miss path, and it is where submission cost hides. High-Performance DBMSs with io_uring: When and How to Use It (Matthias Jasny, Muhammad El-Hindi, Tobias Ziegler, Viktor Leis, Carsten Binnig; VLDB 2026, PVLDB 19; arXiv:2512.04859 · code) measures it in a buffer manager: collecting several eviction victims and submitting their writes with one io_uring_enter() call — still synchronous, no read/write overlap yet — improved throughput by about 14%, to 19 k tx/s (§3.3.1, Fig. 5), because the per-eviction submission cost is amortized across the batch. Topic 45 covers the rest of that paper.

2. Eviction: three shapes of approximate-LRU

  • postgres CLOCK — one nextVictimBuffer atomic ticks around a fixed array; each buffer has a 4-bit usage_count (max 5). Sweep decrements; a buffer survives up to 5 laps. Pinned buffers are skipped. No linked lists, no per-hit list surgery — a hit is just a saturating increment.
  • DuckDB eviction queue — unpinning enqueues (weak_ptr, seq_num) into a concurrent FIFO. Re-pinning doesn’t remove the entry (too expensive); it bumps the handle’s sequence number so the stale entry becomes a dead node, purged in bulk every 4096 insertions. Approximate LRU where the cleanup is amortized, not per-op — same move as topic 2’s incremental rehash.
  • LeanStore cooling stage — no global order at all: random buffer frames get unswizzled into a cooling FIFO (~10% of pool). A cool page touched again is re-swizzled cheaply (second chance); reach the FIFO’s end and you’re evicted. Randomness replaces bookkeeping.

All three approximate recency, and recency is exactly what concurrent analytical scans make useless: every scan touches every page once, so usage counts say nothing about which page is needed next. Sampling-based Predictive Database Buffer Management (Mohammad Khalaji, Theo Vanderkooy, Runsheng Benson Guo, Khuzaima Daudjee; PVLDB 18(13), 2025; paper · code) uses the progress of the running scans to estimate when each page will next be accessed — approximating the optimal policy, which would need to know future accesses — and keeps eviction cheap by scoring only a small random sample of buffers per eviction (Abstract). Implemented in PostgreSQL, with 32 query streams each scanning 10% of a table, it reduced I/O volume by 30% to 40% relative to both Clock-sweep and the earlier priority-queue predictive policy at a 12 GiB cache (§6.2.1, Fig. 6); the gap closes as the cache grows. It is postgres’s CLOCK (reading-postgres-bufmgr.md) with the victim chosen by forecast instead of by recency, and the random sample plays the role random cooling plays in LeanStore — it replaces global bookkeeping.

3. Pointer swizzling (LeanStore) in one diagram

 swip = one u64 in the PARENT node          (bit 63: evicted, bit 62: cool)
 ┌─────────────────────────────────────────────────────────┐
 │ HOT      00…pointer…   direct BufferFrame* — deref it   │
 │ COOL     01…pointer…   frame in cooling FIFO — CAS back │
 │                        to HOT, done (no I/O, no map)    │
 │ EVICTED  10…page id…   page fault: alloc frame, read,   │
 │                        swizzle pointer                  │
 └─────────────────────────────────────────────────────────┘

Consequence: a page can only be referenced by ONE parent (else two swips to re-swizzle). That is fine for a B-tree’s parent→child edges and awkward for anything with a second referent: sibling pointers between leaves, or a graph’s tiles reached by both a row index and a column index. The SIGMOD ’26 paper that this topic’s last reading guide covers states it as a design-goal failure — swizzling “restricts each page to a single reference”, and evicting a page means latching both the page and its parent (§1, §2.1). Two alternatives remove the restriction by keeping the page id as the reference: LIPAH stores a fat pointer (page id plus a hinted frame address, falling back to a hash lookup when the hint is stale) but caps the database at 2³² pages — 17.6 TB at 4 KiB — and predictive translation keeps a plain hash table and hides it (below). For the capstone, matrix tiles referenced from both a row and a column index form a DAG, not a tree, so swizzling is the design to rule out first.

The hash table fights back: predictive translation

A hit in a classic hash-table pool is a chain of dependent loads — bucket, then control block, then frame — and a chain of misses cannot overlap. Predictive translation (Zinsmeister, Nguyen, Leis, Neumann, SIGMOD ’26) gives each page id a preferred frame computed from the id alone and issues the page read there speculatively, in parallel with the hash lookup; the lookup then only confirms the guess. Hot pages are moved into their preferred frames by probabilistic promotion (1/32 per access if no page is displaced, 1/512 if one is), so the guess is right where the accesses are. Measured in the paper, on a 192-thread EPYC: +34% over vmcache and +19% over LeanStore on in-memory TPC-C (§6.1), and +20.6% single-threaded from the predictive placement alone in the ablation (§6.4). The micro-lane translation_micro in experiments/ tests the overlap argument by itself — numbers in notes.md — and reading-predictive-translation.md builds the idea from the dependent-load chain up.

4. Why mmap is (usually) wrong — the CIDR ’22 checklist

  1. No write ordering — the kernel flushes dirty pages whenever; WAL’s “log before page” needs msync gymnastics or is simply unenforceable.
  2. TLB shootdowns — evicting a page means IPIs to every core that might cache the mapping; scales worse with more cores.
  3. Page-fault stalls — a fault blocks the thread; no async I/O, no admission control, no prefetch you control.
  4. Error handling — I/O errors arrive as SIGBUS mid-instruction.

But: LMDB (topic 3) ships on mmap happily — read-mostly, single-writer, COW keeps ordering trivial. The paper’s “usually” is doing real work. vmcache (SIGMOD ’23) is the first synthesis: virtual memory assisted — mmap the address space, but the DB keeps explicit control of residency and eviction. Its bill is a kernel module for good performance and one frame header per storage page (about 480 GB of headers for a 30 TB SSD, by the SIGMOD ’26 paper’s arithmetic, §2.1). Predictive translation (§3) is the second: pay neither, keep the hash table.

5. redis: the other memory management

No pages — redis manages allocations. zmalloc wraps jemalloc with cache-line-aligned used_memory counters — a private slot for each of the first eight threads, eight shared slots for the rest — that are the maxmemory enforcement input, and active defrag literally re-allocates values whose jemalloc bins are underutilized and updates every pointer. FalkorDB’s matrices live inside this world: GraphBLAS blocks are zmalloc’d, counted against maxmemory, and opaque to redis defrag.

6. Code reading (5–7 h)

  • postgres bufmgr.c + freelist.c — packed atomic state, CLOCK, buffer rings. → reading-postgres-bufmgr.md — postgres bufmgr: a buffer’s life in one atomic word
  • DuckDB buffer manager — eviction queue with dead nodes, memory reservations, spill-to-temp. → reading-duckdb-buffer.md — DuckDB’s buffer pool: eviction by queue of hints
  • LeanStore — swips, cooling stage, hybrid latches. → reading-leanstore.md — LeanStore in code: swips, cooling, hybrid latches
  • redis zmalloc.c (+ turso’s CLOCK page cache as a bonus). → reading-redis-zmalloc.md — zmalloc: memory management when there are no pages

7. Papers (4–6 h)

  • “Are You Sure You Want to Use MMAP in Your DBMS?” (CIDR ’22). → reading-mmap-paper.md — mmap is not a buffer pool
  • “LeanStore: In-Memory Data Management Beyond Main Memory” (ICDE ’18) + vmcache (SIGMOD ’23) as the sequel. → reading-leanstore-paper.md — LeanStore & vmcache: pay only on the miss
  • “Predictive Translation: High-Performance Buffer Management Without the Trade-Offs” (SIGMOD ’26) — the hash table fights back. → reading-predictive-translation.md — Predictive translation: hide the lookup instead of deleting it
  • “Bf-Tree: A Modern Read-Write-Optimized Concurrent Larger-Than-Memory Range Index” (PVLDB 2024) — a pool whose frames are the hot records of a leaf (mini-pages in a circular buffer), with the paper’s numbers checked against its text and microsoft/bf-tree source. → reading-bftree.md — Bf-Tree: a buffer pool whose frames are the hot records

8. Experiments (in experiments/)

  1. src/buffer_pool.rs — CLOCK buffer pool: fixed frame array, page_id → frame map, pin/unpin with usage counts, dirty-page write-back on eviction. Tests fix the contract (pinned pages never evicted, dirty pages written before reuse, capacity respected).
  2. src/bin/pool_vs_mmap.rs — same random-read workload over a file 4× larger than the pool/RAM budget: your pool vs mmap. HdrHistogram — compare p50 AND p99.9 (the mmap story is in the tail).
  3. src/bin/translation_micro.rs (provided, runs today) — direct pointer vs hash lookup vs predicted-frame read, independent and dependent (chained) access, at 0/10/50% of pages away from their preferred frame. Measures the overlap claim of §3 in isolation; numbers in notes.md.
  4. benches/eviction.rs — CLOCK vs strict-LRU (linked list) vs FIFO on Zipf-skewed access: hit rate AND ns/lookup. Shows why nobody ships strict LRU (per-hit list surgery costs more than the hit-rate gain).
  5. src/bin/heat_scatter_model.rs (provided, deterministic, no timing) — oracle hit-ratio bounds for record caches versus page caches under a Zipf workload: when does caching records instead of pages pay, and what does it need from where the heat sits? Change the skew and re-run.

9. Capstone milestone M6 (in ../../capstone/)

  • Buffer pool under the persistent backends — graphs larger than RAM.
  • Decide: per-backend pools or one shared pool with MemoryTag-style accounting (DuckDB)? Write the tradeoff down.
  • Reproduce mmap write-back unpredictability once, on your Mac, with numbers in notes.

Done when

Your pool beats mmap at p99.9 on the larger-than-RAM benchmark (or you can explain the exact kernel behavior that prevented it); the eviction bench table is in notes.md; you can explain a swip and a dead node from memory.