Memtable, Flush, and Ref-Counting
This whole section follows one example. the SSTables and sparse indexes part sets up a SuperVersion called SV1. The WAL part starts a read on it. The Concurrency, tombstones and compaction part changes the database twice (a flush, then a compaction) while that read is still running. The Bloom filters part and Compaction strategies show how SV1's memtables and files are kept alive for that read, and exactly when each one is freed or deleted. Read it in order.
Depth beyond this part: The WAL part covers the WAL that makes the memtable durable, and crash recovery shows what the WAL and MANIFEST restore after a crash.
1 · Memtables and flushing
A memtable is a sorted structure in RAM (usually a skip list) that holds every recent write not yet on disk. Every read checks it first, because RAM is fast and the memtable has the newest data. Because it is already sorted, writing it out to disk produces a sorted SSTable file directly.
What happens when it fills up
When the memtable reaches its size limit (often 64 MB), the database does not pause:
- Freeze it. The full memtable becomes immutable: no more writes go into it, but reads still search it.
- Start a new one. A fresh, empty mutable memtable takes over, and writes continue into it without a break.
- Flush in the background. A background thread writes the immutable memtable out as a new SSTable file.
There can be several immutable memtables. If writes are faster than flushing, frozen memtables queue up waiting their turn. LevelDB allows only one (if a second one is needed, writes wait). RocksDB keeps a list of them, newest first, up to a configured limit (max_write_buffer_number counts all memtables, mutable included). When the list is full, writes stall (see below).
2 · The running example: one SuperVersion
So at any moment a read may need to search three kinds of thing: the mutable memtable, the immutable memtables, and the SSTable files. RocksDB lists all three in one small object, the SuperVersion, and keeps one shared pointer to the current one. Here is the example used for the rest of this part:
the running example — SV1
current_sv ──► SV1 ref_count = 1 (the engine)
├─ mem → M3 mutable memtable · new writes land here
├─ imm → [IM2, IM1] immutable memtables · frozen, waiting to flush · newest first
└─ current → V1 Version: the live SSTable files = 7, 6, 5, 4| Field | Points to | In the example | Lives in | After a crash, rebuilt from |
|---|---|---|---|---|
mem | The one mutable memtable | M3 | RAM | The WAL |
imm | The list of immutable memtables (zero or more) | [IM2, IM1] | RAM | The WAL |
current | The current Version: which SSTable files are part of the database, per level | V1 = {7, 6, 5, 4} | RAM (the files themselves are on disk) | The MANIFEST (see below) |
Field names are RocksDB's real ones (mem, imm, current, plus a refs counter). current_sv is this guide's name for the shared pointer. LevelDB has no SuperVersion: it keeps mem_, imm_ and the current Version as three separate fields, but the ideas below are the same.
Why bundle all three behind one pointer?
A read needs all three from the same moment. With three separate pointers, a read could grab the memtable list just before a flush finishes and the file list just after it, and miss a key that moved from one to the other in between. With one pointer to one bundle, "the current state" is a single object that changes in a single step, so there is no in-between moment to catch. It also means a read takes one reference instead of three (see below).
3 · Version and MANIFEST: how a file becomes part of the database
An LSM engine never finds its SSTables by listing the data directory. A file is part of the database only if the current Version lists it. In the example, files 7, 6, 5 and 4 are in the database because V1 names them, not because they are on disk.
| Version | MANIFEST | |
|---|---|---|
| What it is | A list of live SSTable files per level, as of one moment | An append-only log of every change to that list: "+8", "+9 −4 −5", … |
| Lives in | RAM | Disk (one per database) |
| Who uses it | Every read | Only startup, to rebuild the Version |
| Survives a crash? | No | Yes |
| Analogy | Today's catalog card | The librarian's ledger, written in ink |
Why not just list the directory? Because after a crash the directory can contain junk. If the engine crashes in the middle of a compaction that merges 4 and 5 into 9, all three files may be on disk, and nothing about file 9 says whether it was finished. The MANIFEST decides: if the record "+9 −4 −5" reached disk, the compaction happened; if not, it didn't, and file 9 is leftover junk to delete. On restart, the engine replays the MANIFEST from start to end to rebuild the Version.
A Version is never edited. Adding or removing files means building a new Version. That is why several Versions can be alive at once: the current one, plus older ones that running reads still use (see below). RocksDB calls the collection of all live Versions the VersionSet.
4 · How a read uses the SuperVersion
Start a read, Read R, on SV1. Here is everything it does:
Read R
sv = current_sv; // 1. copy the shared pointer once → sv = SV1
sv->ref_count++; // 2. pin it → SV1: 1 → 2
search sv->mem // 3. M3
search sv->imm // 4. IM2, then IM1 (newest first)
search sv->current // 5. files 7, 6, 5, 4 (newest first)
// stop at the first hit
sv->ref_count--; // 6. unpin → SV1: 2 → 1The search stops at the first hit, because everything further along is older. If the key is not found anywhere, it really does not exist: there is nowhere else to look.
The one rule: read the shared pointer once, at the start, and never again. Step 1 copies the address of SV1 into the read's own local variable
sv(8 bytes, nothing else is copied). If the engine later pointscurrent_svat a new SuperVersion, the read'ssvstill says SV1, because a swap of the shared pointer cannot reach another thread's local variable. So the read sees one consistent state from start to finish, and holds no lock while it searches. (Taking the copy is a tiny step: LevelDB holds a mutex for just that instant, and RocksDB usually avoids even that by caching the SuperVersion per thread.)
5 · Changing state: publish a new SuperVersion
While Read R is still running, two things happen. Both follow the same recipe: build the new objects off to the side, build a new SuperVersion that points at them, then swap current_sv to it. Nothing that already exists is edited.
Event 1: the flush of IM1 finishes
| Step | What happens | Where | Can new reads see it? |
|---|---|---|---|
| 1 | Write IM1's contents into a new file, SST 8, block by block | Disk | No. No Version names file 8, so reads don't know it exists |
| 2 | fsync file 8 | Disk | No |
| 3 | Append "+8" to the MANIFEST and fsync. This is the commit. | Disk | No. Reads never look at the MANIFEST |
| 4 | Build Version V2 = {8, 7, 6, 5, 4} and a new immutable list [IM2] | RAM | No. Nothing points to them yet |
| 5 | Build SV2 = { mem: M3, imm: [IM2], current: V2 } | RAM | No |
| 6 | Swap current_sv from SV1 to SV2 | RAM | Yes, from this instant |
Only step 6 changes anything a read can see, and it is a single pointer write. So a read sees either SV1 (the data is in IM1) or SV2 (the data is in file 8), never a state where IM1 is gone but file 8 is not listed yet.
Event 2: a compaction merges files 4 and 5 into file 9
Same recipe. Write file 9, fsync it, append "+9 −4 −5" to the MANIFEST, build V3 = {9, 8, 7, 6}, build SV3 = { mem: M3, imm: [IM2], current: V3 }, swap current_sv to SV3. Files 4 and 5 are not deleted here. They are only dropped from the new Version.
The three events, side by side
Only three events ever publish a new SuperVersion. Each one replaces one or two fields and copies the rest unchanged:
| Event | mem | imm | current | In the example |
|---|---|---|---|---|
| The mutable memtable fills up | new empty one | old mem added at the front | same | would give { M4, [M3, IM2], V3 } |
| A flush finishes | same | flushed memtable removed | new: one file added | SV1 → SV2 |
| A compaction finishes | same | same | new: files merged | SV2 → SV3 |
Where things stand now: the engine points at SV3. Read R is still running on SV1, which still lists IM1 and files 4 and 5. The next two sections answer: what keeps those alive for Read R, and when do they finally go away?
6 · Keeping old state alive: reference counts
Read R's private copy of the pointer (see above) answers which state it sees: SV1, all the way through. It does not keep SV1 in memory. A copied address is just a number; if the engine freed SV1 and IM1 at the swap, Read R would be reading freed memory. Copying a pointer pins nothing. Keeping things alive is the job of reference counts.
The rule: every arrow is one reference
Each object has a counter (ref_count) stored inside the object itself, counting how many things point at it. An object is freed when its counter reaches zero, and never before. Here is everything that points at what, at this moment:
who holds what — engine on SV3, Read R still on SV1
Read R ──► SV1 ──┬─► M3
├─► list [IM2, IM1] ──► IM2, IM1
└─► V1 ──► files 7, 6, 5, 4
engine ──► SV3 ──┬─► M3
├─► list [IM2] ──► IM2
└─► V3 ──► files 9, 8, 7, 6(SV2 is already gone. The moment the engine swapped to SV3, nothing held SV2 any more, so it was freed at once. Everything it pointed at is also pointed at by SV1 or SV3, so nothing else was freed with it.)
Two kinds of counter
| Counter on | Counts | Changes when |
|---|---|---|
| A SuperVersion | Reads using it, plus 1 for the engine if it is the current one | Every read starts and ends: thousands of times a second |
| Everything below it: memtables, immutable lists, Versions, SSTable files | The objects above it that point at it (SuperVersions, lists, Versions) | Only when a SuperVersion, list or Version is created or freed: rare |
A read only ever touches the SuperVersion's counter. It adds 1 at the start and subtracts 1 at the end. It never touches the counters on memtables, Versions or files. Those only move when a SuperVersion is born (it takes a reference on each thing it points to) or dies (it gives them back).
The counts in the example right now:
| Object | Held by | ref_count |
|---|---|---|
| SV1 | Read R | 1 |
| SV3 | the engine | 1 |
| M3 | SV1, SV3 | 2 |
| list [IM2, IM1] | SV1 | 1 |
| list [IM2] | SV3 | 1 |
| IM2 | both lists | 2 |
| IM1 | list [IM2, IM1] | 1 |
| V1 / V3 | SV1 / SV3 | 1 each |
| files 4, 5 | V1 | 1 |
| files 6, 7 | V1, V3 | 2 |
| files 8, 9 | V3 | 1 |
7 · When memtables are freed and files deleted
Now Read R finishes and runs sv->ref_count--. SV1's counter goes from 1 to 0, and a chain of releases follows. Each object, when it reaches zero, gives back the references it holds:
Read R finishes → SV1 reaches 0
SV1: 1 → 0 → free SV1, release what it points to:
M3: 2 → 1 SV3 still holds it → stays
list [IM2, IM1]: 1 → 0 → free the list, release its memtables:
IM2: 2 → 1 list [IM2] still holds it → stays
IM1: 1 → 0 → FREE IM1 from RAM
V1: 1 → 0 → free V1, release its files:
files 7, 6: 2 → 1 V3 still names them → stay
files 5, 4: 1 → 0 → DELETE files 4 and 5 from diskSo a file is deleted when no live Version names it, and a memtable is freed when no live SuperVersion or list holds it. Files 4 and 5 stayed on disk after the compaction (event 2) for exactly as long as Read R needed them, and not a moment longer. (In RocksDB the actual file deletion is done by a background cleanup step shortly after the count reaches zero.)
8 · Write stalls and backpressure
Nothing above blocks writes: publishing a new SuperVersion is one pointer swap. Writes stall only when background work falls behind:
- Too many immutable memtables are queued in RAM waiting to be flushed
- Level-0 SSTables pile up faster than compaction can merge them
- Compaction in general cannot keep up with incoming writes
The engine then applies backpressure: it slows down or pauses writes until background work catches up. Reads usually continue as normal.
The Invariants
- Guarantees: No read ever sees a half-written SSTable, a half-swapped state, or freed memory, and no read is ever blocked by a flush or compaction.
- Does not guarantee: Bounded RAM and disk while old SuperVersions are pinned (old and new state coexist), or that writes never stall: backpressure is a real, deliberate pause when background work falls behind.