All lessonsDay 17B-Building blocks2026-10-15

Storage and Retrieval: How Databases Find Data Again

A video site stores a play count per cat video URL. The count for purr is updated thousands of times per day. Appends are fast. Finding the current count for one URL by scanning a growing file gets slower every day. This lesson explains how storage engines fix that scan without losing writes.

O(n)Naive lookup cost. Doubling records doubles lookup time.
1 seekHash index read: one disk seek if value is on disk. Zero I/O if block is in filesystem cache.
few MBSegment flush threshold: typically a few megabytes for the in-memory sorted tree.
1 / few KBSparse index density: one key for every few kilobytes of segment file.
4 kBB-tree page size: traditionally 4 kB. Height is O(log n).
k = 5B-tree branching example: k = 5 in the figure. Hundreds in reality.

Key points

  • An index is side metadata that points to data. It speeds reads. It slows writes.
  • Sorted files allow sparse indexes. They allow block compression. They allow range scans.
  • Sequential writes win on both hard drives and SSDs.
  • No engine wins everywhere. Benchmark with your workload.
O1Derive the read path for hash, LSM, and B-tree stores from a key.
O2Break down what is lost or corrupted on crash at each stage.
O3Argue for Bitcask style versus LSM versus B-tree for a given read write pattern.
O4Predict why a range query or delete needs special handling in each engine.
Requirements for this lesson
  • (1)Data must survive crash and restart.
  • (2)Point lookup by key must stay fast as data grows.
  • (3)Range scan in key order must be possible.
  • (4)Disk use must stay bounded under repeated overwrites.

Note on requirements. Items (1) to (4) below are a pedagogical scaffold for this lesson. They are not terms from the chapter.

02

Problem: append is fast, find is slow


The chapter starts with the simplest store in Bash:

Show code
#!/bin/bash
db_set () {
    echo "$1,$2" >> database
}
db_get () {
    grep "^$1," database | sed -e "s/^$1,//" | tail -n 1
}
Show code
db_set 123456 '{"name":"London","attractions":["Big Ben","London Eye"]}'
db_set 42 '{"name":"San Francisco","attractions":["Golden Gate Bridge"]}'
db_get 42

Every db_set appends one line. Old values stay in the file. db_get takes the last match with tail -n 1.

This gives a log in the book sense. A log is an append only sequence of records. It need not be human readable.

Why this matters:

Figure 1: scan cost scaler. Drag records. Watch lookup work grow. Doubling records doubles lookup time, so point lookup breaks (2).

5000
Lookup cost
O(n)

5000 lines scanned per lookup

Append cost
O(1)

one append stays cheap

File growth
unbounded

old versions never removed, breaks (4)

try doubling twice
Operable check: append stays O(1) while scan work scales with n. That gap is why an index is needed.
Mental model: index as signpost

Keep primary data in one place. Keep extra metadata on the side. That metadata tells you where to jump. One query pattern may need one signpost. A different pattern may need another. Adding a signpost helps reads. It taxes writes. Both data and signpost must be updated.

03

Mechanism A: hash index with segmented log


Keep an in-memory hash map from key to byte offset. The log stays on disk as before.

Example layout from the chapter. Keys 123456 and 42 map to offsets 0 and 64. To read 42, look up 64 in the map. Seek to 64. Read the value.

This is essentially Bitcask. It is the default engine in Riak.

Live steps:

Figure 2: one seek lookup. Select a key. The map gives the byte offset, then the reader seeks once. Toggle cache to see zero I/O.

In memory hash map
123456 -> 0London
42 -> 64San Francisco
Log on disk
off 0 | 123456, London ...
off 64 | 42, San Francisco ...

Pick a key to trace the read path.

Hash read is O(1) map plus at most one seek. Keys must fit in RAM, values need not.

Why not keep the hash map on disk when RAM is full. The chapter gives three reasons. An on-disk hash map needs much random access I/O. It is expensive to grow when it becomes full. Collision handling needs fiddly logic. That is why the chapter moves to sorted structures and B-trees instead.

Fix for unbounded growth, which addresses (4):

