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:
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:
Write path is excellent. Appending is the simplest write.
Read path breaks (2). Each lookup scans the whole file. Cost is O(n).
Overwrites break (4). The file grows forever. Old versions are never removed.
Figure 1: scan cost scaler. Drag records. Watch lookup work grow. Doubling records doubles lookup time, so point lookup breaks (2).
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:
Write: append key value to current segment. Update hash map to new offset. This covers insert. It covers update with the same path.
Read: check hash map. Seek once. If the page is in filesystem cache, no disk I/O happens.
Values may exceed RAM. Keys may not. All keys must fit in RAM. That breaks (2) when key count is very large.
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):
Break the log into segments of a certain size.
Run compaction. Compaction drops duplicate keys. It keeps only the most recent value per key.
Merge small compacted segments during the same background pass. Segments are never modified after writing. The merged result goes to a new file.
While merging runs, serve traffic from old files. Then atomically switch reads to the new merged segment. Delete old files.
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:
Delete: you cannot just remove bytes from a log. Append a special tombstone record. Merge discards prior values for that key. Without this, deletes break (4). Old values can resurrect.
Crash loses in-memory maps and breaks (1). Restart scans each segment file from start to end. Restart notes the last offset per key. Large segments make restart slow. Bitcask stores a snapshot of each hash map on disk for faster load. Bitcask may load a persisted hash-map snapshot if present to avoid full scan; otherwise restart must scan each segment start to end noting last offset per key.
Crash mid append breaks (1). Files include checksums. Corrupt tail records are detected. They are ignored.
Concurrent writers are risky with appends. Common choice is one writer thread. Segments are append only or immutable. Many threads can read them safely.
Production details that matter:
Do not use CSV in reality. Use binary format with length prefix then raw string. No escaping is needed.
Append only looks wasteful but wins for three reasons. Appends and merges are sequential writes. Sequential writes beat random writes on hard drives and SSDs. Because segments are never overwritten, readers keep using old files while a background thread writes the merged file, then reads atomically switch; no latch on readers and no torn splice of old and new bytes. Merging rewrites live keys from N input segments into one new sequential segment, so live keys that were scattered become contiguous; old files are then deleted.
Honest weakness: range queries such as keys from kitty00000 to kitty99999 need one lookup per key. That breaks (3).
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:
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.
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.
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
Read Seg 1 head: handbag. Read Seg 2 head: handcuffs.
Copy handbag first, then handcuffs, both in order.
Next pair handful versus handicap. Copy handicap, then handful.
If handiwork appeared in both inputs, keep the value from the most recent segment.
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:
On write, insert into the memtable. Append to the crash log at the same time.
The memtable is a Red-Black or AVL tree. Insert arrives in any order. Read back is in sorted order.
When the memtable exceeds a threshold, typically a few megabytes, flush it to disk as a new SSTable segment. Then empty the memtable. Discard the crash log for that memtable.
On read, check memtable first. Then check most recent segment. Then check older segments.
Background threads merge and compact segments. They drop overwritten or deleted values.
This breaks (1) if the machine crashes before flush. The memtable is lost.
Fix and its price:
Keep a separate unsorted log on disk. Append every write there immediately. Its only job is to rebuild the memtable after crash. Discard it after the memtable is flushed as SSTable.
Extra write cost buys durability. You pay one log append. You pay one later SSTable write.
Restart replays the crash log into a new memtable. Restart needs no tree replay. SSTables are already sorted and valid.
Missing key optimization:
Lookup for absent keys is slow. You may check memtable plus every segment to the oldest. Each level may need a disk read.
Present keys can stop early when found. Absent keys cannot stop early. They must be proven absent at every level.
LevelDB maintains Bloom filters. A Bloom filter is a memory efficient set approximation. It can tell you if a key does not appear in the database. It thus saves many unnecessary disk reads.
Illustrative only, not chapter detail: a Bloom filter may falsely claim presence. A false positive still causes a disk read. A true negative skips the read.
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:
Data stays sorted, so range scans are efficient.
Disk writes are sequential, so random write throughput can be remarkably high.
It works even when the dataset is much larger than memory.
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:
Like SSTables they keep pairs sorted. Point lookups work. Range queries work. Design philosophy is different.
Database is split into fixed size blocks or pages, traditionally 4 kB. Read or write one page at a time. This matches disk block layout.
Pages link by address, like on-disk pointers, to form a tree.
Live lookup from the chapter. Search for user_id = 251:
Start at root. Root holds k keys and k + 1 child references. Figure uses k = 5. Reality is often hundreds.
Keys mark range boundaries. For 251, follow the child for 200 to 300.
Repeat down one level. That level splits 200 to 300 into subranges.
Reach a leaf page. The leaf holds values inline. Or it holds references to value pages.
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:
To update, find the leaf and overwrite the value in the page. Page location does not change. References stay valid.
To insert, find the page covering the key range and add the key. If the page is full, split it into two half full pages. Update the parent with the new boundary. Splits can propagate upward.
Splits keep the tree balanced. When leaf P is full, allocate Q, move half keys to Q, overwrite parent to add boundary between P and Q; if parent is full, repeat upward. A tree with n keys has height O(log n). Even huge trees need few page hops.
Failure case that must be handled:
Overwrite is a real hardware action. On spinning disk it seeks and overwrites a sector. On SSD it is similarly slow and more complex.
One logical insert may overwrite several pages. Example is two split children plus the parent. Crash between page writes leaves a corrupted index. Example is an orphan page with no parent. That breaks (1).
Fix: add an append only write-ahead log, also called redo log. Write every modification there before touching tree pages. After crash, replay the log. Replay restores missing page writes. It restores the tree to a consistent state.
Price: every datum is written at least twice. Once to the log. Once to the page. Splits add more writes. LSM engines also rewrite data repeatedly during merges.
This repeated rewriting has a name. It is called write amplification. It matters for SSD wear. SSD blocks can be overwritten only a limited number of times before wearing out. The chapter says B-tree versus LSM on amplification depends on workload and tuning. There is no shortcut. Benchmark with your workload.
Concurrency needs care. Multiple threads need latches, meaning lightweight locks. Without them a thread may see a half updated tree. Log structured merging is simpler. Background work swaps old segments for new segments atomically.
Figure 8: crash and restart. Press Crash on each engine. Each replays a different log to meet (1).
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.
LSM crash log restores the memtable only. It is unsorted. It is discarded after each memtable flush to SSTable. SSTable then carries durability.
B-tree WAL restores tree pages to consistency. It records every page modification before the page write. It is kept until pages are safely persisted. Replay fixes torn splits and orphan pages.
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.
Hash segmented log: scan segments. Rebuild hash maps. Note last offset per key. Load disk snapshot if present to shorten scan.
LSM: keep SSTables as is. Replay unsorted crash log into memtable. Discard log after flush.
B-tree: keep pages as is. Replay WAL. Restore consistent tree. Apply missing page writes.
B-tree optimizations mentioned in the chapter:
Copy on write: used by LMDB. Write a modified page elsewhere instead of overwriting. Create new parent versions pointing to it. Helps crash recovery. Helps concurrency.
Key abbreviation: interior pages store only enough key bytes to mark boundaries. More keys per page means higher branching. Higher branching means fewer levels.
Sequential leaf layout: try to place nearby key ranges nearby on disk to speed scans. Hard to maintain under growth. LSM merging makes locality easier. Large ranges are rewritten together.
Sibling links: leaves point left and right. Ordered scans do not climb back to parents.
Fractal trees: borrow log structured ideas to cut seeks. The name is not about fractals.
Honest comparison from the chapter:
LSM engines usually sustain higher random write throughput. Random writes become sequential writes.
Rule of thumb: LSM is typically faster for writes. B-tree is thought faster for reads. Real benchmarks are often inconclusive. They are workload sensitive.
Compaction can stall live traffic. Disks have finite resources. Average latency may look fine. High percentiles can suffer. B-trees can be more predictable.
B-trees store each key in exactly one place. LSM may store several copies across segments. Single placement helps strong transactional semantics. Range locks can attach directly to tree pages. Multisegment copies would require checking many places for one logical lock. Details are deferred to Chapter 7.
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:
>> database is the whole storage engine write path. Append only gives speed. It gives simple crash behavior. It breaks (4). Old versions remain.
grep "^$1," is the full table scan. It proves why point lookup breaks (2) at scale.
tail -n 1 encodes last write wins. Compaction preserves this rule. SSTable merge preserves it. B-tree overwrite preserves it.
Missing pieces versus production: no segment split. No hash map. No tombstone. No checksum. No snapshot. No single writer guard. Each missing piece maps to a failure in Section 3.
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
Why not update a log file in place. In place overwrite turns a sequential pattern into random writes. It creates torn pages on crash. Torn means half old and half new data. Append plus merge keeps writes sequential. Recovery stays simpler.
When does a hash index fail. When keys exceed RAM. When you need ordered scans. When many segments force many map checks. That is the point to discuss SSTables and sparse indexes.
Why does an LSM need two writes. One append to the unsorted crash log for requirement (1). One later flush as sorted SSTable for requirements (2) and (3). Deleting the log early breaks (1). Keeping it forever breaks (4).
Why do absent keys cost more in LSM. You must check memtable then segments from newest to oldest before declaring absence. Present keys can stop at first hit. Bloom filters cut this cost. They prove absence with certainty. Illustrative only: they may falsely claim presence.
Why do B-trees write twice. Once to the write ahead log. Once to the page itself. Splits add more writes. LSM also rewrites during compaction. The repeated rewriting is called write amplification. It wears SSDs. Ask for a benchmark, not a slogan.
Latch versus lock. Latch guards tree structure for microseconds. Lock guards transactional key ranges for longer. B-tree in-place writes need latches. LSM reads need no latches on immutable segments.
Clustered versus heap. Clustered stores the row in the index. It saves a hop for reads. Heap stores one copy. It points from many secondary indexes to save duplication. Covering is the middle path for selected columns.
How to query two ranges at once, such as latitude and longitude in the restaurant query from the chapter. One dimensional B-tree gives one range. It filters the other. Real fix is a spatial index such as R-tree. Or a space filling curve mapping. Or a multidimensional store such as HyperDex.
Concatenated index limits. It answers leading field queries. It cannot answer second field alone. Phone book needs lastname first.
In-memory durability. Memory serves reads. Log plus snapshot plus replica gives durability. Anti-caching evicts cold records to disk.
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.