Indexes: B-trees and LSM trees
Read first: Choosing a database
A B-tree keeps keys in fixed-size pages with a high fanout, so a point read is a short walk and a range is a leaf scan. An LSM tree writes a log and a memtable, flushes immutable SSTables, and compacts them later. You trade write amplification, read amplification, and space amplification, and a bloom filter only lets you skip a file.
An index exists so a lookup does not read the table. The two shapes you should be able to redraw are the B-tree, which keeps keys in sorted pages and rewrites a page when a key changes, and the LSM tree, which turns a random update into a sequential append and pays the sorting debt later. Which one you want follows from the read and the write, the same test as Choosing a database.
Core concepts
Without an index, a query reads rows until it finds the ones it needs. That cost grows with the table. An index is another structure, ordered by the column the query actually has, that answers “where is this key” in a small number of page reads. The primary store is still the rows. The index is the way in.
B-tree pages and fanout
A B-tree, from Bayer and McCreight, is a balanced tree of fixed-size pages. A page holds many keys, not one. That count is the fanout. High fanout is the whole trick: the tree stays short, so a point read walks a handful of pages, and the internal pages are few enough to keep in memory.
The leaves hold the rows, or pointers to the rows, in key order. A range scan is then a walk along the leaves, which is sequential if the pages sit together. That is why a B-tree is the right shape for “category, then price from here to there” and for “this channel, newest page.” A point read and a range are the same structure.
An update rewrites the page. Change a price, and the leaf that holds that key is dirty. Change an indexed column, and every secondary index page that includes the column is dirty too. The write is random when the keys are random: the leaf you rewrite is wherever that key lives, not at the end of a log. A spinning disk pays a seek to get there. On the teaching list, a disk seek is 10 ms. Flash does not seek, and a random 4 KB read is the 2012 teaching number of 150 μs, or tens of microseconds on a current NVMe. The shape of the cost remains. You rewrote a page to change a row.
How tall is the tree? Tie the page to the number you already know, a 4 KB read, and label the rest as assumptions. Assume a page is 4 KB, 4,096 bytes, and a key plus a child pointer is 20 bytes.
fanout 4,096 / 20 = 204.8, about 200 if the page is full
200^2 40,000
200^3 8,000,000
200^4 1,600,000,000
Three levels address about 8 million keys. A billion keys wants a fourth level. If the internal pages are cached, the lookup pays one random leaf read: 150 μs on the old SSD number, or tens of microseconds on NVMe. If the cache is cold and the disk is spinning, four seeks are 4 times 10 ms, which is 40 ms. Height and cache are the whole latency story. A larger real page raises the fanout and shortens the tree. The argument does not change, and you should say you assumed 4 KB and 20 bytes.
LSM: memtable, log, SSTable, compaction
An LSM tree, from O’Neil and others, is the answer when the write is the problem. A random page rewrite per insert is a bad fit for a stream of new keys scattered across the key space. The LSM accepts the write in memory and on a sequential log, and it sorts in the background.
The path of a write:
- Append the change to a log on disk. This is the durability. If you ack before that append is durable, a crash loses the write. The log is sequential, so it does not pay a seek between records the way a random leaf does.
- Insert the key into the memtable, a sorted table in memory. A read can see the write here before anything is flushed.
- When the memtable is large enough, flush it to an SSTable, an immutable sorted file. The flush is a sequential write of already-sorted keys.
- Compaction merges SSTables into larger sorted files and drops overwritten values and deletions. Compaction is where the sorting debt is paid.
A point read checks the memtable and then the SSTables that might hold the key, newest first. It can touch several files. A range read is a merge of every run that overlaps the range, which is more work than walking one B-tree leaf chain. Write-heavy ingest fits an LSM better than an update-in-place B-tree. Read-heavy ranges fit the B-tree.
The Bigtable paper is this write path, and it is not a paper about filters. Chang and others describe a memory table and a log, a flush to an immutable SSTable on GFS, and compaction that rewrites files. Tablets split the table by row range. Bloom filters are the later, standard way an SSTable avoids a useless read. Do not put them at the center of the 2006 paper. Google Bigtable is the place for the rest of that system. The filter belongs in the next paragraph, as a read optimization on top of files that already exist.
Three amplifications
Write amplification is bytes written to disk divided by bytes the client sent. Read amplification is how much extra you read to return one value, often counted as files touched. Space amplification is bytes on disk divided by the logical bytes. Push one down and another goes up. There is no setting where all three fall.
A teaching model, every step an assumption except the arithmetic: a memtable flushes once, and compaction rewrites a byte once per level across 4 levels. The level count is an assumption, not a measured engine. Count the writes of one byte.
flush 1 write
compaction 1 write per level * 4 levels = 4
total 5
Write amplification is about 5 in this model. It is not a vendor benchmark. If you compact a level twice because you refuse to let files pile up, that level’s term doubles, and write amplification moves toward 6 or more. If you compact less, write amplification falls and the file count rises, so point reads look at more files and overwritten keys occupy space until the merge deletes them. That is the triangle, derived from how many times you rewrite, not from a datasheet.
Space amplification is easiest to see on an overwrite. The old SSTable still holds the old price, the new SSTable holds the new price, and both exist until compaction drops the old file. One unmerged overwrite of a key is about two copies, so space amplification is about 2 for those keys. An insert-only log does not keep an old version of the same key. It still pays write amplification to merge runs, and it still pays read amplification equal to the number of files a lookup has to consider.
Bloom filters skip files
A bloom filter sits on an SSTable and answers a cheap question: this key is definitely absent, or it might be present. Definitely absent means you skip the file. Might be present means you read it. A “maybe” can be wrong, so the filter does not turn a point read into a single I/O. It removes some of the misses.
It does nothing for a range. A range overlaps a file or it does not based on the file’s key span, and the merge still happens. It does nothing for a hot key. The hot key is present, the filter says maybe, and you read the file every time, on one partition. That is the Discord symptom: in an LSM, a read touches the memtable and possibly many files, so a hot channel made one node fall behind and dragged every other key on that node. The filter is not the cure, and it is not the heart of the Bigtable paper.
flowchart LR
client[Client]
wal[Commit log]
mem[Memtable]
sst[SSTable]
compact[Compaction]
client --> wal
client --> mem
mem --> sst
sst --> compact
The same ordered log shows up again when a replica has to catch up. Replication ships a log of committed changes. The commit log here is the local durability of one node. Do not confuse “the SSTable was flushed” with “a replica has this write.”
A worked example
Two workloads, one machine each, and you have to pick the structure. The large-product sketch uses the course scale: 100 million daily active users, 20 actions each, which is 2 billion actions a day. That is a teaching scale, not a company’s measured QPS. A day is 86,400 seconds. Divided by the shortcut of about 100,000 seconds, 2 billion is about 20,000 actions a second. The stricter division is on the page so the shortcut is visible.
The catalog is the other workload, and every figure in it is an assumption. 20 million products, a 1 KB row, 2,000 reads a second, 5 price updates a second. The query that matters is a price range inside one category.
actions/day 100,000,000 * 20 = 2,000,000,000
per second 2,000,000,000 / 86,400 = 23,148
shortcut 2,000,000,000 / 100,000 = 20,000
event size 100 bytes, an assumption
logical 23,148 * 100 = 2,314,800 bytes/s
per day 2,000,000,000 * 100 = 200 GB
write amp 5 2,314,800 * 5 = 11,574,000 bytes/s
per day 200 GB * 5 = 1,000 GB written
naive B-tree each insert rewrites a 4 KB page
23,148 * 4,096 = 94,814,208 bytes/s
ratio 4,096 / 100 = 40.96, about 41 times the logical bytes
The ratio 41 does not depend on the rate. It is the page size divided by the event size, under the assumption that every insert dirties a full page and that page is flushed alone. A buffer pool usually does better: many updates that land in the same leaf go out as one write. Random keys do not land in the same leaf. Sequential keys do. A log of independent entity ids is the random case, and the naive 41 is the direction of the pain even after the buffer pool helps. About 95 MB/s of random page writes, against about 2.3 MB/s of logical ingest, is why this log does not want an update-in-place B-tree.
The LSM at a write amplification of 5 writes about 12 MB/s, about 1,000 GB a day. You assumed four compaction levels plus the flush. Say that in the interview, and say the number moves if compaction runs twice per level. The read of one event by key checks the memtable and up to one file per level. A bloom filter that says no skips that file. A range such as “all actions for this account today” merges the runs that overlap the range. That merge is the cost you accepted.
Now the catalog. 20 million rows at 1 KB is 20 GB. Five updates a second rewrite a few leaves. Two thousand reads a second of a price range want leaf order: find the first key, then scan. A B-tree does that as a walk. An LSM does it as a merge across the memtable and every file that overlaps the range, and a price update sits in a new file until compaction, so the merge gets wider after a burst of edits and narrower when compaction catches up. The sawtooth is the fingerprint. Bloom filters do not stop it, because a range is not a point absence check.
If the 20 GB working set is cached, a catalog read is memory, and a main-memory reference is 100 ns. The B-tree still earns its place by the order of the leaves and by rewriting one page on a price change, not because every read hits a disk. If a leaf misses, one random 4 KB read is 150 μs on the 2012 number. Five misses would be 750 μs. You will not see that on a cached catalog. You will see it on the log’s point reads once files pile up.
Failure: compaction falls behind on the log. Assume the point read now considers 6 files, a pile-up past the 4-level model, and each file that says maybe costs a random 4 KB read at the 2012 teaching number.
6 * 150 μs = 900 μs
That 900 μs is an illustration of read amplification, not a benchmark, and NVMe at tens of microseconds a read makes 6 files a few hundred microseconds or less. The page you will answer is not “the drive is slow.” It is “one hot key touches many files on one node and the queue behind it grows.” Discord’s message store hit that shape: a hot channel, an LSM read of the memtable plus many files, one node behind, and latency for every other partition on that node. At the beginning of 2022 that cluster was 177 nodes. The node count is not the lesson. The read amplification on one hot partition is.
A second failure, on the other engine. Put the same 23,148 random inserts a second on a B-tree and fsync each dirty leaf. You are asking the disk for random writes at tens of megabytes a second of pages, for 2.3 MB/s of events. The write latency tracks the random I/O. The workload was sequential in time and random in key, and the B-tree only saw the random part. An append that always hits the rightmost leaf, one time-ordered log with a single key, is the case a B-tree handles well. Say which key distribution you have before you pick.
Tradeoffs
| Workload | Structure that fits | The bill you are agreeing to |
|---|---|---|
| Point reads and ranges, updates are rare | B-tree | A page rewrite on each update, random if the key is random |
| Insert-heavy log of scattered keys | LSM | Write amplification from compaction, read amplification from several files |
| Overwrites of the same keys in an LSM | Still an LSM if writes dominate | Space amplification until compaction drops the old file |
| Point read that must skip empty files | Bloom filter in front of each SSTable | A maybe still reads the file, ranges do not benefit, a hot key does not either |
| Compact more often to keep reads short | Fewer files, less space held | More write amplification, because you rewrote the level again |
| Compact less to save disk bandwidth | Lower write amplification | More files on a point read, and old versions occupying space |
The last two rows are one knob. You do not get to turn it in both directions. When someone says the LSM is “fast,” ask which of the three amplifications they measured, and at what file count.
Pitfalls
- Indexing the primary key you already look up by identity, and not the column in the WHERE clause. The symptom is a sequential scan on the query the product actually runs.
- Expecting an LSM range to walk like a B-tree leaf. The symptom is a “price between” query that slows down after a burst of updates and speeds up when compaction catches up.
- Treating a bloom filter as “one I/O per point read.” The symptom is several maybes, several file reads, and a range query that never consulted the filter at all.
- Putting bloom filters at the center of the 2006 Bigtable paper. The symptom, in the interview, is a story that skips the memtable, the log, the SSTable, and the tablet.
- Ignoring compaction on a write-heavy LSM. The symptom is disk filling with old versions, point reads touching more files, and a p99 that sawtooths. p99 means about 1 in 100 requests is slower than the number you quote.
- Sending random inserts through an update-in-place B-tree and calling the disk the bottleneck. The symptom is write latency tracking random page rewrites, on the order of a seek at 10 ms if the device is spinning, for a workload that was an append.
- Believing a filter fixes a hot key. The key is present, so every read opens the file. The symptom is one partition’s latency infecting the node, which is the Discord shape.
- Building a secondary index outside the write path. The symptom is a row you just updated that a read by the new value cannot find.
In the interview
Open with the workload, then the structure. “The catalog is a range inside a category, a few updates a second, so a B-tree. The walk is short because fanout is about 200 on a 4 KB page with a 20-byte separator, and a billion keys is four levels, with the leaf as the only I/O if the top is cached.” Then the log: “23,000 inserts a second of 100 bytes is about 2.3 MB/s logical. An LSM that rewrites a byte five times writes about 12 MB/s. A B-tree that rewrites a 4 KB page per insert is about 40 times the logical bytes if the buffer does not coalesce, and random keys stop it from coalescing.”
Skip bloom-filter math you did not derive. Skip a tour of storage engines. Say the filter skips a file that definitely does not hold the key, and that the 2006 paper’s write path is the log, the memtable, and the SSTable. If you cite Discord, cite the mechanism: many files on a hot partition, one node behind.
The question that usually follows is why the range got slow after a write burst. The answer is file count. Compaction had not merged the runs, so the range merge got wider, and a point-read filter would not have helped. The honest tradeoff is the one you pick next: compact harder and spend write amplification, or leave the files and spend the read.
Check yourself
A page is 4 KB and a separator is 20 bytes. What fanout do you get, and how many levels address a billion keys?
4,096 divided by 20 is about 200. 200 cubed is 8 million keys, so three levels are not enough for a billion. 200 to the fourth is 1.6 billion. Four levels. If the internal pages are cached, the lookup is one leaf read. The 4 KB and 20 byte figures are assumptions tied to the teaching page size, and you should say so.
The log takes 23,148 writes a second of 100 bytes, and your model writes each byte five times. What disk rate does that imply, and what did you count to get five?
Logical ingest is 23,148 times 100, about 2.3 MB/s, or 200 GB a day from 2 billion events. Five counts one flush plus one rewrite at each of four levels. Disk writes are about 12 MB/s, about 1 TB a day. Change the level count and the result changes. It is a derivation, not a measured engine.
A bloom filter says maybe for several SSTables on a point read. Why does that not fix a hot key, and why is it wrong to center the 2006 Bigtable paper on filters?
Maybe means you still read the file, and a hot key is present, so the filter never says no. The key’s traffic stays on one partition and the files stay on one node. The 2006 paper’s write path is the memtable, the log, and the flush to an SSTable, plus compaction. Filters are the later, standard way to skip a file that cannot hold a key.
A catalog does 2,000 range reads a second and 5 price updates a second. Which structure do you pick, and what does the other one make expensive?
Pick the B-tree. The query walks leaves in key order, and five page rewrites a second are noise. An LSM makes the range a merge across every run that overlaps it, and each price update adds a file until compaction. The sawtooth after a burst of edits is that merge getting wider. A bloom filter does not apply to the range.
Based on: Designing Data-Intensive Applications, Kleppmann and Riccomini; O'Neil and others; Bayer and McCreight; Bigtable, Chang and others; Discord message store.