Cat video example from the figures. Input has mew: 1078, purr: 2103, purr: 2104, mew: 1079, and so on. After compaction only the latest per key remains. Example survivors are mew: 1082 and purr: 2108.

Figure 3: compaction before and after. Flip the view. Before keeps every overwrite. After keeps only the latest per key.

Same last write wins rule, bounded disk. Each segment keeps its own hash table, newest segment checked first.

Each segment gets its own hash table. Lookup checks the most recent segment first. Then it checks older segments. Merging keeps segment count small. Few maps are checked.

Failure cases and fixes:

Production details that matter:

Best fit: values updated often with few distinct keys. The chapter example is URL to play count. It has many writes per key.

04

Mechanism B: sorted segments and LSM-tree


Change one rule. Require segment contents sorted by key. Call the result a Sorted String Table or SSTable. Require one copy of each key per merged segment.

Lineage note from the chapter. Bigtable introduced the terms SSTable and memtable. Patrick O'Neil et al described the structure as Log-Structured Merge-Tree. LevelDB and RocksDB implement it. LevelDB can be used in Riak as an alternative to Bitcask.

Three payoffs:

  1. Merge stays cheap even when files exceed RAM. Read input segments side by side. Copy the lowest key to output. Repeat. This is the mergesort pattern. If the same key appears in several inputs, keep the value from the most recent segment. Adjacent segments are merged. Recency is well defined.
  2. You no longer index every key. Sorting lets you bound the search. The chapter example searches for handiwork between known sparse keys handbag and handsome. Jump to handbag. Scan forward a few kilobytes. Stop if you pass the target range. Sparse means one index entry per few kilobytes is enough.
  3. Group nearby pairs into a block and compress it. Each sparse entry points to a compressed block start. This trades extra CPU for less disk I/O. The chapter notes disk bandwidth is usually the worse bottleneck.

Figure 4: sorted merge trace. Press Next or Play. This is the lesson stepper. One concrete word list merges end to end.

Seg 1handbag, handful
Seg 2handcuffs, handicap
Comparelowest key wins
Outputsorted, latest kept
  1. Read Seg 1 head: handbag. Read Seg 2 head: handcuffs.
  2. Copy handbag first, then handcuffs, both in order.
  3. Next pair handful versus handicap. Copy handicap, then handful.
  4. If handiwork appeared in both inputs, keep the value from the most recent segment.
  5. Output is sorted: handbag, handcuffs, handicap, handful, handiwork. One copy per key.
Sorted word example from the figures. Inputs contain handbag, handcuffs, handful, handicap, handiwork, and others. Merge output is sorted. It keeps only the latest value per key.

Fresh reader question: how do you find a key that was never indexed. You jump to the largest indexed key below the target. You scan forward only within that small block. You stop at the target or at a larger key. You never scan the whole file. Absence is proven by passing the target range.

Fresh reader question: why does sorting enable compression. Sorted keys place similar keys in the same block. Similar adjacent keys compress well together. Writer groups a few-KB range into one block, compresses block, sparse entry points to block start; reader decompresses block after seek. Hash segments store writes in arrival order. Arrival order mixes unrelated keys. Mixed keys compress poorly. Mixed order also prevents bounded scans.

Figure 5: sparse probe. Type a word, then Find. You jump to the sparse key below it and scan only one block.

Try handiwork, handful, or zebra.

Sparse means one index entry per few kilobytes is enough. Stop when you pass the target range.

Problem: incoming writes arrive in any order. Sorting on disk per write would be costly.

Fix with memtable. The three structures differ as follows. Memtable is sorted. It lives in memory in a balanced tree. It is lost on crash. Crash log is unsorted. It lives on disk as append only. It survives crash. SSTable is sorted. It lives on disk as a segment. It survives crash.

Live steps:

This breaks (1) if the machine crashes before flush. The memtable is lost.

Fix and its price:

Missing key optimization:

Figure 6: absent key cost. Toggle Bloom, then test a present key versus an absent key. Absent keys must be proven absent at every level.

Pick a test to count disk reads.

Present keys stop at first hit. Absent keys check memtable plus every segment without Bloom.

Why this design wins:

Field note: same idea powers full text search

