Concurrency, Tombstones, and Compaction
Concurrent reads and writes on the memtable
Scenario: a read is in progress on the memtable when a write arrives for the same key.
Naive approach: the read returns whatever value happens to be in memory at that instant — old or new, unpredictably. Most databases avoid this.
What LSM engines actually do: the memtable does not overwrite the old value. It inserts a new version alongside it, tagged with a higher sequence number:
memtable (internally):
user:42 seq=5 "alice" ← old
user:42 seq=9 "alice2" ← new writeEvery read is handed a snapshot sequence number at the moment it starts, and sees only versions with seq ≤ its snapshot:
Thread A (read) starts at seq=5
Thread B (write) gets seq=9
Thread A reads user:42 → latest version where seq ≤ 5 → returns "alice"The memtable is not a hashmap where writes overwrite in place. It stores multiple versions per key, and reads filter by sequence number — which is what makes the concurrent write invisible rather than racy.
Deep dive: two separate guarantees are at work
Sequence-number filtering answers "which version does a read see." It does not answer a more basic question: while a read is physically walking the skip list, new nodes are being spliced into that very list — how does the walk not crash or read garbage? Two different layers:
| Layer | What it guarantees | Mechanism |
|---|---|---|
| A — Structural | Traversal never sees a corrupted or half-built node | Lock-free skip list + atomic pointer publication |
| B — Logical | Read sees a consistent point-in-time snapshot | Sequence-number filtering |
Layer A makes the walk safe. Layer B makes the result correct.
Layer A — inserting into a skip list without locking out readers
A memtable insert never edits an existing node and never removes one. It only adds. That single property is what makes lock-free reads possible:
The node is fully built before it is linked in, and linking it in is a single atomic write. A reader following a next pointer either reads it before the splice (the new node simply isn't there yet) or after (the new node is fully formed). There is no third case. And because existing nodes are never mutated after being linked in, a reader already past some point is never disturbed by something changing behind it.
Writer concurrency: RocksDB's default path serializes writers behind a mutex — one writer splices at a time — but that mutex is only between writers; readers never take it. With allow_concurrent_memtable_write, multiple writer threads splice concurrently using CAS loops instead. Either way the guarantee handed to readers is identical.
Layer B — why it doesn't matter which new nodes a read sees
Layer A only promises the walk won't crash. It says nothing about which of 100 concurrent inserts a given read encounters. That race is real and stays unresolved at the structural level — which is fine: every read captured a snapshot seq at the start, and every node carries its own seq. A node inserted mid-read always has a seq greater than the read's snapshot, so it is filtered out whether or not the traversal happened to pass through it.
| Layer A (structural) | Layer B (logical) | |
|---|---|---|
| Protects against | Torn / corrupted reads | Inconsistent snapshots |
| How | Atomic pointer publish, append-only nodes | Sequence-number filter, per read |
| Scope | The skip list, generically | This engine's MVCC design specifically |
The pointer to the memtable is frozen for a read's whole lifetime (ref-counted, via SuperVersion — see Memtable, flush and ref-counting). The contents of that memtable are deliberately not frozen; new writes keep landing in it throughout the read. Safety of walking a moving structure comes from Layer A; correctness of the answer despite it moving comes from Layer B.
What exactly is a snapshot, and where is it tracked?
A snapshot is nothing more than a frozen sequence number. Not a copy of data, not a pointer — just an integer handed to a read when it starts, held until it finishes:
Read starts → engine hands back the current seq (say 7)
Read's snapshot = 7
... read compares every key's version seq against 7 for its whole lifetime ...
Read finishes → the number 7 is discarded, no longer "held" by anyone"Active snapshot" just means: some read is currently in flight, holding one of these numbers open.
Where the list of held snapshots lives: entirely in RAM inside the storage-engine process. Never on disk, never in the WAL. It doesn't need to survive a crash — if the process dies, every in-flight read dies with it, so there is nothing to recover.
The structure (RocksDB's actual choice): a small doubly-linked list of held sequence numbers, guarded by a mutex since threads open and close snapshots concurrently.
| Operation | What happens | Cost |
|---|---|---|
GetSnapshot() (read starts) | Read the current global seq counter, wrap it in a node, insert at the tail | O(1) |
ReleaseSnapshot() (read finishes) | Unlink that node | O(1) — the read kept a pointer to its own node, no search |
| Find oldest active snapshot (compaction) | Peek at the head | O(1) |
Because sequence numbers only ever increase, a newly-created snapshot is always ≥ every existing one — so appending at the tail keeps the list sorted for free, which is what makes "find the oldest" an O(1) head peek rather than a scan.
When compaction actually reads this: once per compaction job, not once per key. Before merging a set of SSTables it peeks at the head to get a single oldest_snapshot, then reuses that number for every key in the pass. That is why a version a snapshot is protecting only gets cleaned up "on the next compaction pass," not the instant the snapshot is released.
Why a doubly-linked list — not a heap, sorted array, or hashmap?
The hard requirement is O(1) removal of an arbitrary snapshot from the middle. Reads don't finish in FIFO order — a long-running read can outlive many reads that started after it — so release must work at any position.
| Structure | Insert | Release (remove from middle) | Find oldest |
|---|---|---|---|
| Sorted array | O(1) amortized (append) | O(n) — shift everything after | O(1) — head |
| Min-heap | O(log n) | O(log n) for the root; an interior node needs a seq→position index just to locate it | O(log n) |
| Hashmap / set of seqs | O(1) | O(1) | O(n) — scan for the min |
| Balanced BST | O(log n) | O(log n) | O(log n) |
| Doubly-linked list | O(1) — append at tail | O(1) — unlink via the node's own pointers | O(1) — peek head |
It wins by exploiting the monotonic-seq invariant: new snapshots always belong at the tail (no comparison needed to place them), which makes the list sorted as a free side effect. GetSnapshot() hands back a pointer to the node it created; ReleaseSnapshot() unlinks directly via that pointer. That last point is exactly why it must be doubly linked — unlinking a middle node requires touching its predecessor, and a singly-linked list can't reach backward without an O(n) scan from the head, which would defeat the whole design.
Multiple versions, flush, and tombstones
During flush, both versions are written to the SSTable as-is. The flush cleans nothing up; it moves the memtable to disk faithfully:
| Phase | What happens to old versions |
|---|---|
| Flush | Both versions written to the SSTable, nothing dropped |
| Compaction | Versions below the oldest active snapshot are dropped |
During compaction the engine checks the oldest active snapshot: if no read still holds seq=5, drop "alice" and keep only "alice2"; if a read is still alive at seq=5, keep both until it finishes.
How deletes actually work: tombstones
A delete is not an in-place removal — SSTables are immutable and can never be modified. A delete is a new write carrying a tombstone marker at a higher sequence number:
user:42 seq=5 "alice" ← original write
user:42 seq=9 "alice2" ← update
user:42 seq=14 TOMBSTONE ← deleteWhat reads see: a read at seq=15 finds the tombstone (highest seq ≤ 15) and returns "key not found" — even though the old data is still physically on disk.
What compaction does when it sees all versions of a key together: if no active snapshot holds a seq older than the tombstone, drop all versions including the tombstone itself — the key is fully gone from the merged output. If a read is alive at an older seq, keep the versions that snapshot needs and drop the rest on a later pass.
Compaction: merging SSTables
As SSTables accumulate, reads get slower (more files to check) and disk fills with stale duplicates. Compaction is a background process that picks a set of SSTables, merges them into a new one keeping only the latest value per key, and deletes the originals.
Sparse index recovery on restart
On startup the database does not reconstruct sparse indexes. It reads the pre-stored indexes out of the SSTable footers into RAM — a fast metadata read, not a block scan. This is the structural fix for the Log and hash index part's "slow restart" problem: hash maps require replaying millions of log entries; SSTables carry their own index with them.
How compaction swaps files without disturbing reads
Exactly the same way a flush does. This is Memtable, flush and ref-counting, event 2 (files 4 and 5 merged into file 9), so here is only the short version:
- Write the merged file and
fsyncit. No Version names it yet, so reads cannot see it. - Append "+9 −4 −5" to the MANIFEST and
fsync. This is the commit. - Build a new Version and a new SuperVersion, then swap the shared pointer. New reads now use file 9.
- Reads still holding the old SuperVersion keep using files 4 and 5. When the last one finishes, no live Version names those files, so they are deleted (see Memtable, flush and ref-counting).
The one point worth adding here: the MANIFEST and the reference counts do different jobs. The MANIFEST records "files 4 and 5 are removed" immediately, at step 2, so after a crash they are not part of the database. The files themselves stay on disk until the reference counts say no read still needs them. The MANIFEST answers "what is real after a restart?"; reference counts answer "can this file be deleted right now?". The MANIFEST knows nothing about reads, and reference counts are lost on a crash, which is fine, because after a restart no old reads exist.
Crash recovery: what gets kept vs deleted
Two independent mechanisms recover two independent kinds of data. There is no single "recovery log" — it's WAL for RAM state and MANIFEST for on-disk file state:
| What could be lost | Recovered via | How |
|---|---|---|
| Memtable data (RAM only, not yet flushed) | WAL | Replay from the start; each entry checksummed, replay stops at the first torn entry |
| Which SSTable files are "real" (some on disk may be orphaned mid-write) | MANIFEST | Read the append-only log of every committed SSTable addition/deletion |
- Crash before WAL fsync — the client was never told "success," so there is nothing to recover; the write simply didn't happen.
- Crash after WAL fsync, before flush — the memtable existed only in RAM and is gone. Replay the WAL to rebuild it exactly. The WAL is never discarded until after a flush succeeds, so this replay is always possible.
- Crash mid-flush — the new SSTable was a temp file not yet in the MANIFEST, so it's ignored/deleted on restart: it was never "real." Meanwhile that data's WAL is still on disk, so it replays and the flush is effectively retried later.
- Crash mid-compaction — same idea. The new merged SSTables aren't in the MANIFEST, so they're orphaned garbage. The MANIFEST still reflects the old SSTable set, so the engine keeps serving from those. No data lost — just wasted compaction work.
The MANIFEST is the single source of truth for "what files exist" after a crash — not the directory listing, and not ref counts. Ref counts are pure RAM/live-query bookkeeping; they evaporate on crash and were never meant to survive one. Anything on disk the MANIFEST doesn't list is garbage, no matter how far its write got.
The full flow, end to end
The Invariants
- Guarantees: A read sees a consistent point-in-time view, never a corrupt structure, and never blocks a writer — and after a crash, exactly the acknowledged writes plus exactly the MANIFEST-listed files.
- Does not guarantee: That a deleted key's bytes are gone from disk (the tombstone only hides it until compaction), or that a released snapshot frees space promptly — cleanup waits for the next compaction pass.