AlgoViz

LSM tree

hard 28 min

A 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

Our systemflushClientLSM engineLogemptyMemtable0 of 5Level 0emptyLevel 1emptyLevel 2empty

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

Our systemflushClientLSM engineLog1 recordsMemtable1 of 5Level 04 filesLevel 13 filesLevel 2empty
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

    critical

    The frozen memtable is still only in memory. A crash before its flush loses confirmed writes.

    Wrong
    frozen = memtablelog.clear()flush(frozen)
    Right
    frozen = memtablelog.start_new_segment()flush(frozen)log.drop_segment_of(frozen)
  • Reading old files first

    critical

    The first match would be an outdated version.

    Wrong
    for sst in levels[0].oldest_first():    ...
    Right
    for sst in levels[0].newest_first():    ...
  • Dropping tombstones in any level

    critical

    An older version deeper down becomes visible again.

    Wrong
    if value is TOMBSTONE:    continue
    Right
    if value is TOMBSTONE and is_last_level:    continue
  • A very small memtable

    minor

    Many tiny files reach level 0 and compaction never rests.

    Wrong
    memtable_limit = 64 KB
    Right
    memtable_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.