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:

  1. Freeze it. The full memtable becomes immutable: no more writes go into it, but reads still search it.
  2. Start a new one. A fresh, empty mutable memtable takes over, and writes continue into it without a break.
  3. 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
FieldPoints toIn the exampleLives inAfter a crash, rebuilt from
memThe one mutable memtableM3RAMThe WAL
immThe list of immutable memtables (zero or more)[IM2, IM1]RAMThe WAL
currentThe current Version: which SSTable files are part of the database, per levelV1 = {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.

Ownership map. In RAM: the engine’s shared state holds one global pointer per column family, to the current SuperVersion, the bundle of what is readable now. The SuperVersion points at exactly one mutable memtable, where all new writes land; a list of zero or more immutable memtables, frozen and awaiting flush; and the current Version, the list of live SSTables per level. On disk: the Version names the SSTable files that are part of the database. After a crash the RAM side is gone: the WAL is replayed to rebuild both memtables, and the MANIFEST is replayed to rebuild the Version.
Every live object hangs off one pointer — the disk side only rebuilds it

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).

The SuperVersion SV1 on the heap, with ref_count equal to 3. Its fields: mem points to mutable memtable M3; imm points to the immutable list IM2, IM1; current points to Version V1, the SSTable list. Three holders point at SV1: Read A and Read B through local pointers on their stacks, and the engine through the shared pointer. A read changes only SV1's counter.
SV1 while two reads are using it: one object, one counter, three holders

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.

VersionMANIFEST
What it isA list of live SSTable files per level, as of one momentAn append-only log of every change to that list: "+8", "+9 −4 −5", …
Lives inRAMDisk (one per database)
Who uses itEvery readOnly startup, to rebuild the Version
Survives a crash?NoYes
AnalogyToday's catalog cardThe 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 → 1
Read path while a flush is in progress, newest to oldest. First the mutable memtable, where new writes land; then the immutable memtable, frozen to writes and fully readable in RAM; then the SSTables the current Version names, newest to oldest. The read stops at the first hit. The SSTable being flushed from the immutable memtable is not named by any Version, so it is not on the path. A miss all the way down means the key does not exist.
Newest to oldest, stop at the first hit — the file being flushed is not on the path

The 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 points current_sv at a new SuperVersion, the read's sv still 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

StepWhat happensWhereCan new reads see it?
1Write IM1's contents into a new file, SST 8, block by blockDiskNo. No Version names file 8, so reads don't know it exists
2fsync file 8DiskNo
3Append "+8" to the MANIFEST and fsync. This is the commit.DiskNo. Reads never look at the MANIFEST
4Build Version V2 = {8, 7, 6, 5, 4} and a new immutable list [IM2]RAMNo. Nothing points to them yet
5Build SV2 = { mem: M3, imm: [IM2], current: V2 }RAMNo
6Swap current_sv from SV1 to SV2RAMYes, 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.

A grid of five moments in a flush against three places a key can be read from. Before the flush trigger: the mutable memtable. After the trigger: the immutable memtable, frozen but fully in RAM. During the flush to disk: still only the immutable memtable, because the half-written SSTable is not in the Version and no read can see it. At the swap: both, for one instant — the new Version names the SSTable while the memtable is still pinned. After the flush completes: the new SSTable; the memtable is dropped once the last read holding it finishes. Every row has at least one readable source.
Where one key is readable from, moment by moment — never nowhere

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:

EventmemimmcurrentIn the example
The mutable memtable fills upnew empty oneold mem added at the frontsamewould give { M4, [M3, IM2], V3 }
A flush finishessameflushed memtable removednew: one file addedSV1 → SV2
A compaction finishessamesamenew: files mergedSV2 → 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

Timeline. At t0 Read R copies the shared pointer to SV1 and starts walking IM1. At t1 the flush finishes and the engine swaps the pointer to SV2, which no longer lists IM1. At t2 Read R is still inside IM1. Two questions: which state is Read R using, answered by its private copy of the SV1 pointer; and is IM1 still there, answered by reference counts.
Event 1 happens while Read R is still inside IM1

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 onCountsChanges when
A SuperVersionReads using it, plus 1 for the engine if it is the current oneEvery read starts and ends: thousands of times a second
Everything below it: memtables, immutable lists, Versions, SSTable filesThe 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:

ObjectHeld byref_count
SV1Read R1
SV3the engine1
M3SV1, SV32
list [IM2, IM1]SV11
list [IM2]SV31
IM2both lists2
IM1list [IM2, IM1]1
V1 / V3SV1 / SV31 each
files 4, 5V11
files 6, 7V1, V32
files 8, 9V31

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 disk
Reference count of SV1 across six events. SV1 is current and the engine holds it: 1. Read A starts and pins it: 2. Read B starts: 3. The swap to a new SuperVersion drops the engine reference: 2, not freed. Read A finishes: 1. Read B finishes: 0, and SV1 is freed, releasing everything it points to. Between the swap and the last read finishing, SV1 is in limbo: unreachable by new reads but alive.
SV1’s counter: the swap only drops the engine’s reference — the last read out frees SV1

So 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.