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.
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
- Watch
- Try it
- Predict
- Capture
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.
Highlighted lines are the ones running in the diagram right now.
def read_page(page_no):if page_no in cache:page = cache[page_no] # HIT: ~1 us, RAMtouch_lru(page_no) # mark as MRUreturn page# MISS: page is not residentif len(cache) >= cache_size:evict_lru(cache) # make roompage = disk_read(page_no) # ~10 ms, syscallcache[page_no] = pagetouch_lru(page_no)return page
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