B-trees vs LSM trees: why some databases are built for heavy writes
Under every database is a data structure deciding how records are laid out on disk. Two families dominate: B-trees and log-structured merge trees (LSM trees). They make opposite trade-offs.
B-trees
A B-tree keeps data sorted in fixed-size pages arranged as a shallow, wide tree. Finding a key means walking from the root to a leaf, touching only a handful of pages even for huge tables.
- Updates in place: changing a row means modifying the page that holds it.
- Strengths: fast, predictable reads and range scans.
- Weaknesses: random writes scattered across the disk, page splits when pages fill up.
- Used by most traditional relational databases.
LSM trees
An LSM tree buffers writes in memory, then flushes them to disk as immutable sorted files. Over time, background compaction merges these files and discards overwritten or deleted values.
- Strengths: very fast writes, because disk writes are large and sequential.
- Weaknesses: a read may need to check several files, which databases mitigate with techniques like Bloom filters and caching. Compaction uses CPU and I/O in the background.
- Common in key-value stores and systems built for high write throughput.
The amplification triangle
Engineers often talk about three costs:
- Read amplification: how much extra data is read per query
- Write amplification: how many times data is rewritten
- Space amplification: extra disk space for old or duplicate data
Neither structure wins on all three. You pick based on whether your workload is read-heavy, write-heavy or tight on storage.
Discussion:
- Have you run into compaction stalls or page-split issues in production?
- Which workloads have you moved to an LSM-based store, and did it pay off?
Comments · 2
So B-trees update data in place and LSM trees batch writes first and merge later? That explains why write-heavy systems prefer LSM.
The trade-off I see in practice is reads. LSM trees can need more work to look up a key, which bloom filters help with.