A B-tree updates data in place, paying a random disk write per change. The log-structured merge-tree makes a different bet: never update in place. Writes land instantly in a small in-memory memtable; when it fills, it’s flushed to disk as an immutable, sorted SSTable and a fresh memtable takes over. Reads consult the memtable first, then SSTables newest-to-oldest. Old versions pile up until compaction merges files and discards the shadowed ones. Write some keys, watch them flush, then read and compact.
Every write lands in the sorted memtable in memory. When it reaches 4 keys it flushes to an immutable SSTable on disk. Write keys and watch it fill.
0/4
memtable
0
SSTables
–
last read cost
How it works
The trade the LSM-tree makes is write amplification down, read amplification up. Because writes only ever append to a memtable and later flush sequentially, they avoid the random in-place disk writes a B-tree pays — great for write-heavy workloads. The cost is that one key’s history can be spread across several SSTables, so a read may have to check several files (newest first) before it finds the current value. Compaction is what keeps that number bounded: it merges SSTables and throws away every version shadowed by a newer one.
1
Write → memtable
Each write updates the in-memory memtable, kept sorted by key. No disk seek, so writes are fast and cheap. Updating an existing key just overwrites it in the memtable.
2
Full → flush to an SSTable
When the memtable reaches its size limit, it’s written out sequentially as a new immutable, sorted SSTable, and an empty memtable takes over. Old SSTables are never modified.
3
Read → newest-first
A read checks the memtable, then each SSTable from newest to oldest, stopping at the first match. The newest occurrence of a key is its current value; older copies are stale.
✓
Compaction → merge and prune
Over time, stale versions accumulate across SSTables. Compaction merges SSTables into fewer files, keeping only the newest value per key — reclaiming space and shortening the read path.
Writes
sequential, fast
Read amplification
multiple files
SSTables
immutable, sorted
Used in
RocksDB, Cassandra
The code
# simplified LSM write / read / compactdef put(k, v):
memtable[k] = v # fast: in-memory, sortedif len(memtable) >= LIMIT:
sstables.insert(0, flush(memtable)) # immutable sorted file
memtable = SortedDict()
def get(k):
if k in memtable: return memtable[k]
for sst in sstables: # newest -> oldestif k in sst: return sst[k] # first hit is currentreturnNonedef compact(): # merge, keep newest per key
sstables = [merge_keeping_newest(sstables)]
Quick check
1. Why are writes to an LSM-tree fast?
Writes only touch the in-memory memtable, and full memtables are flushed to disk sequentially as immutable SSTables. Avoiding random in-place disk writes is exactly what makes LSM-trees write-optimized.
2. A key was written three times over its lifetime. Where is its current value?
Reads go newest-first: memtable, then SSTables from newest to oldest. The first occurrence found is the current value; older copies in older files are stale and ignored.
3. What does compaction accomplish?
Compaction merges multiple SSTables into fewer, keeping only the newest value of each key. That reclaims the space held by stale versions and reduces how many files a read must check.
FAQ
What is an LSM-tree?
A write-optimized storage structure. Writes go into an in-memory sorted buffer (memtable); when full it flushes to an immutable sorted file (SSTable). Reads check the memtable then SSTables newest-to-oldest, and compaction merges files while discarding shadowed old versions.
How does an LSM-tree differ from a B-tree?
A B-tree updates in place (a random disk write per update), favoring reads. An LSM-tree never updates in place — it appends to a memtable and flushes sequentially, favoring writes. The trade: LSM reads may check several files (higher read amplification) vs a B-tree’s single path.
What is read amplification in an LSM-tree?
Because a key’s versions spread across the memtable and multiple SSTables, one read may check several places before finding the current value — that extra work is read amplification. Per-SSTable bloom filters (skip files that definitely lack the key) and compaction both reduce it.
Which databases use LSM-trees?
Write-heavy and large-scale stores: RocksDB and LevelDB, Cassandra and ScyllaDB, HBase and Bigtable, and RocksDB-based systems like CockroachDB and TiKV — chosen when write throughput and sequential I/O matter more than the lowest possible read latency.
The picture: where each key lives
The same 13 writes the table below replays, memtable limit 4. Red cells are stale copies: a=1, a=5 and b=2 are shadowed by a=9 and b=10 in newer files, yet still occupy space. Reading c has to walk past two files that do not contain it before the oldest one answers, which is read amplification made visible.
Worked example, step by step
A model of the page’s code with a memtable limit of 4 keys. The 13 writes are a=1, b=2, c=3, d=4, a=5, e=6, f=7, g=8, a=9, b=10, h=11, i=12, j=13. Each flush writes the memtable out as one immutable sorted file. “Disk entries written” counts every key-value pair ever written to a file, whether by flush or by compaction. “Probes” is the number of SSTables opened while answering a read.
Operation
Memtable
SSTables
Disk entries written
Cost
write #4: d=4
empty
1
4
—
write #8: g=8
empty
2
8
—
write #12: i=12
empty
3
12
—
write #13: j=13
j13
3
12
—
get c
found 3
3
12
3 file probes
get a
found 9
3
12
1 file probe
get z
absent
3
12
3 file probes
compact all 3 files
j13
1
21
read 12 entries, wrote 9
get c again
found 3
1
21
1 file probe
Three flushes wrote 12 entries for 12 writes, so flushing alone costs one disk write per entry and all of it sequential. The reads show the other side of the bargain: c, the oldest key, took 3 probes, a missing key also took 3 because every file must be ruled out, and the freshly overwritten a took 1. Compaction read 12 entries and wrote 9, because a appeared three times and b twice; the three stale copies of a and the stale b were dropped. That brings total disk writes to 21 for 13 user writes, about 1.6 disk writes per write. That ratio is write amplification, and it is the price of making reads cheap again: the final get c costs 1 probe.
Complexity and trade-offs
Case
Time
Space
Why
Write (memtable plus flush)
O(log m) in memory, amortised sequential disk I/O
O(m) memtable
One sorted-structure insert; each entry is later written once per flush as part of a large sequential write.
Point read, no compaction
O(s) file probes, each O(log f)
O(1) extra
Worst case is a key that is absent: every one of the s files must be checked. The example above takes 3 probes; 40 distinct keys with no compaction take 10.
Point read, after full compaction
O(log n), one file
O(n)
Same as one sorted file, but compaction itself rewrites everything it merges.
Compaction
O(total entries merged)
Up to old plus new copy while merging
A k-way merge as in external merge sort. Dropping stale versions is what reclaims space.
B-tree update in place
O(log n) page reads and a random page write
O(n)
Reads touch one path; every write is a random in-place update. Cheaper reads, costlier writes.
Notice that the read cost is counted in files, not comparisons. Searching inside one sorted file is logarithmic either way; what the design trades is how many files a read must open. Overwrite-heavy workloads show the cost of waiting: 40 writes cycling over 4 keys leave 10 files and 40 entries on disk for 4 live keys, and one compaction turns 40 entries into 4. Compacting more often keeps reads fast and space tight but pays more write amplification; compacting less is the reverse. Every LSM-tree is a choice of where to sit on that line.
A delete is written as a marker, not by erasing the old value. Suppose c=3 sits in the oldest file and a later file holds the delete marker for c. If a compaction merges only the two newer files and discards the marker as “nothing left to delete”, get c returns 3 again. A marker may be dropped only when the compaction includes the oldest file that could still hold the key.
Reading oldest-first
The first match must be the newest. With the page’s writes up to i=12, scanning files oldest to newest returns a=1; the correct newest-first scan returns a=9. Newest-first is also what lets a read stop early.
Never compacting
Files only ever accumulate. Forty writes cycling over four keys leave 10 files, so a lookup of a missing key opens all 10, and 40 entries sit on disk for 4 live keys. Compaction is part of the read path’s contract, not an optional cleanup.
Counting writes instead of distinct keys
The memtable limit measures how many keys it holds. Overwrites of the same key replace the entry in place, so 8 writes alternating between a and b never fill a 4-key memtable. A trigger that counts writes flushes at 4 and produces files of 2 entries, each tiny and each one more file to probe.
Acknowledging writes that only live in memory
The memtable is volatile. With a limit of 4, up to 3 acknowledged writes can be sitting in it when the process dies. Real systems append each write to a log first and replay it on restart; leaving that out is correct only if losing recent writes is acceptable.
Where this shows up
Write-heavy key-value stores
Event logs, time-series ingestion, message metadata and activity feeds append far more than they read in place. Storage engines built on this design turn those writes into large sequential ones, which is the reason to pick it over a B-tree.
Deletes and TTLs
Because files are immutable, deleting and expiring data means writing markers and letting compaction reclaim the space later. That is why disk use after a mass delete can stay high until compaction catches up.
Tuning read cost
Systems typically keep a small in-memory summary per file so that most files that cannot contain a key are skipped without being opened. That attacks exactly the “3 probes for a missing key” cost above without changing the write path.
Merge as a building block
Compaction is a k-way merge of sorted files, the same step that finishes an external merge sort. If you understand one you already understand the other.
SOLVE IT YOURSELF
Solve it: build an LSM-tree
A B-tree updates a record where it already lives — a random disk write per update. An LSM-tree refuses to: every write is an append to memory, flushed later as an immutable sorted file. Writes get fast; reads and deletes get interesting. Python or TypeScript.
YOUR TASK
Implement LSMTree with put(key, value), get(key), delete(key) and compact(). The memtable flushes to a new segment once it holds threshold entries. get returns None/null for a missing or deleted key.
HINTS — 9 IDEAS
Writes land in the memtable, an in-memory sorted map. No disk seek, no read-before-write — this is the whole reason LSM-trees are write-optimised.
When the memtable fills, freeze it into an immutable sorted segment and start an empty one. Segments are never edited afterwards, only created and discarded.
Because segments are immutable, an overwrite does not replace anything — it just writes a newer copy elsewhere. Both versions exist on disk at once.
So get must search newest-first: memtable, then segments in reverse creation order. The first hit wins; anything older is a stale version.
Delete cannot erase a key from an immutable file, so it writes a tombstone — a marker meaning "deleted here". A read that hits a tombstone first must report absence, not keep looking.
Without tombstones, deleting a key would silently resurrect its older value from an earlier segment. That is the bug this design exists to prevent.
Compaction merges segments oldest-to-newest into one, keeping only the newest version of each key and dropping tombstoned keys entirely. That is where the space actually comes back.
Flush the memtable before merging. A tombstone still sitting in memory would be missed, and the compacted segment would carry the key's old value straight back onto disk.
The cost of all this is read amplification: a miss touches every segment. Real engines add a Bloom filter per segment to skip most of them.