LSM tree
hard 28 minA log-structured merge tree collects writes in memory, flushes them as sorted files and merges those files in the background.
See it run
Follow writes from memory to level 1, find a key, delete one, and see compaction fall behind.
Operations
Write
The log and the memtable take every write.
Step 1 of 4
Start
Memtable
empty
Level 0
empty
Level 1
empty
Ready for writes
Everything is empty.
Step 1: Start
def put(key, value): log.append(key, value) # durability memtable[key] = value # sorted, in memory if memtable.size >= LIMIT: rotate() return "ok"- Disk work now
- One append
- Disk work later
- Flush, compaction
- Update in place
- a page per change
Say when the log is flushed. That decides what a crash can take.
In the real world
The same lsm tree doing real jobs. Pick one and step through it.
Writes arrive faster than files are merged.
Step 1 of 5
Normal
- Disk busy
- 45%
Memtable
...
Level 0
SST 1: a-e · SST 2: f-j · SST 3: b-g · SST 4: c-i
Level 1
L1-1: a-c · L1-2: d-g · L1-3: h-j
Four files, then a merge. Reads are cheap.
Step 1: Normal
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Dropping the log at rotation
criticalThe frozen memtable is still only in memory. A crash before its flush loses confirmed writes.
Wrongfrozen = memtablelog.clear()flush(frozen)Rightfrozen = memtablelog.start_new_segment()flush(frozen)log.drop_segment_of(frozen)Reading old files first
criticalThe first match would be an outdated version.
Wrongfor sst in levels[0].oldest_first(): ...Rightfor sst in levels[0].newest_first(): ...Dropping tombstones in any level
criticalAn older version deeper down becomes visible again.
Wrongif value is TOMBSTONE: continueRightif value is TOMBSTONE and is_last_level: continueA very small memtable
minorMany tiny files reach level 0 and compaction never rests.
Wrongmemtable_limit = 64 KBRightmemtable_limit = 64 MB # then measure
Interview tips
How to explain it
- Log, sort, merge.
- Newest first when reading.
- Compaction trades writes for reads.
Memory trick
- WAL, Memtable, Flush.
- Level zero overlaps.
- Each level ten times larger.
Choose it when
- Writes dominate.
- Data is larger than memory.
- Keys are scattered.
Watch
- Level 0 files.
- Compaction debt.
- Tombstones.
- Free disk space.