In Lucene, the key is a term word. The value is the list of document IDs containing it. That list is called a postings list. Lucene keeps term to postings mappings in SSTable like sorted files. It merges them in the background.

05

Mechanism C: B-tree with update in place


Log structured engines append and merge. B-trees overwrite fixed pages.

Lineage note from the chapter. B-trees were introduced in 1970. They were called ubiquitous less than 10 years later. B-tree implementations are generally more mature than LSM implementations. They remain standard in almost all relational databases.

Core facts:

Live lookup from the chapter. Search for user_id = 251:

Figure 7: descend and split. Press Find 251 to walk root to leaf. Press Insert to fill leaf P, split into P and Q, and push a boundary upward.

Root
0-100100-200200-300300-400400-500
Branch 200-300
200-240240-260260-300
Leaf P: 240-260 [3/4 full]
241251255

Tree height is O(log n). Even huge trees need few page hops.

Follow one key end to end: 251 stays in 200 to 300, then 240 to 260, then leaf P.

Live write:

Failure case that must be handled:

Figure 8: crash and restart. Press Crash on each engine. Each replays a different log to meet (1).

Hash segmented log
Running. Maps in RAM, segments on disk.
LSM
Running. Memtable in RAM, SSTables valid.
B-tree
Running. Pages on disk, WAL ahead.

Restart rule: hash scans segments, LSM replays crash log into memtable, B-tree replays WAL onto pages.

Fresh reader detail: what exactly happens on restart in each engine is shown above.

Fresh reader question: what is the difference between the LSM crash log and the B-tree WAL. Both are append only logs. Purposes differ. Lifecycles differ.

Fresh reader question: what is a latch versus a lock. A latch is a short lightweight guard on tree structure. It is held only during a page read or write. A lock is a longer transactional guard on key ranges. B-trees need latches because threads overwrite shared pages in place. LSM merging avoids latches on reads because segments are immutable. LSM swaps old segments for new segments atomically.

Fresh reader question: what exactly happens on restart in each engine.

B-tree optimizations mentioned in the chapter:

Honest comparison from the chapter:

06

Code: runnable append log plus notes


Reuse the Bash store from Section 2. Do not duplicate it here. Run the same db_set and db_get sequence. Inspect database with cat.

Lines that matter:

Illustrative hash sketch. Labeled illustrative only. It uses simplified CSV for teaching. It contradicts the production binary rule from Section 3. Production should use length prefix plus raw string.

Show code
# Illustrative only, not chapter code.
# Simplified CSV demo. Do not use in production.
offsets = {}  # key -> byte offset, must fit in RAM
def db_set_log(f, key, value):
    off = f.tell()
    f.write(f"{key},{value}\n")
    offsets[key] = off  # breaks (2) if keys exceed RAM
07

Field guide: three worked cases plus extensions


Case 1: heap versus clustered versus covering. Mechanism: heap stores the row once in a heap file in no order. Each secondary index holds a pointer to the heap location. Clustered stores the row inside the primary index. InnoDB uses primary key as clustered index. Covering stores selected columns inside the index. It is called index with included columns. Break example: update grows the value beyond free space. Heap must move the row. Then it must update all pointers or leave a forwarding pointer. Clustered and covering speed reads by saving the heap hop. They cost extra storage. They cost extra write work.

Case 2: restaurant finder with two ranges. Mechanism: query asks for latitude > 51.4946 AND latitude < 51.5079 AND longitude > -0.1162 AND longitude < -0.1004. A standard B-tree or LSM gives one range efficiently. It filters the other range by scanning. Break example: B-tree on latitude returns all venues in the latitude strip at any longitude. Then it discards most rows by longitude. Chapter fixes: map 2D to 1D with a space filling curve then use a B-tree. Or use a specialized R-tree via PostGIS. Or use a multidimensional store such as HyperDex for date plus temperature or color dimensions.

Figure 9: two ranges at once. Switch the plan. A plain B-tree on latitude scans the whole strip and discards most rows. A spatial plan hits only the box.

Rows scanned
40
Rows returned
6
Waste
34 discarded
Operable check: one dimensional index gives one range, then filters the other by scanning.

