When we pick a database, we usually compare the things we can see: the query language, the client libraries, the ecosystem, maybe the pricing. Postgres or MySQL? Cassandra or something else? RocksDB or LMDB if we want an embedded one?
Very few people start with the question of what happens to a key and a value after they are handed to the database. Yet that is the part that decides how fast your writes are, how quickly your SSD wears out, and why your latency graph has a strange spike at 3 AM that nobody can explain.If you don't know about these indexes you will be in a better place after reading this while choosing a database.
That piece of code is the storage engine, and most of them are built on one of two ideas: the B-tree or the LSM tree. This post is about those two. How each one stores data, what each one pays for the things it is good at, and how to tell which one fits the workload in front of you.
To keep things simple, I am going to treat every database here as a plain key-value store, the way Designing Data-Intensive Applications (DDIA) does. No SQL, no joins, no documents. A key goes in, a value comes out. Everything else is built on top of that.
Start with the dumbest database
Before looking at either structure, it helps to see why they exist. Here is the simplest database you can write, two bash functions:
db_set() { echo "$1,$2" >> database; } db_get() { grep "^$1," database | sed -e "s/^$1,//" | tail -n 1; } db_set appends a line to a file. db_get scans the whole file and returns the last match for the key. Updating a key doesn't touch the old line, it just adds a newer one below it.
Writes here are about as fast as they can be, because appending to the end of a file is sequential I/O, which disks of every kind handle well. Reads are terrible. Every lookup scans the entire file, so the cost grows with the amount of data.
The usual fix is an index. Keep a hash map in memory that maps each key to the byte offset of its latest value in the file. Now a read is one hash lookup and one disk seek. This is roughly what Bitcask does, and it works nicely, as long as all your keys fit in memory and you never need to ask for a range of keys. A hash map has no idea which keys are "between" two others.
It also has a second problem. The file never stops growing, because old values are never removed.
Every storage engine we care about starts from this situation. You can see two reasonable reactions to it, and they lead to the two families we are comparing. One is to keep the append-only log and make it smarter. That road leads to LSM trees. The other is to throw the log away and update data in place, in a structure that is good at lookups. That road leads to B-trees.
LSM trees: never overwrite, just merge later
LSM stands for log-structured merge tree. It takes the append-only log from our dumb database and fixes its two problems, the slow reads and the endless growth, without giving up sequential writes.
Here is how a write flows through it.
- The write goes into an in-memory sorted structure called the memtable (a balanced tree or a skip list, usually). This is fast because it is just memory.
- Memory vanishes in a crash, so each write is also appended to a write-ahead log (WAL) on disk before it is acknowledged. After a crash, the engine replays the log to rebuild the memtable. The log exists only to protect the memtable.
- When the memtable grows past some size, say a few megabytes, it is written to disk as a single file in sorted order. This file is called an SSTable (sorted string table). Since the memtable was already sorted, this is one fast, sequential write.
- SSTables are immutable. Once written, they are never modified.
That immutability is the whole trick. The engine never goes back to change something in place. Updating a key just means writing a newer version into the memtable. Deleting a key means writing a special marker called a tombstone. The old versions are still sitting in older files, and they are cleaned up later.
Reading is where you pay for this. To look up a key, the engine checks the memtable first, then the newest SSTable, then the next newest, and so on, until it finds the key or runs out of files. If the key doesn't exist at all, it has to check everything, which is the worst case.
Two things keep this from being a disaster. Each SSTable carries a sparse index, so checking one file is cheap. And each one carries a Bloom filter, a small probabilistic structure that can say "this key is definitely not in this file" without reading the file. The Bloom filter is what turns "check twenty files" into "check one or two." We will take a proper look at how Bloom filters work and how they are tuned in a later blog. For now it is enough to know that they speed up point lookups, and that they do nothing for range scans, because a filter can answer "is this exact key here?" but not "is anything between A and Z here?"
That brings up the range scan. LSM trees can do them, since every SSTable is sorted. But the engine has to open an iterator on the memtable and on several SSTables and merge them on the fly, picking the smallest key at each step and hiding stale versions and tombstones. It works, it is just more work and less predictable than walking along B-tree leaves.
The last piece is compaction. In the background, the engine picks several SSTables, merges them into new ones, and throws away overwritten values and tombstones. This keeps the number of files under control and gets rid of the garbage. Which files to merge, and when, is a deep topic with real consequences, and there are different strategies for it (leveled and size-tiered are the two names you will hear most). We will come to those in a later blog.
B-trees: update in place
Now the other reaction to the dumb database: forget the log, and update data where it lives. B-trees came first (1970) and are still the default in almost every relational database. The idea is to break the database into fixed-size pages, typically 4 to 16 KB, and arrange those pages as a tree.
Each page holds a sorted run of keys. In the interior pages, the keys act as signposts: they tell you which child page to go to for a given range. In the leaf pages, you find the actual values (or pointers to them). To look up a key, you start at the root, follow the signposts down, and land on the right leaf. Because each page can point to hundreds of children, the tree is very shallow. DDIA works out that a four-level tree with a branching factor of 500 and 4 KB pages can store around 256 TB. In practice that means a lookup touches only a handful of pages, and the top levels are usually cached in memory anyway.
Writes work differently from the log. To update a value, you find the leaf page that holds the key, change it, and write the page back to the same place on disk. If the page is full, it splits into two, and the parent gets a new signpost. The tree stays balanced all the time.
Overwriting pages in place brings a crash-safety problem. If the machine dies halfway through a page split, you can be left with a corrupted tree. So B-tree engines keep a write-ahead log too, the same idea we saw in the LSM write path: an append-only file where every change is recorded before the pages are modified. After a crash, the engine replays the log and gets back to a consistent state.
Notice what this means for the cost of a write. You wanted to change a 100-byte value. The engine rewrote an entire 4 KB or 16 KB page, and wrote the change into the WAL as well. These writes also land at scattered places on disk, which is random I/O.
The reads are the good part. A lookup is a short, predictable walk down the tree. A range scan is even better, since in the common B+tree variant, leaf pages are laid out in key order and linked together. Find the start of the range, then walk along the leaves.
Amplification: the real cost of each design
Now to the heart of the comparison. Every storage engine does more physical work than the application asked for, and that extra work is called amplification. It comes in three flavors.
Write amplification is the number of bytes written to disk for each byte the application wrote. Read amplification is the number of disk reads needed to answer one lookup. Space amplification is how much disk you use compared with the size of your actual data.
Here is how the two families compare, in rough terms:
| LSM tree | B-tree | |
|---|---|---|
| Write amplification | Data rewritten every time compaction moves it | Whole page rewritten per update, plus the WAL |
| Read amplification | Higher (several files), reduced by Bloom filters | Low and predictable (a few pages) |
| Space amplification | Old versions and tombstones until compaction cleans them | Partly empty pages and fragmentation |
| Write pattern | Sequential I/O | Random I/O |
Let's go through the rows, because the table hides some surprises.
Write amplification exists in both. This is the point people most often miss. It is tempting to say "LSM trees have write amplification and B-trees don't," but that is wrong. A B-tree changing a 100-byte value rewrites a whole page, so in the worst case the physical write is dozens of times larger than the logical one, and then the WAL doubles part of it. What differs is the shape of the cost. B-tree writes are many small, random writes. LSM writes are fewer, larger, sequential writes, but the same data gets rewritten repeatedly as it is merged from file to file during compaction. Depending on how the engine is configured, an LSM tree can end up rewriting each piece of data many times over its lifetime. Disks, especially SSDs, are much happier with sequential writes, which is why LSM trees often still come out ahead on write throughput despite the repeated rewriting.
Read amplification favors the B-tree. A B-tree lookup touches a few pages, always. An LSM lookup might touch several files, and how many depends on how well compaction has been keeping up. Bloom filters narrow the gap for point lookups, but they never fully close it, and they don't help ranges at all.
Space amplification depends on how you look at it. B-trees leave pages partly empty so that inserts don't cause a split every time, and fragmentation builds up as pages split and get deleted. LSM trees carry stale versions of keys and tombstones until compaction reaches them. LSM trees can often compress better, since SSTables are written in big sorted blocks that compress well, but during a compaction you also need room for both the old files and the new ones.
When compaction becomes the problem
You had the right intuition about compaction. It is a background process that competes with everything else for disk bandwidth, and at low write rates nobody notices. The trouble starts when the incoming write rate gets close to what the disk can sustain.
Think about what the engine is doing at that point. It has to flush new memtables to disk and also merge old files, and both need bandwidth. Compaction work is proportional to how much data you write, so the heavier the write load, the more compaction there is to do. If it falls behind, SSTables pile up. More SSTables means more files to check per read, so reads get slower. If it falls further behind, the engine has no choice but to slow down or even stop accepting writes until compaction catches up. This is a write stall, and it is the cause of many of those mysterious latency spikes.
Notice that this doesn't show up in a quick benchmark. A fresh database with little data runs beautifully. The cost arrives later, as the dataset grows and the compaction workload grows with it. So if you are evaluating an LSM-based engine, test with a realistic amount of data and run long enough for compaction to get busy.
There is a second cost on SSDs. Because data is rewritten many times, an LSM engine under a heavy write load writes far more to the drive than the application ever sent it, and flash has a limited number of write cycles. B-trees have the same concern, with their own pattern. This is one reason write amplification is worth measuring and not just reasoning about.
Which workload suits which
With all that, we can start matching engines to workloads.
If your workload is write-heavy, such as ingesting logs, metrics, events or time series, where data arrives constantly and mostly doesn't get updated, LSM trees are a natural fit. Sequential writes are cheap, and you rarely re-read the same keys right after writing them.
If your workload is read-heavy with point lookups, think a user profile table, an order lookup, anything where reads far outnumber writes, B-trees give you predictable latency. You know a lookup will touch a few pages, and there is no background merging competing with your reads.
If you do a lot of range scans, B-trees have the edge. Sorted leaf pages, walked in order, are hard to beat, and the cost doesn't depend on how many files compaction has left lying around.
If your workload is mixed, it genuinely depends, and this is where people get stuck. A mixed workload with a small hot set that fits in memory may do fine on either. A mixed workload with a huge dataset and a steady stream of updates will test both designs in different ways.
One more consideration that isn't about speed: transactions. In a B-tree, each key lives in exactly one place, which makes it simple to attach locks to a key or a range of keys. That is part of why B-trees have stayed the default for transactional databases. LSM engines can do transactions too, but there are several versions of a key scattered around, so the implementation is a bit more involved.
Two real engines: RocksDB and LMDB
It helps to see the two ideas in actual software. Both of these are embedded engines, meaning they are libraries that you link into your program, not servers you connect to. That makes them a good place to see the data structures with nothing else around them.
RocksDB is an LSM engine. Facebook built it as a fork of Google's LevelDB, tuned for fast storage and heavy write loads. It has everything we discussed: a memtable, a WAL, SSTables, Bloom filters and compaction, along with a very large number of tuning knobs. Many other systems use it as their storage layer, for example TiKV, and Kafka Streams uses it for local state. The knobs are both a strength and a warning: you can tune RocksDB for a lot of different workloads, and it is also easy to configure badly.
LMDB is a B+tree engine, but with a twist. It uses copy-on-write: when you modify a page, it doesn't overwrite it. It writes a new copy and updates the parents to point at the copy, all the way up to the root. The commit is an atomic switch to the new root. Since old pages are never modified, a crash can never leave a half-written tree, so LMDB needs no WAL at all. It also memory-maps the file, so reads go straight through the OS page cache with no extra copying. Readers never block writers (or the reverse), though there is only one writer at a time. LMDB is aimed at read-heavy workloads, and it does that job very well.
Put them next to each other and you get the whole trade-off in miniature: one engine that makes writes cheap and pays for it in the background and at read time, and another that makes reads simple and fast and takes the cost on every write.
The bigger names you will see elsewhere fit the same split. MySQL's InnoDB and Postgres's default indexes are B-tree based. Cassandra and HBase are LSM based. We will get into how some of these actually behave in future posts.
How to choose
If you strip it down, there are a few questions worth asking about your own workload before you pick an engine.
Is it mostly writes or mostly reads? How much of the read traffic is point lookups, and how much is range scans? Does the dataset fit in memory, or is it much larger than memory? Can you tolerate occasional latency spikes in exchange for high write throughput, or do you need smooth, predictable latency?
No answer to these is "right" in general. They just point you toward one side or the other.
No free lunch
There is a name for this pattern. The RUM conjecture says that a storage structure can't minimize all three of Read cost, Update cost and Memory (space) cost at the same time. Improving two of them makes the third worse.
B-trees spend on updates to keep reads cheap and predictable. LSM trees spend on reads and on background work to keep updates cheap. Neither is a better design. They are answers to different questions, which is why both are still everywhere, decades later.
The most useful thing to take away is the habit of asking what a database is doing with your bytes on disk. Once you can answer that, the benchmark results, the latency spikes and the disk-wear numbers all start to make sense.
Most of the framing here comes from Chapter 3 of Martin Kleppmann's Designing Data-Intensive Applications. If you have not read it, it is worth your time.
