Most key-value store interviews stop at the distributed layer - consistent hashing, quorums, replication - and quietly assume each node has “a storage engine” that durably holds the bytes. This post is about that box. Not the ring, not the quorum: the single-node engine that takes put(key, value) and get(key), survives a crash, and stays fast when the dataset is ten times larger than RAM. That last constraint is the entire problem. If everything fit in memory you would use a hash map and a write-ahead log and go home. It does not fit, so most of your data lives on disk, and the question becomes: how do you make writes cheap, reads fast, and disk usage sane all at once, when those three pull in opposite directions?
The instinct is a B-tree - that is what a normal database uses. But a B-tree updates pages in place, which means a write to a random key is a random disk write, and random writes are the slowest thing a disk does. A write-heavy engine that does a random write per put falls over. The log-structured merge-tree (LSM) inverts this: buffer writes in memory, flush them to disk as immutable sorted files in big sequential batches, and merge those files in the background. Writes become sequential and fast. The cost is that a single key can now live in many files, so a read might have to check several of them, and the background merging rewrites data over and over. The whole design is about bounding those two costs - read amplification and write amplification - without letting disk usage (space amplification) blow up. This is the engine inside LevelDB, RocksDB, Cassandra, and the storage layer of half the databases you have heard of.
Let me build it properly.
Functional Requirements (FR)
In scope:
- put(key, value). Insert or overwrite. Keys and values are opaque byte strings; keys up to a few KB, values up to a few MB. An overwrite is just another
put- the engine does not update in place. - get(key). Return the current value for a key, or “not found.” This is the operation whose latency we fight hardest to keep low.
- delete(key). Remove a key. In an LSM this is not a real removal - it writes a tombstone, a marker that says “this key is dead,” which only physically disappears during a later merge. Deletes are a subtle, first-class concern.
- Ordered iteration / range scan.
scan(start_key, end_key)returning keys in sorted order. The “sorted” in sorted string table is what makes this cheap, and it is a reason to pick an LSM over a hash index. - Durability. An acknowledged write survives a process crash or power loss. We guarantee this with a write-ahead log, independent of when data reaches its final on-disk home.
- Crash recovery. After a crash the engine reconstructs its exact pre-crash state from durable artifacts (the log plus the on-disk files).
- Snapshots / point-in-time reads. A read sees a consistent view; a long scan is not corrupted by concurrent writes. Immutability makes this nearly free.
Explicitly out of scope (own the boundary):
- Distribution, replication, sharding. This is one node’s engine. Consistent hashing, quorum, and cross-node consistency are a layer above this box and are a different design. We expose a clean local
get/put/delete/scanfor that layer to build on. - Transactions across many keys. We provide atomic single writes and a consistent read snapshot, not multi-key serializable transactions. A transaction layer (e.g. MVCC with a sequence number per write, which we do touch) sits on top.
- A query language, secondary indexes, joins. Access is by key or key-range. Secondary indexes are built as separate key spaces on top of this engine, not a core feature.
- The exact value format. Values are opaque blobs; the engine does not parse them.
The single decision that drives everything: this is a write-optimized engine that turns random writes into sequential ones by never updating in place - it appends to memory, flushes immutable sorted files, and merges them in the background - and the central engineering problem is bounding read amplification, write amplification, and space amplification simultaneously through the compaction strategy. Every other choice follows from that.
Non-Functional Requirements (NFR)
- Scale: a dataset of 1-10 TB on a single node, far larger than the ~64 GB of RAM available. Key count on the order of 1-10 billion keys. The defining ratio is roughly 100:1 data-to-RAM - the working set does not fit, so disk layout and the number of disk seeks per read are what matter.
- Throughput: sustain 100K-500K writes/sec and 50K-200K reads/sec on a single node on NVMe SSD. Writes are the pressure case; the design exists to make them cheap.
- Latency: p99 get under ~1ms when served from cache or a single SSTable, under a few ms for a cold multi-level lookup. put p99 sub-millisecond because a write only touches memory plus a sequential log append.
- Durability: an acked write must survive crash and power loss. Zero loss of acknowledged data. Configurable:
fsyncper write (strict) versus batchedfsync(fast, a few ms of writes at risk on power loss). - Read amplification: bounded to a small, constant number of SSTable lookups per key regardless of dataset size - the headline goal. “A
gettouches O(levels) files, not O(total files).” - Write amplification: the bytes written to disk per byte of user data, kept to a practical constant (single to low double digits), traded against read and space amplification.
- Space amplification: on-disk size versus live data size, kept under a bounded factor (ideally ~1.1x for the dominant level), so a 1 TB dataset does not need 3 TB of disk.
These three amplifications are a trilemma: you cannot minimize all three at once, and the compaction strategy is precisely the knob that picks where you sit. Stating that out loud is the core insight the interviewer is listening for.
Back-of-the-Envelope Estimation (BoE)
Grounding the design in numbers before drawing boxes.
The data-to-RAM ratio (why disk layout is the whole game):
Dataset: 4 TB live data
Avg key+value: ~400 bytes (100B key + 300B value, blended)
Key count: 4 TB / 400 B ≈ 10 billion keys
RAM: 64 GB
Data / RAM: 4 TB / 64 GB ≈ 64x
So ~1.5% of data fits in memory. 98.5% lives on disk.
A get for a random key almost always goes to disk.
The design target: make that "go to disk" cost a SMALL number of
reads, not a scan, and never a random write per user write.
Write path cost (why sequential beats a B-tree):
Write rate: 200,000 writes/sec, avg 400 B -> 80 MB/sec user data.
B-tree worst case: 1 random 4KB-page write per put (update-in-place)
= 200K random writes/sec -> a disk killer; NVMe random
write IOPS are a fraction of its sequential bandwidth.
LSM: buffer in RAM, flush in big sequential batches.
200K puts land in memory (nanoseconds) + one sequential
WAL append. Disk sees sequential MB-sized writes, not
200K scattered 4KB writes.
Memtable and flush cadence:
Memtable size cap: 256 MB (then flush to an immutable SSTable)
Write rate: 80 MB/sec user data
Flush interval: 256 MB / 80 MB/s ≈ every 3.2 seconds a new L0 SSTable.
L0 SSTables/hour: ~1,100 files/hour if nothing merged them.
-> compaction MUST keep pace or L0 file count explodes (read amp disaster).
Write amplification budget (the cost of leveled compaction):
Level fan-out (T): 10x per level (each level ~10x the previous)
Levels for 4 TB: L0 (~256MB) ... up to ~4 TB -> ~6-7 levels.
Leveled write amp: roughly T per level merged ≈ ~10 per level,
total ~10 * (levels-1) ≈ 50-70x in the worst theoretical
case; ~10-30x typical with partial/overlap-aware merges.
Meaning: 80 MB/sec user writes -> up to ~0.8-2 GB/sec of
background compaction I/O. This is why compaction
throughput and SSD endurance are first-class concerns.
Read amplification budget (the headline goal):
Without bounding: a key could be in any of thousands of L0-style files
-> thousands of lookups per get. Unusable.
With leveling: a key is in AT MOST ONE SSTable per level (levels are
internally non-overlapping), + the few overlapping L0 files.
7 levels -> at most ~7-12 SSTable lookups per get.
Bloom filters cut: ~99% of those files are skipped without a disk read
(filter says "definitely not here").
Effective disk seeks per get: often 1 (the level that actually has it),
occasionally 2-3. THIS is the bounded read amp.
Bloom filter memory:
Bloom filter: ~10 bits/key for ~1% false positive rate.
10B keys * 10 bits = 100 Gbit = 12.5 GB of bloom filters.
That does not fit fully in 64 GB RAM alongside block cache + memtable,
so filters for the largest (coldest) level may be partially paged;
the block cache holds hot blocks + hot filters. Memory budgeting
between memtable, block cache, and bloom filters is a real tuning axis.
Two conclusions drive the design. First, writes must be sequential - at 64x data-to-RAM and 200K writes/sec, a random write per put is fatal, so the engine buffers and flushes in batches. Second, a naive bag of files makes reads O(files) - the entire job of compaction is to organize those files so a get touches a small constant number of them, and bloom filters make even that number mostly free.
High-Level Design (HLD)
An LSM engine has three storage zones: an in-memory write buffer (the memtable), a durable write-ahead log that makes the memtable crash-safe, and a layered set of immutable sorted files on disk (the SSTables, organized into levels). A background compactor continuously merges files down the levels. Reads check memory first, then walk the levels top-down, using per-file bloom filters and indexes to skip almost everything.
WRITE PATH (put/delete) READ PATH (get)
┌───────────────────────────┐ ┌────────────────────────────┐
│ put(k,v) / delete(k) │ │ get(k) │
└─────────────┬─────────────┘ └──────────────┬─────────────┘
│ 1. append (seq) │ check newest first
┌──────▼───────────┐ ┌──────▼──────────────┐
│ Write-Ahead Log │ (durability) │ 1. Active memtable │ (RAM)
│ (sequential disk)│ └──────┬──────────────┘
└──────┬───────────┘ │ miss
│ 2. insert ┌─────▼──────────────┐
┌──────▼───────────┐ │ 2. Immutable │ (RAM)
│ Active Memtable │ (sorted map, RAM) │ memtables │
│ (skiplist) │ └─────┬──────────────┘
└──────┬───────────┘ │ miss
│ full -> seal, new WAL ┌─────▼────────────────────┐
┌──────▼───────────┐ │ 3. L0 SSTables (overlap)│
│ Immutable memtable│ flush in bg │ check each, bloom │
└──────┬───────────┘ ├───────────────────────────┤
│ 3. flush (seq write) │ 4. L1 (sorted, disjoint) │
┌──────▼─────────────────────────┐ │ binary search -> 1 file│
│ DISK (SSTables) │ ├───────────────────────────┤
│ │ │ 5. L2 ... Ln (10x each) │
│ L0: [sst][sst][sst] overlapping│ <──────────│ 1 file per level max │
│ L1: [ sst | sst | sst ] disjoint│ reads └───────────────────────────┘
│ L2: [ sst | sst | ... ] 10x L1 │ each file: bloom filter +
│ ... │ sparse index + data blocks
│ Ln: [ ................ ] 10x L(n-1) bloom skips ~99% of files
└──────────────┬──────────────────┘
│ COMPACTION (background)
┌──────────────▼──────────────────────────────┐
│ Compactor: pick a file in Li, merge with │
│ overlapping files in Li+1, write new sorted │
│ files into Li+1, drop superseded versions │
│ and expired tombstones. Keeps each level │
│ internally non-overlapping and size-bounded.│
└──────────────────────────────────────────────┘
Write hot path - a put being stored:
- The write is appended to the write-ahead log (a sequential disk write) and
fsynced (or batch-fsynced). Once the WAL append is durable, the write is safe even if the process dies a nanosecond later. - The write is inserted into the active memtable, an in-memory sorted structure (a skiplist or balanced tree) keyed by user key plus a monotonically increasing sequence number. The sequence number is what lets a later value shadow an earlier one and powers snapshots. The write is now visible to reads and is acked.
- When the memtable reaches its size cap (say 256 MB), it is sealed into an immutable memtable and a fresh active memtable plus a new WAL segment start. A background thread flushes the sealed memtable to disk as a new L0 SSTable - one big sequential write of already-sorted data. After the flush is durable, the corresponding WAL segment is deleted.
Read hot path - a get:
- Check the active memtable, then any immutable memtables still being flushed. If found (including a tombstone), return immediately - this is the newest data.
- Otherwise walk the levels newest to oldest. L0 files can overlap each other (each is a raw flush), so check each L0 file; L1 and below are internally sorted and non-overlapping, so a single binary search over the level’s file key-ranges picks at most one file. For each candidate file, consult its bloom filter first; if the filter says “not present,” skip the file with no disk read. Otherwise use the file’s sparse index to seek to the right block, read and decompress that block, and binary-search it for the key. The first value found (highest sequence number) wins and the search stops.
Background path - the compactor:
- The compactor keeps the shape sane: it merges L0 files into L1, and merges files down each level when a level exceeds its size budget, always writing new immutable files and atomically swapping them into the level manifest. During a merge it drops superseded versions (older sequence numbers of a key) and expired tombstones, which is what reclaims space and bounds how many files a read must consider.
The architectural core: writes are cheap because they are a memory insert plus a sequential log append, never a random in-place update; durability comes from the WAL, not from where data finally lands; and reads stay fast because compaction keeps each level internally non-overlapping so a key is in at most one file per level, while bloom filters skip almost every file a read would otherwise open. The LSM is that trade made concrete, and compaction is the machinery that keeps the trade from degrading.
Component Deep Dive
The hard parts, each walked from the naive approach to where it breaks to the real design: (1) the write path and memtable plus WAL, (2) the SSTable file format and read path with bloom filters, (3) the compaction strategy - the heart of the design, where read, write, and space amplification are balanced, and (4) deletes, snapshots, and crash recovery.
1. The Write Path: In-Place Updates -> Memtable + WAL + Immutable Flush
The engine takes 200K writes/sec on a dataset 64x larger than RAM. How those writes hit disk decides everything.
Approach A: Update the value where it lives on disk (the B-tree instinct)
Keep a sorted on-disk structure (a B-tree) and, on each put, find the leaf page for the key and rewrite it in place.
put(k, v): find leaf page for k -> read page -> modify -> write page back
Where it breaks:
- A random write per put. Consecutive puts hit scattered keys, so they rewrite scattered 4 KB pages all over the disk. An SSD’s random-write IOPS are a fraction of its sequential bandwidth, and every page rewrite also triggers flash garbage collection and wear. At 200K puts/sec this thrashes - the disk is doing its slowest operation on the hot path.
- Write amplification from page granularity. To change 400 bytes you rewrite a full 4 KB page (10x amplification right there) and, on a split, its neighbors and parent pointers too.
- Durability needs its own log anyway. A page write is not atomic across a crash, so a B-tree also needs a WAL - you pay for the log and still do random writes.
A B-tree is read-optimized and update-in-place. This workload is write-dominated. Wrong tool for the write side.
Approach B: Never update in place - buffer, log, and flush immutable files (the LSM write path)
Stop touching old data on a write. Absorb writes in RAM, make them durable with a sequential log, and flush them to disk in sorted, immutable batches.
- Memtable: an in-memory sorted buffer. All writes go into a skiplist keyed by
(user_key, sequence_number). A skiplist gives O(log n) ordered insert and lookup and is friendly to concurrent readers while a writer mutates it. Keeping it sorted means the eventual flush produces an already-sorted file for free. An overwrite is just a new entry with a higher sequence number; the old one is not removed, it is shadowed. - WAL: durability without random I/O. Before (or as) a write enters the memtable it is appended to the write-ahead log, a pure sequential file. If the process crashes, replaying the WAL rebuilds the exact memtable. The memtable is volatile; the WAL is what makes an acked write safe. Crucially the WAL append is sequential, so durability costs one sequential write, not a random one.
put(k,v):
seq = next_sequence_number()
wal.append(seq, k, v); wal.flush() # sequential, durable
memtable.insert((k, seq), v) # in-memory, sorted
return ACK # ~microseconds, no random disk I/O
- Seal and flush to an immutable SSTable. When the memtable hits its cap, it is frozen (new writes go to a fresh memtable with a new WAL) and a background thread writes it out, in sorted order, as one immutable SSTable at L0 - a single large sequential write. Immutability is the gift: a file never changes after it is written, so readers never need a lock on it, compaction can rewrite copies safely, and backups/snapshots are just file references.
memtable full:
freeze memtable -> immutable memtable (reads still see it)
open new memtable + new WAL segment (writes continue, no stall)
background: write immutable memtable -> L0 SSTable (sorted, sequential)
on success: delete the old WAL segment (its data is now in the SSTable)
The payoff: a user write is a memory insert plus a sequential log append - sub-millisecond, no random I/O - and the disk only ever sees large sequential writes (WAL appends and SSTable flushes). We have converted a random-write workload into a sequential-write workload, which is exactly what SSDs and the storage hierarchy want. The bill comes due on the read side and in background compaction, which the next two sections pay.
2. The Read Path and SSTable Format: Scan Everything -> Bloom Filters + Sparse Index
A key can now live in the memtable, in several L0 files, and once in each lower level. A naive read checks them all. We need reads to touch a small, constant number of files and to avoid disk reads on files that cannot contain the key.
Approach A: Check every file, scan each for the key (naive)
For a get, open every SSTable, binary-search each for the key, return the newest hit.
Where it breaks: with ~1,100 L0 files produced per hour and thousands of files across levels, a single get opens and searches thousands of files - thousands of disk seeks for one key. Even if each file is internally sorted, the sheer file count makes read amplification O(number of files), which grows without bound as the dataset grows. Unusable at TB scale.
Approach B: A structured SSTable format plus bloom filters and a sparse index (the real read path)
Two moves: make each file cheap to search, and make most files skippable without any disk read.
The SSTable layout. An SSTable is a sorted, immutable file with internal structure so a point lookup reads only a few KB, not the whole file:
SSTable file layout:
┌───────────────────────────────────────────────┐
│ Data block 0 (sorted KVs, ~4-64 KB, compressed)│
│ Data block 1 │
│ ... │
│ Data block N │
├───────────────────────────────────────────────┤
│ Bloom filter (over all keys in this file) │ <- "is key maybe here?"
├───────────────────────────────────────────────┤
│ Sparse index (first key of each data block -> │ <- binary-searchable,
│ block offset) │ RAM-resident
├───────────────────────────────────────────────┤
│ Footer (offsets of index + filter, magic, crc) │
└───────────────────────────────────────────────┘
The sparse index holds one entry per data block (the block’s first key and offset), not one per key, so for billions of keys the index is small enough to keep in RAM or the block cache. To find a key: binary-search the sparse index to pick the one block that could hold it, read just that block (a few KB), decompress it, and binary-search within it. One disk read per file actually consulted, not a scan.
The bloom filter - skipping files for free. Most files a read would consider do not contain the key at all. A bloom filter per SSTable answers “is this key possibly in this file?” with no false negatives and a tunable false-positive rate (~1% at ~10 bits/key). The read consults the filter (in memory) first:
get(k) over a candidate SSTable:
if bloom_filter.maybe_contains(k) == false:
skip file entirely # NO disk read - the big win
else:
sparse_index -> block -> read block -> search # one disk read
With a 1% false-positive rate, ~99% of files that do not hold the key are rejected with a pure in-memory check. So even though a key could in principle be in one file per level, the read actually touches disk for only the level(s) where the key (or a rare false positive) lives.
Walking the levels. The read order is newest to oldest, and it stops at the first hit (highest sequence number):
get(k):
1. active memtable (RAM) -> hit? done.
2. immutable memtables (RAM) -> hit? done.
3. L0: files OVERLAP (raw flushes), so check each L0 file (bloom-gated),
newest first. Few files if compaction keeps L0 small.
4. L1..Ln: each level is internally NON-OVERLAPPING and sorted, so a
single binary search over the level's file key-ranges yields AT
MOST ONE candidate file per level (bloom-gated).
-> total files that can hold k: (L0 count) + 1 per lower level
= a small constant (~7-12). Bloom filters make disk reads ~1-3.
This is where the headline read-amplification bound comes from and why L0 is kept small and the lower levels are kept non-overlapping. The invariant “at most one file per level can contain a key” is produced by compaction (next section); without it, reads degrade to O(files). A block cache holds hot data blocks and hot filters/indexes so repeat reads of hot keys never touch disk at all.
3. Compaction: Bounding the Read/Write/Space Trilemma
This is the heart of the design. Flushing alone produces an ever-growing pile of overlapping L0 files; reads degrade and dead data never gets reclaimed. Compaction merges files to maintain the “one file per level” read invariant, reclaim space from overwrites and tombstones, and keep write amplification practical. The strategy chosen decides where you sit in the trilemma.
Approach A: Never compact - just keep flushing L0 files (naive)
Let memtables flush to L0 forever and never merge anything.
Where it breaks on all three axes:
- Read amplification explodes. L0 files overlap, so a
getmust check every one of them. At 1,100 files/hour this is thousands of bloom-checks and many disk reads per get within hours. Reads degrade linearly with dataset age. - Space amplification explodes. A key overwritten a thousand times keeps all thousand versions across a thousand files; a deleted key keeps its old value forever next to its tombstone. On-disk size is many multiples of live data.
- It never converges. There is no mechanism to reclaim dead bytes, so disk fills with garbage.
Flushing without merging is not a storage engine; it is a leak.
Approach B: Size-tiered compaction (write-optimized, but read and space suffer)
Group SSTables into tiers by size; when enough same-size files accumulate (say 4), merge them into one larger file in the next tier. This is Cassandra’s default STCS.
tier 0: [S][S][S][S] -> merge -> tier 1: [ SS ]
tier 1: [SS][SS][SS][SS] -> merge -> tier 2: [ SSSS ]
- Low write amplification. Each byte is rewritten only when its tier fills, roughly
log_T(data/memtable)times - few rewrites, so compaction I/O is modest. Great for write-heavy ingest. - Where it breaks: read and space amplification. Within a tier the large files overlap in key range (each came from an independent merge), so a key can be in multiple big files at once - a
getmay check several files per tier, not one. Worse, during the merge of several ~N-sized files into one ~4N file, the engine transiently holds both the inputs and the output: space amplification can spike to ~2x or more, and the biggest files are the ones that overlap, so a read-heavy workload or a tight disk budget suffers. Size-tiered is the right pick when writes dominate and read latency and disk headroom are secondary, and it is why it is the ingest-optimized option.
Approach C: Leveled compaction (the read- and space-bounded design)
Organize SSTables into levels L1..Ln where each level is internally non-overlapping (the files in a level partition the key space, each file a disjoint key range) and each level is ~T times larger than the one above (T ≈ 10). L0 is the lone exception - it holds raw flushes that can overlap - and is kept small. This is LevelDB’s and RocksDB’s default.
L0: [a-z][a-z][a-z] small, OVERLAPPING (raw memtable flushes)
L1: [a-f][g-m][n-s][t-z] 10 MB total, files DISJOINT, sorted
L2: [a-b][c-d]...[y-z] 100 MB total, files DISJOINT
L3: ... 1 GB total, DISJOINT
... each level 10x the previous
Ln: the bulk of the data (~90% lives in the last level)
The invariant that bounds reads: because every level below L0 is internally non-overlapping, a key can be in at most one file per level. A get therefore does one binary search per level to find the single candidate file, bloom-gated. That is the “small constant number of SSTable lookups per key” from the NFRs, and it holds no matter how large the dataset grows - the level count grows only logarithmically (7 levels covers 4 TB at T=10).
How a leveled compaction runs:
When Li exceeds its size budget:
1. pick one SSTable F from Li (round-robin / oldest / most-overlapping).
2. find all SSTables in Li+1 whose key range OVERLAPS F's range
(a handful, since Li+1 is ~10x but partitioned).
3. merge-sort F with those overlapping Li+1 files:
- keep only the newest version of each key (drop shadowed ones)
- drop tombstones whose deleted data cannot exist in deeper levels
4. write the merged output as new, non-overlapping SSTables into Li+1.
5. atomically update the manifest: add new files, remove inputs.
F's range in Li is now empty; Li shrank, Li+1 absorbed it.
Because you merge one Li file against only the Li+1 files it overlaps, each compaction is a bounded, incremental unit of work - not a rewrite of the whole level. The write-amplification cost is that a byte moving from Li to Li+1 is rewritten alongside the ~T overlapping bytes already in Li+1, so each level transition costs ~T in write amplification, and a byte traverses ~levels transitions over its life. That is the price leveled compaction pays for its read and space wins:
- Space amplification is low (~1.1x). Since ~90% of data lives in the last level and each level is non-overlapping, there is at most one live copy of a key per level, and the last level dominates - so on-disk size is close to live size. Overwrites and tombstones are reclaimed every time a file passes through a merge, which happens continuously. No large transient double-storage like size-tiered’s tier merges (compaction units are small).
- Write amplification is the cost (~10-30x). Rewriting Li+1 overlap on every Li->Li+1 move means a byte is rewritten many times before it reaches the bottom. This is the explicit trade: leveled spends write I/O and SSD endurance to buy bounded reads and tight space.
The trilemma, named. The three strategies sit at different corners:
| Strategy | Read amp | Write amp | Space amp | Best for |
|---|---|---|---|---|
| No compaction | Terrible (O(files)) | None | Terrible | Nothing |
| Size-tiered (STCS) | High (overlap per tier) | Low | High (~2x+ merge spikes) | Write-heavy ingest |
| Leveled (LCS) | Low (~1 file/level) | High (~10-30x) | Low (~1.1x) | Read-heavy, space-tight |
| Tiered+leveled hybrid | Medium | Medium | Medium | Mixed (RocksDB default-ish) |
You cannot win all three. Leveled compaction is the answer when the requirement is bounded read amplification and tight disk usage - which is exactly our NFR (“a small constant number of SSTable lookups per key,” “~1.1x space”) - and we accept higher write amplification, mitigated by keeping compaction I/O sequential and rate-limited. A real engine (RocksDB) often runs a hybrid: size-tiered at L0 (cheap, absorbs the flush firehose) and leveled below (bounded reads for the bulk), getting the best of both at the busiest level.
Keeping compaction from starving foreground traffic. Compaction competes with reads and writes for disk bandwidth. The fixes: rate-limit compaction I/O to a budget, run it on dedicated threads with its own I/O priority, and apply backpressure / write stalls - if L0 grows past a threshold (compaction is falling behind), slow or briefly pause writes so the engine never reaches the unbounded-read-amp state. A healthy engine keeps L0 small; a backed-up L0 is the first warning sign.
4. Deletes, Snapshots, and Crash Recovery
Three correctness concerns that fall out of immutability and must be handled explicitly.
Deletes are tombstones, and tombstones are subtle. You cannot erase a key in place - the key may still exist in older SSTables at lower levels, and the memtable has no idea. So delete(k) writes a tombstone: a marker entry with a sequence number that shadows any older value. A get that finds a tombstone first returns “not found.” A tombstone can only be physically dropped during compaction once it has merged past every level that could hold an older version of the key - drop it too early and an older value in a deeper level gets resurrected. This is why tombstones travel down the levels and are reclaimed only at (or near) the bottom level. A pathological case is a range of many tombstones (a bulk delete): reads and scans must still walk past them until compaction cleans them, so a tombstone-heavy range is slow until merged. Range deletes are stored as a single range tombstone rather than one per key to avoid exactly that.
delete(k): memtable.insert((k, seq), TOMBSTONE) # a write, not a removal
get(k): first entry found (highest seq) is a tombstone -> "not found"
compaction: drop the tombstone only when no deeper level can hold an
older k -> otherwise the old value would RESURRECT.
Snapshots and MVCC come free from sequence numbers. Every write carries a monotonic sequence number, and old versions are shadowed, not overwritten, until compaction reclaims them. A snapshot is just a sequence number S: a read “as of S” ignores any entry with a sequence number greater than S, so it sees a consistent point-in-time view even as writes continue. Because SSTables are immutable, a long scan holds its snapshot by pinning the file set it started with; compaction may produce new files but will not delete versions still visible to an open snapshot (reference-counted). This is how an LSM gives consistent reads and non-blocking scans without read locks - the immutability that makes compaction safe also makes MVCC nearly free.
Crash recovery is WAL replay plus a manifest. Durability does not depend on data reaching an SSTable; it depends on the WAL. On startup:
Recovery:
1. Read the MANIFEST (the durable log of which SSTables exist at which
level, and the last flushed sequence number). This reconstructs the
on-disk LSM shape exactly.
2. Find WAL segments newer than the last flushed sequence number.
3. Replay those WAL records into a fresh memtable, in sequence order.
-> engine is now in its exact pre-crash logical state. Acked writes
(which were WAL-durable before ack) are all present; nothing is lost.
The manifest is itself an append-only log of edits (file added to level, file removed, flush completed), updated atomically on every compaction and flush, so the set of live SSTables and their levels survives a crash mid-compaction - a half-finished compaction’s output files are simply never referenced by the manifest and are garbage-collected. The durability guarantee is precise: a write is safe the instant its WAL append is fsynced, independent of memtables, flushes, or compaction, and recovery deterministically rebuilds everything above the WAL.
API Design & Data Schema
Engine API (embedded, in-process - this is a library, not a service)
An LSM engine is typically embedded (LevelDB/RocksDB are libraries linked into the process above them), so the “API” is a function interface, not HTTP. The distributed KV layer calls these.
Open(path, options) -> DB # options: memtable_size, level fanout T,
# bloom bits/key, block cache size,
# compaction style, wal mode (sync|batch)
Put(key []byte, value []byte, opts) # opts.sync=true -> fsync WAL before ack
-> error # false -> batched fsync (faster)
Get(key []byte, opts) -> (value []byte, found bool, error)
opts.snapshot = <seq> # read as-of a point-in-time snapshot
Delete(key []byte, opts) -> error # writes a tombstone
WriteBatch(ops []Op, opts) -> error # atomic multi-key batch: all ops get
# contiguous seq numbers, one WAL append,
# applied atomically (crash = all or none)
NewIterator(range, snapshot) -> Iter # Seek/Next/Prev over sorted keys;
# merges memtable + all levels on the fly
GetSnapshot() -> seq # pin a consistent read view
ReleaseSnapshot(seq) # unpin (lets compaction reclaim versions)
Flush() # force active memtable -> L0 (e.g. pre-backup)
CompactRange(start, end) # force compaction of a key range
Close()
Notes: WriteBatch is how atomic single-key writes and small transactions are built - contiguous sequence numbers and one WAL append make the batch all-or-nothing across a crash. opts.sync is the durability-versus-latency knob (strict per-write fsync versus batched). Iterators are merging iterators: they open a cursor on the memtable and one per relevant SSTable per level, and merge-sort on the fly so a scan sees the newest version of each key in sorted order.
On-disk and in-memory structures (not SQL - a purpose-built set of files)
This is deliberately not a relational table and not a single B-tree. It is a set of structures each tuned for one job.
The internal key (what is actually stored and sorted):
InternalKey = (user_key, sequence_number DESC, type)
user_key bytes # the caller's key
sequence_number uint64 # monotonic, global; higher = newer
type enum # PUT | DELETE(tombstone) | MERGE | RANGE_DEL
Sort order: user_key ASC, then sequence_number DESC
-> the newest version of a user_key sorts FIRST, so a lookup that
stops at the first match gets the current value. This encoding is
the whole trick behind versioning, snapshots, and deletes.
Memtable (RAM): a concurrent skiplist of InternalKey -> value. O(log n) ordered insert/lookup, lock-light for readers. Sized ~256 MB; sealed and flushed on fill.
SSTable (immutable, on disk):
SSTable {
data blocks : sorted InternalKey->value, ~4-64 KB each, compressed (LZ4/Zstd),
each block prefixed for prefix-key compression
bloom filter : ~10 bits/user_key, ~1% false positive -> skip file w/o disk read
sparse index : one (first_key, block_offset) per data block -> RAM-resident
footer : offsets of index & filter, format version, CRC
}
Why custom / "NoSQL", not a SQL B-tree:
- append-only sequential writes vs random in-place page updates (write amp)
- immutable files -> lock-free reads, free snapshots, safe background merge
- leveled layout bounds read amp to O(levels); B-tree bounds it to O(depth)
too, BUT at the cost of random writes an LSM avoids. For a write-heavy,
larger-than-RAM store, the LSM write path wins decisively.
Write-ahead log (on disk): append-only records (seq, type, key, value), grouped per memtable, fsynced per write or per batch; deleted after its memtable flushes.
Manifest / version set (on disk): an append-only log of version edits - which SSTables live at which level, their key ranges, and the last flushed sequence number. The one structure that must be crash-consistent; it is small (metadata about files, not data) so this is cheap. Everything else (the bulk data) is immutable and reconstructed relative to the manifest.
Level metadata (in RAM, from the manifest):
level[i] = sorted list of { file_id, smallest_key, largest_key, size }
(disjoint ranges for i>=1 -> binary-searchable to ONE file)
level_size_budget[i] = base * T^i (T≈10) # triggers compaction when exceeded
The split is deliberate: a skiplist memtable for fast ordered in-memory writes, immutable SSTables with bloom filters and sparse indexes for bounded-seek reads, a WAL for durability, and a small crash-consistent manifest for the level structure. Each does the one thing it is best at, and immutability ties them together - it is what makes compaction, snapshots, and lock-free reads all simultaneously correct.
Bottlenecks & Scaling
Where it breaks first, in order, and the fix for each.
1. Read amplification as files pile up (breaks first and worst without compaction). Raw flushes produce overlapping files; a get degrades to O(files).
Fix: leveled compaction keeps every level below L0 internally non-overlapping, so a key is in at most one file per level and a get is O(levels) ≈ 7-12 file checks. Bloom filters (~10 bits/key, ~1% FP) then skip ~99% of those files with no disk read, cutting effective disk seeks per get to ~1-3. Keep L0 small so its overlapping files do not dominate.
2. Write amplification and SSD endurance (the cost of leveled compaction). Rewriting Li+1 overlap on every level transition means a byte is written ~10-30x over its life, burning disk bandwidth and flash endurance. Fix: accept it as the trilemma price for bounded reads/space, but cap and rate-limit compaction I/O, use a hybrid (size-tiered L0 to cheaply absorb flushes, leveled below), tune fan-out T (larger T = fewer levels = less write amp but bigger per-level merges), and use SSDs rated for the write volume. Monitor bytes-written amplification as a core metric.
3. Compaction falling behind the write rate. At 200K writes/sec, L0 files arrive every ~3s; if compaction cannot keep pace, L0 grows, read amp spikes, and space balloons. Fix: parallel compaction threads, sub-compactions that split one compaction across cores by key range, and write stalls / backpressure - deliberately slow writes when L0 exceeds a threshold so the engine never enters the unbounded-read-amp regime. A growing L0 is the canary; alert on it.
4. Write stalls and tail latency from flush/compaction pauses. A memtable flush or a big compaction can momentarily block or slow writes, spiking p99. Fix: multiple memtables (a sealed memtable flushes while a fresh one takes writes, so writes never wait on a flush), separate WAL per memtable, and smoothing the write-stall curve (gradually throttle rather than hard-stop). The goal is no cliff: throughput degrades gently under pressure, never to zero.
5. Point lookups for non-existent / cold keys. A get for a key that is not present could, worst case, check one file per level.
Fix: bloom filters are exactly for this - a missing key is rejected at every level by the in-memory filter with zero disk reads. For range/prefix workloads, prefix bloom filters extend the same trick to scan existence checks. Keep hot filters and indexes pinned in the block cache.
6. Tombstone buildup and scan slowdowns. A bulk delete leaves a dense run of tombstones that reads and scans must walk until compaction reclaims them; deleted data can resurrect if a tombstone is dropped too early. Fix: range tombstones for bulk deletes (one marker, not N), tombstone-aware compaction that prioritizes ranges dense in tombstones, and the correctness rule that a tombstone is dropped only once it has merged past every level that could hold an older version - preventing resurrection. Monitor the tombstone ratio per range.
7. Memory pressure between memtable, block cache, and bloom filters. All three want RAM; at 10B keys bloom filters alone are ~12.5 GB and cannot all stay resident. Fix: budget RAM explicitly across the three, keep filters/indexes for hot (upper) levels resident and let the coldest level’s filters page, use block cache for hot data blocks, and consider ribbon/partitioned filters (more bits-efficient than classic blooms) to shrink the filter footprint. This split is a primary tuning axis.
8. A single hot key or hot key-range. One key read or written far more than others concentrates load on its file(s) and its compaction. Fix: the block cache absorbs hot reads (a hot key serves from RAM and never touches an SSTable); hot writes are already cheap (memtable + WAL). A hot key-range that dominates compaction can be isolated into its own column family (independent memtable/levels/compaction) so its churn does not stall unrelated data. True single-key hotspotting is handed to the distributed layer above (sharding, caching), outside this engine’s scope.
9. Crash during compaction or flush. A crash mid-merge could leave orphan files or an inconsistent level structure.
Fix: the manifest is the single source of truth, updated atomically - new compaction output is referenced only after it is fully written and fsynced, so a crash leaves orphan files that are simply garbage-collected (never referenced), and the pre-crash structure is intact. WAL replay restores any un-flushed memtable. No acked write is ever lost because WAL durability precedes ack.
10. Scaling past one node. A single node caps at its disk and its compaction throughput.
Fix: this engine is intentionally the per-node storage layer; horizontal scale is the job of the layer above (consistent hashing, sharding, replication) that embeds one of these engines per shard. The clean Put/Get/Delete/Scan/Snapshot/WriteBatch interface is precisely what that distributed layer builds on. Keeping the engine single-node and sharp is what lets the distributed layer stay simple.
Wrap-Up
The trade-offs that define this design:
- Never update in place; buffer, log, and flush immutable files. We trade random in-place writes (which we do not need) for a memtable insert plus a sequential WAL append, converting a write-heavy, larger-than-RAM workload into sequential-only disk I/O - the single reason an LSM beats a B-tree here. The cost, paid deliberately, is that a key lives in multiple files and background merging rewrites data.
- Leveled compaction over size-tiered, buying bounded reads and tight space with write amplification. Keeping every level non-overlapping bounds a
getto a small constant number of SSTable lookups (the headline goal) and keeps on-disk size near live size (~1.1x), at the price of ~10-30x write amplification. Size-tiered would flip that - cheap writes, costly reads and space - which is the right pick only for write-dominated ingest. Naming this trilemma and picking the corner is the core of the answer. - Bloom filters make the read bound nearly free. Even “at most one file per level” would mean several disk seeks per
get; a per-file bloom filter rejects ~99% of non-matching files with an in-memory check, so effective disk seeks pergetdrop to ~1-3 regardless of dataset size. - Immutability pays for itself three times. Immutable SSTables make compaction safe to run in the background, make snapshots and MVCC nearly free (old versions are shadowed, not overwritten, until reclaimed), and make reads lock-free - one property, three wins.
- Durability lives in the WAL and the manifest, not in where data lands. An acked write is safe the instant its WAL append is
fsynced; crash recovery deterministically replays the WAL on top of the manifest-described level structure, and orphaned mid-compaction files are harmlessly collected. This decouples the durability guarantee from the entire compaction machinery.
One-line summary: an LSM key-value engine absorbs writes into an in-memory skiplist memtable backed by a sequential write-ahead log, flushes them as immutable sorted SSTables, and runs leveled compaction to keep each level internally non-overlapping - so a get touches at most one bloom-filter-gated file per level - trading higher write amplification for bounded read amplification and near-1.1x space amplification on datasets far larger than RAM.
Comments