Case 3: secondary index and full text index from the same key value idea. Mechanism: a secondary index handles non unique keys. Build it as a list of row IDs per key. Or append row ID to key to keep keys unique. Both B-trees and log structured engines work. Lucene applies the same pattern to search. Term maps to postings list in SSTable like files. Break example: exact B-tree lookup cannot handle misspellings. Chapter fix: Lucene keeps an in-memory automaton over terms. It supports edit distance search. It also merges sorted term files in the background.

Extension A: concatenated index phone book rule. Mechanism: a concatenated index combines several fields into one key. Field order is fixed in the definition. Example is paper phone book from (lastname, firstname) to phone number. It can answer lastname alone. It can answer lastname plus firstname. It cannot answer firstname alone. Sort order groups by first field only. Second field search would need a scan.

Extension B: keeping everything in memory. Mechanism: an in-memory database serves reads entirely from memory. Disk is used only as append only log for durability. Durability comes from four options in the chapter. Options are battery powered RAM. Log of changes to disk. Periodic snapshots to disk. Replication to other machines. Restart reloads state from disk or from a replica. Vendors include VoltDB and MemSQL and Oracle TimesTen for relational use. RAMCloud is open source key value with log structured memory and disk. Redis and Couchbase write to disk asynchronously and give weak durability. Fresh reader question: where does durability come from if all data is in RAM. Answer: it comes from the log plus snapshots plus replicas. Memory gives speed by avoiding on-disk encoding overhead. Disk caching alone does not give the same gain. Recent anti-caching research evicts least recently used records to disk. It loads them back on access. It still requires indexes to fit in memory. It manages records not memory pages.

08

Interview ears


09

Judgment quiz


Q1Predict: a Bitcask style node loses power after many cat-video increments (illustrative number, not from chapter) but before any snapshot. What must happen on restart to meet (1)?

Answer: rebuild each segment map by scanning from start to end. Keep the last offset per key. Restarts are slow on large segments. Snapshots shorten this. The slow restart is an availability and recovery cost. It is not steady state O(n) lookup.

Q2Predict: a workload looks up keys that almost never exist. Which engine suffers extra disk reads without Bloom filters, and why?

Answer: LSM. Absence is proven only after checking memtable plus segments back to the oldest. A Bloom filter proves absence without disk reads. Illustrative only: it may falsely claim presence.

Q3Compare: mostly random writes (illustrative workload, not from chapter) plus ordered scans over handbag to handsome style ranges. Argue LSM versus B-tree.

Answer: LSM turns random writes sequential. It scans sorted segments well. Watch compaction stalls at high percentiles. B-tree may be more predictable for reads. It offers single copy range locks.

Q4Compare: table with five secondary indexes (illustrative number, not from chapter) and frequent large value updates. Argue heap plus secondary pointers versus clustered duplication.

Answer: heap avoids five copies (illustrative number, not from chapter). It pays a hop. It pays costly moves or forwarding pointers when values grow. Clustered or covering speeds reads. It adds storage and write work.

Q5Choose under tradeoff: keys fit in RAM, values are updated constantly, no range queries needed. Choose hash segmented log or B-tree and defend with (2), (3), and (4).

Answer: hash segmented log. One seek reads. Appends absorb writes. Compaction bounds disk. Accept loss of (3). B-tree would pay random overwrites and WAL doubles without range benefit.

Q6Choose under tradeoff: restaurant finder must enforce latitude > 51.4946 AND latitude < 51.5079 AND longitude > -0.1162 AND longitude < -0.1004. A plain B-tree on latitude is proposed. Break down the failure and name the chapter fix.

Answer: it returns all venues in the latitude strip at any longitude, then filters. Or vice versa. Fix with R-tree via PostGIS. Or space filling curve to one B-tree key. Or multidimensional index.

Sources

Designing Data-Intensive Applications, Chapter 3: Storage and Retrieval. Bitcask default engine in Riak, LevelDB and RocksDB LSM implementations, Bigtable SSTable and memtable terms, Patrick O'Neil et al Log-Structured Merge-Tree, LMDB copy on write, PostGIS R-tree, HyperDex, Lucene postings lists, VoltDB, MemSQL, Oracle TimesTen, RAMCloud, Redis, Couchbase.