Saltar al contenido principal

Fast Writes, Patient Reads: Inside the LSM Tree

· 10 min de lectura
Clustron Team
Ingeniería de Sistemas Distribuidos

There are two fundamentally different ways to put key-value data on disk, and the choice colors everything the store does under load. The classic answer is the B-tree, which updates records in place: to change a value it locates the page holding it, reads that page, modifies it, and writes it back. B-trees give wonderful reads — a lookup is a short walk down a shallow tree — but every write is a random seek followed by a read-modify-write, and updating pages in place is the opposite of the append-only writing that makes a store crash-safe and a disk happy.

The log-structured merge tree inverts the arrangement completely. It never updates anything in place; it only appends. A write goes into a write-ahead log for durability and into a sorted in-memory table called the memtable. When the memtable grows past a threshold, it is flushed to disk in one shot as an immutable, sorted file — an SSTable — written sequentially with no seeks. The store ends up holding a growing collection of these immutable files, each a frozen snapshot of some batch of writes.

That design makes writes blisteringly fast, because a sequential append to a log and an in-memory insert are about the cheapest durable operations there are. But nothing is free: the cost has been moved, not removed. It lands on reads, which may now have to look in several files to find a key, and on a background process that has to keep merging those files so their number does not grow forever. Understanding the LSM is understanding where that cost went and how it is controlled.

Writes go in one direction: down and sequential​

The write path has exactly two steps and neither of them seeks. First the record is appended to the write-ahead log, so the write is durable the instant that append returns — if the process dies, recovery replays the log to rebuild whatever was still only in the memtable. Second, the record is inserted into the memtable, an in-memory sorted structure. The client is acknowledged, and that is the whole hot path.

Flushing happens off to the side. When the memtable fills, it is sealed, a fresh one takes over for incoming writes, and the sealed table is written out as a new SSTable in a single sequential pass. Because the memtable was already sorted, the SSTable is sorted too, which is what makes it searchable later. No existing file is ever modified — a flush only ever adds a new immutable file — so the disk sees nothing but large sequential writes, which is the access pattern spinning disks and SSDs both love.

writememtableRAM, sortedWAL (durability)flush when fullSSTable — newestbfSSTablebfSSTable — oldestbfread keycheck memtable, then SSTables newest→oldest; bloom skips missescompactionmerges fileswrites are sequential and seekless; a read may consult several files — compaction keeps that number bounded

Reads look in many places — but not all of them​

Because a key's latest value might sit in the memtable or in any SSTable, and because newer always wins over older, a read proceeds newest-to-oldest: check the memtable first, then each SSTable from the most recent flush backward, stopping at the first hit. Taken literally that is alarming — a store with twenty SSTables could touch twenty files for one missing key. This is read amplification, and the LSM has two devices that tame it.

The first is that each SSTable is sorted and carries a sparse index, so finding a key within a file is a binary search, not a scan. The second is decisive: each SSTable has a bloom filter over its keys. Before touching a file, the reader asks its bloom filter "could this key be here?" — and because a bloom filter never produces a false negative, a "no" means the key is definitely not in that file and it is skipped without a single disk access. For a key that exists in just one SSTable, the reader blows past all the others on their bloom filters and does real I/O only on the one that might hold it. Read amplification is real, but bloom filters collapse it from "every file" to "the few files that plausibly match."

Compaction pays the deferred bill​

SSTables pile up, the same key accumulates copies across many files, and deletes leave tombstones that must linger until every older copy they shadow is gone. Left alone, read amplification would creep upward and dead data would hog disk forever. Compaction is the background process that fixes both: it reads several SSTables, merges their sorted contents, keeps only the newest value for each key, and drops superseded values and tombstones whose grace has passed — exactly the log-compaction idea applied to the on-disk files, and the natural place to finally discard keys that expired by TTL. The output is fewer, larger, cleaner files, which is what keeps reads fast and space in check.

// Merge several sorted SSTables into one; newest wins, dead data drops out.
SSTable Compact(IReadOnlyList<SSTable> inputs /* newest first */) {
var writer = new SSTableWriter();
foreach (var (key, newest) in MergeSortedByKey(inputs)) { // first seen = newest
if (newest.IsTombstone && newest.Age > graceWindow) continue; // reclaim delete
if (newest.IsExpired) continue; // reclaim TTL
writer.Add(key, newest.Value); // keep latest only
}
return writer.Finish(); // one bigger, cleaner, still-immutable file
}

The amplification triangle​

Everything about tuning an LSM comes down to three costs that trade off against each other. Write amplification is how many times a byte gets rewritten: a single logical write is copied again by every compaction that touches it, so one write can become many physical writes over its life. Read amplification is how many files a read may consult. Space amplification is how much stale, superseded data sits on disk waiting to be compacted away. You cannot minimize all three at once — pushing down on one pushes up on another — and the compaction strategy chooses which to favor. Leveled compaction keeps data in size-tiered levels with little overlap, giving low read and space amplification at the price of high write amplification; size-tiered compaction merges similarly-sized files only occasionally, giving low write amplification but more files to read and more stale data retained. A read-heavy store leans leveled; a write-heavy one leans tiered. There is no free corner of the triangle, only the corner that matches the workload.

Wrap-up​

The LSM tree makes writes fast by refusing to update in place: every write is a sequential append to a log and an in-memory table, flushed later as an immutable sorted SSTable, so the disk only ever sees large sequential writes. It pays for that on the read side, where a key may live in any of many files — but sorted files, sparse indexes, and a bloom filter per SSTable mean a read touches only the files that could actually contain the key. Compaction runs underneath, merging files to keep the newest value per key and to reclaim tombstones and expired data, and the whole design resolves into a three-way tradeoff between write, read, and space amplification that the compaction strategy tunes to the workload. Fast writes, patient reads, and a background process quietly keeping the bargain honest.