The page cache — RAM is 1000x faster than disk

The pager keeps a fixed-size LRU cache of pages in RAM; you're fast iff the working set fits, slow the moment it doesn't.

Previously

Every B-tree descent we drew assumed each page touch hit the disk. In reality the pager keeps recent pages in RAM — and that one fact rewrites the cost model for everything we've built so far.

Scene 07

The page cache — RAM is 1000x faster than disk

  1. Watch
  2. Try it
  3. Predict
  4. Capture
PAGE CACHE — 8 slots, MRU ← leftslot 0emptyslot 1emptyslot 2emptyslot 3emptyslot 4emptyslot 5emptyslot 6emptyslot 7emptyDB FILE — 32 pages on disk1234567891011121314151617181920212223242526272829303132LATENCY—THROUGHPUT100 ops/sHIT RATE—WORKLOADB-tree descent (hot path)recent 0working set = 100 pages on disk · cache_size = 8 slots
What to watch for

We run the same 3-page B-tree descent twice. First run: cold cache → 3 misses → ~30 ms total. Second run: same path → 3 hits → ~3 µs total.

Continue unlocks when the animation finishes.
Implementation

Highlighted lines are the ones running in the diagram right now.

Pager.read_page(page_no)
the only routine the B-tree ever uses to touch a page
def read_page(page_no):
if page_no in cache:
page = cache[page_no] # HIT: ~1 us, RAM
touch_lru(page_no) # mark as MRU
return page
# MISS: page is not resident
if len(cache) >= cache_size:
evict_lru(cache) # make room
page = disk_read(page_no) # ~10 ms, syscall
cache[page_no] = page
touch_lru(page_no)
return page
evict_lru(cache)
drop the least-recently-used page to make room
def evict_lru(cache):
victim = pick_least_recently_used(cache)
del cache[victim.page_no]
return victim

Where this sits in Build a B-tree storage engine (SQLite-style)

Scene 07 of 11, in the Speed & durability act — Page cache, WAL+fsync, and the checkpoint that keeps WAL bounded.. The pager caches pages in RAM with LRU; you're fast iff the working set fits, slow the moment it doesn't.

Up next. RAM makes reads (and dirty writes) blazing fast. But cache is not durability — a crash wipes RAM. Next scene: WAL + fsync, the trick that turns cache writes into durable commits without rewriting the file every time.

All 11 scenes in Build a B-tree storage engine (SQLite-style) · Every curriculum

Built with Arqly
Every scene in Build a B-tree storage engine (SQLite-style) builds on the one before it.All 11 Build a B-tree storage engine (SQLite-style) scenes