Storage engines: B-trees and LSM trees
How databases lay data on disk, and why that choice shapes write throughput, read latency and space.
20 min readB-trees update in place
Most relational databases (PostgreSQL, MySQL InnoDB) store data in a B-tree of fixed-size pages, usually 8 or 16 KB. With a branching factor of a few hundred, a tree just 4 levels deep indexes billions of rows, and the top levels stay in memory, so a point read costs one or two disk reads. A write finds its page, modifies it in place and logs the change to a write-ahead log first for crash safety. The weakness is that updating a 100-byte row rewrites a whole 8 KB page eventually, and random writes scatter across the disk.
LSM trees append and merge
Log-structured merge trees (RocksDB, Cassandra, ScyllaDB, LevelDB) buffer writes in an in-memory table backed by a sequential log. When the memtable fills (tens of MB) it is flushed as an immutable, sorted file called an SSTable. Background compaction merges SSTables, discarding overwritten values and deletion markers (tombstones). All disk writes are sequential, so LSM engines sustain much higher write rates on the same hardware.
- Reads may check the memtable and several SSTables, so each SSTable has a bloom filter
- A bloom filter with about 10 bits per key gives a false-positive rate near 1%
- Compaction rewrites data repeatedly: write amplification of 10 to 30 times is common with levelled compaction
Amplification is the trade-off
Every engine trades between three costs: write amplification (bytes written to disk per byte written by the application), read amplification (disk reads per query) and space amplification (disk used per byte of live data). B-trees have low read amplification and moderate space overhead from half-full pages. LSM trees have low write cost per operation and good compression, but reads and range scans touch more files, and compaction competes with foreground traffic for disk bandwidth, causing latency spikes at p99.
Choosing
Pick a B-tree engine for read-heavy, transactional workloads with point lookups and range queries, such as orders and bookings. Pick an LSM engine for write-heavy workloads such as metrics, event logs, messages and location updates, where you ingest far more than you read. On the canvas, the sql component behaves like a B-tree store and nosql, timeseries_db and stream-backed stores behave like LSM stores, which is why their write ceilings differ in the Feedback panel.
Key takeaways
- B-trees update fixed-size pages in place: fast reads, random writes
- LSM trees write sequentially and compact in the background: fast writes, more work per read
- Bloom filters let LSM reads skip SSTables that cannot contain the key
- Match the engine to the read/write ratio and watch compaction for p99 latency spikes
Sign in to track lessons and earn badges.