Sub topic 1
Why LSM Trees Exist: B-trees, Random Writes, and Sequential I/O
Prerequisites
This chapter assumes you know basic data structures (hash maps, sorted arrays, binary search). It also assumes you know the difference between memory and disk, and between sequential and random I/O. You should be able to read short Python programs.
The problem: updating data in place
A B-tree keeps keys sorted in fixed-size pages on disk. To change one key, the engine finds the page that holds it, reads that page, edits it, and writes it back to the same location. This is called update in place.
Reads are cheap. A lookup follows a few pages from the root to a leaf, so it costs a handful of disk reads. Writes are the weak point. Each insert touches a page chosen by the key, not by the time of arrival. Random keys therefore cause random writes scattered across the disk. A page split, which happens when a page overflows, can touch several pages at once.
Why random writes are costly
Disks reward sequential access. A hard disk must move its head for each random write. An SSD has no head, but it still writes in large units and erases whole blocks, so small scattered writes cause extra internal work and wear. Appending to the end of a file avoids both costs.
| Access pattern | Hard disk | SSD |
|---|---|---|
| Sequential write | Fast, no head movement | Fast, fits large write units |
| Random write | Slow, one seek per write | Slower, extra internal rewriting |
The LSM idea
A log-structured merge tree (LSM tree) never updates data in place. It does this instead:
- Buffer recent writes in memory, sorted by key.
- When the buffer is full, write it to disk as one new sorted file, in a single sequential pass.
- Never edit that file again. Newer versions of a key go into newer files.
- Merge files in the background to remove stale data.
Many small random writes become a few large sequential ones.
What you pay for it
The speed comes with costs, and the rest of this tutorial covers them.
- Reads get harder. A key may sit in memory or in any of several files, so a lookup may check more than one place.
- Data is rewritten. Background merging writes the same data more than once.
- Space is wasted temporarily. Old versions of a key remain until a merge removes them.
A B-tree makes the opposite trade. It has simpler, predictable reads and one copy of each key, but it pays with random writes.
Check your understanding
Exercise
A service receives 50,000 small writes per second with random keys, and reads are rare. Why might an LSM tree fit better than a B-tree, and what cost will it add?
Show answer
A B-tree would turn each write into a random in-place page update, which is slow on both hard disks and SSDs. An LSM tree buffers writes in memory and flushes them as large sequential files, so it sustains the write rate more easily. The added cost is that reads may check several files, and background merging rewrites data, using extra I/O.