What is an LSM Tree?
An LSM tree is a data structure that maintains key-value pairs across multiple levels of storage:- Memory (MemTable): Active write buffer
- Disk (SST Files): Immutable sorted files organized in levels
Unlike B-trees which update in place, LSM trees append writes and periodically merge sorted runs. This design makes writes much faster but requires background compaction.
Write Path
When data is written to RocksDB, it follows this path:Step-by-Step Write Process
- 1. WAL Write
- 2. MemTable Insert
- 3. Flush to L0
First, the write is appended to the Write-Ahead Log (WAL) for durability:
The WAL ensures data isn’t lost if the process crashes before MemTable is flushed.
Level Structure
RocksDB organizes SST files into multiple levels, each with specific characteristics:Level 0 (L0)
L0 contains recently flushed MemTables:- Files may have overlapping key ranges
- Read queries must check all L0 files
- Controlled by
level0_file_num_compaction_trigger
Too many L0 files degrades read performance. RocksDB will slow or stop writes to allow compaction to catch up.
Levels 1 through N
Lower levels have non-overlapping files within each level:Level Properties
Level Properties
- Non-overlapping: Each key exists in at most one file per level
- Sorted: Files are ordered by key range
- Binary search: Can quickly locate the correct file for a key
- Compaction targets: Files are compacted from Li to Li+1
Read Path
Reading data requires checking multiple locations:Read Search Order
- Active MemTable - Check current write buffer (O(log n))
- Immutable MemTables - Check MemTables being flushed
- Block Cache - Check if block is cached in memory
- L0 SST Files - Check all L0 files (newest to oldest)
- L1-LN SST Files - Binary search to find correct file per level
Bloom filters can quickly determine if a key is NOT in an SST file, avoiding expensive disk reads. With a 10-bit filter, false positive rate is about 1%.
Range Scans
LSM trees efficiently support range queries:Iterators merge-sort data from all levels, providing a consistent view of the database.
Merge Algorithms
RocksDB uses efficient merge algorithms to combine data from multiple levels:- Point Lookup
- Range Scan
Search from newest to oldest data:
- MemTable
- L0 (all files, newest first)
- L1 (binary search to file)
- L2 (binary search to file)
- …
Optimizing LSM Performance
Write Optimization
Read Optimization
Space Optimization
LSM vs B-Tree
LSM trees excel when write throughput is critical and you can tolerate background compaction. B-trees are better for read-heavy workloads or when consistent low latency is required.
Next Steps
Compaction
Learn how compaction optimizes LSM structure
Architecture
Understand overall RocksDB architecture
Write-Ahead Log
Deep dive into WAL for durability
Tuning Guide
Optimize LSM for your workload