LSM Trees: How Modern Databases Make Writes Fast
Table of Contents
Why Use an LSM Tree?
Databases must accept writes, keep data durable, and still answer reads efficiently. One challenge is that storage devices generally handle sequential I/O more efficiently than scattered random writes. Updating an on-disk B-tree in place can require locating and modifying several pages, and a split may cause additional page writes.
A Log-Structured Merge Tree (LSM tree) takes a different approach: buffer updates in memory, write sorted batches to disk, and merge those batches in the background. Instead of repeatedly modifying existing disk pages, the engine turns many small logical updates into larger sequential writes.
The central idea
Buffer
Collect writes in memory
Flush
Write sorted files sequentially
Compact
Merge files in the background
An LSM tree is not one single in-memory tree mirrored on disk. It is a collection of components at different stages of the write lifecycle. The exact organization varies between database engines, but the common building blocks are a write-ahead log, one or more memtables, immutable sorted files, and a compaction process.
The Write Path: WAL and Memtable
1. Write-ahead log (WAL)
When a client writes a key-value pair such as user:42 -> { name: Maya, plan: pro }, the database first appends a record describing the operation to its write-ahead log. The WAL is an append-only log, so new records can be written sequentially.
The WAL provides a recovery path if the process or machine fails before the in-memory data has been flushed to an SSTable. On restart, the engine replays the relevant log records to reconstruct the memtable. Whether a write is guaranteed to survive a sudden power loss when it is acknowledged depends on the configured durability policy, including when the WAL is flushed to stable storage.
2. Memtable
After logging the operation, the database applies it to a memtable: a mutable, in-memory data structure that keeps entries ordered by key. Implementations commonly use a balanced tree or skip list. Because the memtable is in memory, it can accept updates and serve recent reads without immediately touching disk.
A simplified write sequence looks like this:
- Append the operation to the WAL.
- Apply the update to the active memtable.
- Acknowledge the write according to the configured durability policy.
- When the memtable reaches its size threshold, freeze it and create a new active memtable.
- Flush the frozen memtable to a new SSTable on disk.
Simplified write path
user:42 -> valueThe active memtable can continue accepting writes while a previously frozen memtable is flushed. This separation helps keep foreground writes moving while disk work happens asynchronously.
Flushing Immutable SSTables
An SSTable (Sorted String Table) is an immutable file containing key-value entries sorted by key. When a memtable fills up, the database writes its contents in sorted order to a new SSTable. Since the file is immutable after creation, the engine does not need to perform in-place updates to its contents.
A newly flushed SSTable may contain a key that is also present in an older SSTable. This is expected: the newer file represents a later version of that key. Engines typically attach sequence numbers or equivalent version metadata to writes so they can determine which value is visible.
Example: the same key in multiple files
Newer SSTable
user:42 → plan: pro
More recent version
Older SSTable
user:42 → plan: free
Older version remains until compaction
A read must return the newest version visible to its snapshot, not whichever copy happens to be found first on disk.
SSTable structure: data blocks and sparse index
An SSTable is usually too large to read into memory all at once, so its sorted entries are stored in smaller chunks called data blocks. Each block contains a consecutive range of keys. For example, one block might contain apple, banana, and cherry, while the next block contains the following keys in sort order.
The reader needs a quick way to decide which block could contain a requested key. That is the job of the sparse index. Rather than storing an index entry for every key, it stores a small number of entries that identify each block. A common design records the block's last key and a block handle (the block's file offset and size). Because the data is sorted, the reader can find the first index key that is greater than or equal to the target key; the corresponding block is the only candidate it needs to read.
Example: data blocks and their sparse index
Data block 1
apple
banana
cherry
Illustrative offset: 0
Data block 2
date
fig
grape
Illustrative offset: 4096
Data block 3
kiwi
mango
orange
Illustrative offset: 8192
Sparse index (one entry per block)
cherry
→ offset 0
grape
→ offset 4096
orange
→ offset 8192
The offsets and keys above are just an example. Real block sizes and index-entry choices depend on the SSTable format.
What happens when we look up a key?
Suppose we want to find fig. The reader searches the sparse index and finds the first boundary that is not smaller than fig: grape. That entry points to data block 2. The engine reads that block (or gets it from the block cache), then searches inside it for the exact key. If the key is not in that block, the lookup returns not found; it does not need to scan every block in the SSTable.
- Search the small sparse index for the block boundary covering the target key.
- Use the stored offset and size to locate that block in the SSTable file.
- Read the block from disk, unless it is already in the block cache.
- Search the block for the exact key and its value.
Other metadata in an SSTable
The data blocks hold the actual key-value entries. Other structures help the reader find or avoid reading those blocks:
- Index block: stores the sparse index entries, mapping key boundaries to data-block handles. It is an index of blocks, not a separate entry for every key.
- Filter block: often stores Bloom-filter data. The reader can check whether a key is definitely absent and skip the relevant data block or file, depending on the filter design. A possible match still needs to be checked in the data block.
- Footer: a small structure at the end of the file that tells the reader where important metadata blocks are located, commonly including the index block and a metadata index. This lets the reader find the index without scanning the whole file.
A useful way to remember the roles is: data blocks store the records, the index block points to data blocks, the filter helps rule out unnecessary reads, and the footer tells the reader where the metadata lives. These are common ideas in block-based SSTable formats, not a universal byte-for-byte layout; different engines may organize or name the metadata differently.
Reading Data Efficiently
Reads need to account for data spread across several places. A typical lookup checks the active memtable and any immutable memtables first, then searches relevant SSTables. The engine uses version metadata and the read's snapshot to select the newest visible value. The precise order and file-selection strategy depend on the LSM layout and compaction policy.
Bloom filters
A Bloom filter is a compact probabilistic structure that can tell the engine whether a key is definitely not present in an SSTable. If it reports that the key is absent, the engine can skip that file. If it reports that the key may be present, the engine must still check the index and data block because false positives are possible.
A correctly constructed Bloom filter has no false negatives: if a key is present in the set represented by the filter, the filter will not report it as absent. Its benefit is especially clear when a lookup key is missing from most SSTables.
Block cache
A block cache keeps recently or frequently accessed SSTable blocks in memory. If a later read needs the same block, the database can reuse the cached copy instead of issuing another disk read. This is useful for workloads with hot keys or repeated range scans.
Simplified SSTable lookup
- Check memtables for a newer visible version.
- Use the Bloom filter to skip files that definitely do not contain the key.
- Use the sparse index to locate the likely data block.
- Read the block from cache or disk and search for the key.
- Compare versions across candidates and return the newest visible value.
Compaction: The Essential Background Process
Every memtable flush creates another SSTable. Without compaction, the number of files would keep growing, reads would need to consult more files, and obsolete versions would consume disk space. Compaction merges selected sorted files into new sorted files and eventually replaces the input files.
During a merge, the engine processes entries in key order. When several input files contain versions of the same key, it can discard versions that are no longer needed by active snapshots and retain the newest version that must remain visible.
Tombstones: representing deletes
Deleting a key cannot always mean immediately removing every copy from every SSTable. An older value may still exist in another file and could reappear if the delete marker disappeared too early. Instead, the engine writes a tombstone: a special record indicating that the key has been deleted.
The tombstone must be retained until compaction can safely prove that no older value can become visible again, taking levels, snapshots, and other storage rules into account. Once it is safe, compaction can remove both the tombstone and the obsolete values it masks.
What compaction accomplishes
- Merge sorted files while preserving key order.
- Discard obsolete versions when they are no longer needed.
- Remove tombstones only when older values are guaranteed not to reappear.
- Reduce the number of files that reads need to inspect.
- Rebuild indexes and Bloom filters for the output files.
- Reclaim disk space occupied by obsolete records.
Different engines use different compaction strategies. In leveled compaction, files in a level are organized so that key ranges generally do not overlap within that level, while a lower level has a larger target capacity. Size-tiered compaction instead groups similarly sized files for merging. These choices affect write amplification, read amplification, space amplification, and background I/O.
Conceptual compaction
SSTable A
a, c, e
SSTable B
b, c, d
↓ merge, sort, resolve versions
New SSTable
a, b, c, d, e
One ordered output file
Trade-offs and Where LSM Trees Fit
LSM trees are attractive for write-heavy workloads because they batch updates and turn much of the disk work into sequential writes. They are used in storage engines and databases such as LevelDB, RocksDB, and Apache Cassandra, although each system has its own architecture and tuning choices.
The write path is not free. A logical update may be rewritten during multiple compaction rounds, creating write amplification. Reads may need to check multiple files, creating read amplification. Temporary input and output files can also increase disk usage during compaction, contributing to space amplification.
Bloom filters, sparse indexes, block caches, and careful compaction policies help control these costs, but they do not eliminate the underlying trade-offs. An LSM tree is therefore not automatically faster for every workload. A system with frequent point updates and read-heavy access patterns may make different design choices from one that receives a continuous stream of writes.
The main trade-offs
Write amplification
The same logical data may be written multiple times as files are compacted.
Read amplification
A read may need to examine multiple memtables or SSTables.
Space amplification
Old and new files can coexist temporarily, and obsolete versions occupy space until compaction.
The key idea is to move much of the cost of maintaining sorted on-disk data away from the foreground write path and into batched flushes and background merges. WALs provide recovery, memtables absorb recent updates, SSTables provide immutable sorted storage, and compaction keeps the collection of files manageable.