LSM tree

Also known as: Log-structured merge-tree

On this page 7

An LSM tree, or Log-structured merge-tree, is a disk-based data structure that turns random writes into sequential writes by buffering changes in memory and periodically flushing them as immutable sorted files, which background processes later merge. In databases, the LSM tree is the main alternative to the B-tree for indexing, and it dominates in write-heavy workloads such as time series, event logging and large key-value stores.

The design trades some read efficiency and background work for very high write throughput and good compression. Understanding that trade-off, and the knobs that tune it, is essential for anyone operating storage engines such as RocksDB, LevelDB, Apache Cassandra or ScyllaDB.

How an LSM tree processes writes and reads

Every write in an LSM tree first goes to a write-ahead log for durability and to an in-memory sorted structure called the memtable, typically a skip list or balanced tree. When the memtable reaches a configured size, often 64 to 256 MB, it becomes read-only and is flushed to disk as a sorted string table (SSTable), a file whose keys are stored in order and never modified in place.

Updates and deletes do not overwrite existing data. An update simply writes a newer version of the key, and a delete writes a marker called a tombstone. The newest version wins when data is read, and obsolete versions disappear only when compaction merges files and discards them.

A read must check the memtable first and then the on-disk files from newest to oldest until it finds the key. The following table summarizes the components that make this process efficient.

ComponentLocationPurpose
Write-ahead logDisk, append-onlyRecovers memtable contents after a crash
MemtableMemoryAbsorbs writes in sorted order
SSTableDisk, immutableStores sorted keys and values
Bloom filterMemory, per SSTableSkips files that cannot contain a key
Block indexMemory or diskLocates the data block inside a file
Compaction processBackground threadsMerges files and removes obsolete data
Main components of an LSM tree

Compaction strategies and amplification

Compaction determines most of the behavior of an LSM tree, and its effects are measured as three kinds of amplification. Write amplification is the ratio of bytes written to disk to bytes written by the application, read amplification is the number of files or blocks examined per lookup, and space amplification is the ratio of disk space used to the size of live data.

No compaction strategy minimizes all three at once, a limit often described as the RUM conjecture for read, update and memory overhead. The table compares the two dominant strategies and a common hybrid.

StrategyWrite amplificationRead amplificationSpace amplification
Leveled compactionHigh, often 10 to 30Low, about one file per levelLow, about 1.1
Size-tiered compactionLow, often 2 to 5Higher, several files per tierHigh, temporarily up to 2
Hybrid or tiered-leveledModerateModerateModerate
Comparison of compaction strategies

Leveled compaction organizes files into levels where each level is typically ten times larger than the previous one and holds non-overlapping key ranges. Size-tiered compaction merges files of similar size into larger ones, which writes less data but leaves more overlapping files for reads to check.

LSM tree compared with the B-tree index

The LSM tree and the B-tree index solve the same indexing problem with opposite update philosophies. A B-tree updates pages in place, which gives predictable reads but causes random writes, whereas an LSM tree only appends and merges, which favors writes and compression at the cost of background work.

PropertyLSM treeB-tree
Write patternSequential, batchedRandom page updates
Write throughputVery highModerate
Point read latencyGood with Bloom filtersConsistently low
Range scansMerge across several filesDirect leaf traversal
Compression ratioHigh, files are immutableLower, pages keep free space
Latency stabilityCompaction can cause spikesMore uniform
LSM tree and B-tree side by side

Many relational systems use B-trees by default, while engines built for ingestion use LSM trees. Some databases, including MySQL through the MyRocks engine, allow either structure, so the choice can be made per workload rather than per product.

Tuning an LSM tree in practice

Operating an LSM-based engine well requires matching its configuration to the workload. The most influential settings are memtable size, compaction style, Bloom filter accuracy and the number of background compaction threads.

WorkloadRecommended settingReason
Heavy ingestionSize-tiered or larger memtablesReduces write amplification
Read-heavy point lookupsLeveled with about 10 bits per keyFewer files and about 1% false positives
Time series with expiryTime-window compactionDrops whole expired files cheaply
Storage-constrainedLeveled with strong compressionKeeps space amplification low
Workload-driven tuning decisions

Monitoring matters as much as configuration. Operators should track pending compaction bytes, the number of files in the first level and write stalls, because an engine that cannot compact as fast as data arrives will eventually throttle or block incoming writes.

Limitations and failure modes

The main weaknesses of an LSM tree come from its deferred cleanup. Compaction debt accumulates under sustained write bursts, reads slow down as overlapping files multiply, and latency percentiles can spike when large merges compete for disk bandwidth.

  • Tombstone buildup slows range scans when many deleted keys have not yet been compacted away.
  • Write stalls occur when the engine deliberately pauses writes to let compaction catch up.
  • Flash wear increases with high write amplification on solid-state drives.
  • Tuning complexity is significant, since dozens of parameters interact with each other.

A common misconception is that LSM trees are always faster. They excel at ingesting large volumes of writes, but for update-in-place workloads with frequent range scans and strict latency targets, a B-tree may still be the better structure.

Explained without jargon

An LSM tree is a way of storing data that can accept new information very quickly. It does not search for the perfect spot for each new item. Instead, it jots new items onto a notepad in memory. When the notepad is full, the notes are sorted and saved as a neat file.

Over time, many such files pile up. The system tidies them in the background by combining smaller files into larger sorted ones. Outdated entries are thrown away along the way. It is like dropping incoming mail into a tray and sorting the tray into folders once a day. That is much faster than filing every letter the moment it arrives.

A typical use case

A company operating about 40,000 industrial sensors needs to store one reading per sensor every second, which amounts to roughly 3.5 billion rows per day. A traditional B-tree index struggled with the constant stream of random inserts, and disk utilization stayed close to saturation during peak hours.

The engineering team moved the data to a wide-column database built on an LSM tree and configured time-window compaction with one-day windows and a 90-day retention period. Writes now land in memtables and are flushed sequentially, and expired data disappears by deleting whole files rather than individual rows.

After the migration, sustained ingestion rose to several times the previous rate on the same hardware, compressed storage shrank by about 60 percent, and queries for the last hour of a single sensor stayed within a few milliseconds thanks to Bloom filters and sorted files.