Sub topic 2
The Single-Node Storage Engine: WAL, Memtable, and SSTables
This chapter assumes you know hash maps, sorted lists, binary search, and basic file I/O, and that you can read short Python snippets. Everything here happens on one machine. Later chapters spread the same engine across a cluster.
Why a storage engine comes first
Every node in a distributed key-value store needs a local place to keep its share of the data. The cluster-level design decides which node owns a key. The storage engine decides how that node saves and finds it. A slow or fragile engine limits the whole cluster, however good the replication is.
The engine must meet three goals:
- Durability: an acknowledged write survives a process crash or power loss.
- Fast writes: the target workload writes constantly, so writes should avoid random disk I/O.
- Reasonable reads: a read should touch few files.
The log-structured merge tree (LSM tree) meets these goals. Cassandra, RocksDB, LevelDB, and HBase use it. It has three parts: a write-ahead log, a memtable, and sorted string tables.
The three components
- Write-ahead log (WAL): an append-only file. Each write is recorded here before anything else happens. Appending sequentially is the cheapest disk operation.
- Memtable: an in-memory sorted structure (often a skip list or balanced tree) holding recent writes. Reads check it first.
- SSTable (sorted string table): an immutable file of key-value pairs sorted by key. When the memtable fills, it is written out as a new SSTable.
The write path
- Append a record to the WAL.
- Force it to disk with
fsync. - Update the memtable.
- Acknowledge the client.
The order matters. If the process crashes after step 2, the memtable is lost but the WAL still holds the write. If you updated the memtable first and crashed before logging, you would lose a write you may already have acknowledged.
The fsync call is the costly step, because it waits for the storage device. Engines offer a policy choice here:
| Policy | Durability | Cost |
|---|---|---|
| fsync on every write | No acknowledged write is lost | Highest latency |
| Group commit (one fsync covers many concurrent writes) | Same as above | Better throughput, slight added latency |
| fsync on a timer (for example every 10 ms) | Can lose the last interval of writes | Lowest latency |
In a replicated store, a timer-based policy is sometimes acceptable because other replicas hold the data. That is a decision to make deliberately, and a later chapter on quorums returns to it.
Flushing to an SSTable
When the memtable reaches a size limit, the engine writes its contents in key order to a new file. It writes to a temporary name, calls fsync, then renames the file into place. A rename is atomic on POSIX file systems, so a crash never leaves a half-written SSTable under its real name. After the rename, the old WAL is no longer needed and can be truncated.
SSTables are never modified. New data creates new files, and this is what keeps writes sequential. The file is sorted, so an index of keys to byte offsets lets a reader binary-search and then seek once. Large engines keep a sparse index (one entry per block) rather than one per key.
The read path
A read checks the memtable, then SSTables from newest to oldest. The first match wins, because newer files hold newer values. A key that exists nowhere forces the engine to check every file, which is the expensive case. Two techniques reduce this:
- Bloom filters: a compact in-memory structure per SSTable that answers "definitely not here" or "maybe here". It never gives a false negative, so a "no" lets the engine skip the file.
- Compaction: described below.
Deletes and tombstones
Because SSTables are immutable, a delete cannot remove a key from an old file. Instead the engine writes a tombstone, a marker meaning "this key is deleted". Reads that find a tombstone stop and report the key as missing, without checking older files.
The tombstone must stay until it has shadowed every older copy of the key. Dropping it too early makes a deleted value reappear. This problem becomes sharper with replication: if one replica discards a tombstone before another replica learns of the delete, repair can copy the old value back. Cassandra handles this with a grace period (gc_grace_seconds) before tombstones are purged.
Compaction
Over time SSTables pile up, and reads get slower. Compaction merges several SSTables into one. Because each input is already sorted, this is a streaming k-way merge. For each key it keeps only the newest version and drops overwritten values and, once safe, tombstones.
Two common strategies:
- Size-tiered: merge files of similar size. Writes are cheap, but reads may check many files and space use can spike during a merge.
- Leveled: keep files in levels with non-overlapping key ranges, so a read checks about one file per level. Reads and space use are better, but the engine rewrites data more often.
The cost of rewriting data is called write amplification: one logical write causes several physical writes over its lifetime. Compaction trades this cost for lower read cost.
Recovery on startup
After a crash the engine does the following:
- Open the existing SSTables.
- Read the WAL from the start and re-insert each record into a fresh memtable.
- Stop at the first record that fails to parse. A crash during an append can leave a partial final record, and it was never acknowledged, so discarding it is safe.
Production WALs add a checksum to every record, so corruption in the middle of the file is detected rather than silently accepted.
A working sketch
This program implements the whole write and read path in about 80 lines. For brevity it has no compaction or Bloom filter, and it uses None as the tombstone, so you cannot store None as a real value.
import bisect
import json
import os
import tempfile
class SSTable:
def __init__(self, path):
self.path = path
self.keys = []
self.offsets = []
offset = 0
with open(path, "rb") as f:
for line in f:
self.keys.append(json.loads(line)["k"])
self.offsets.append(offset)
offset += len(line)
def get(self, key):
"""Return (found, value). A found value of None is a tombstone."""
i = bisect.bisect_left(self.keys, key)
if i == len(self.keys) or self.keys[i] != key:
return False, None
with open(self.path, "rb") as f:
f.seek(self.offsets[i])
return True, json.loads(f.readline())["v"]
class MiniLSM:
def __init__(self, directory, memtable_limit=4):
self.dir = directory
self.limit = memtable_limit
os.makedirs(directory, exist_ok=True)
names = sorted(n for n in os.listdir(directory) if n.endswith(".sst"))
self.tables = [SSTable(os.path.join(directory, n)) for n in names]
self.next_id = len(names)
self.memtable = {}
self.wal_path = os.path.join(directory, "wal.log")
if os.path.exists(self.wal_path):
with open(self.wal_path, "rb") as f:
for line in f:
try:
rec = json.loads(line)
except ValueError:
break # torn final record from a crash
self.memtable[rec["k"]] = rec["v"]
self.wal = open(self.wal_path, "ab")
def put(self, key, value):
self._write(key, value)
def delete(self, key):
self._write(key, None) # tombstone
def get(self, key):
if key in self.memtable:
return self.memtable[key]
for table in reversed(self.tables): # newest first
found, value = table.get(key)
if found:
return value
return None
def close(self):
self.wal.close()
def _write(self, key, value):
record = json.dumps({"k": key, "v": value}) + "\n"
self.wal.write(record.encode())
self.wal.flush()
os.fsync(self.wal.fileno())
self.memtable[key] = value
if len(self.memtable) >= self.limit:
self._flush()
def _flush(self):
path = os.path.join(self.dir, f"{self.next_id:06d}.sst")
tmp = path + ".tmp"
with open(tmp, "wb") as f:
for k in sorted(self.memtable):
line = json.dumps({"k": k, "v": self.memtable[k]}) + "\n"
f.write(line.encode())
f.flush()
os.fsync(f.fileno())
os.replace(tmp, path)
self.tables.append(SSTable(path))
self.next_id += 1
self.memtable = {}
self.wal.close()
self.wal = open(self.wal_path, "wb") # truncate the log
with tempfile.TemporaryDirectory() as d:
db = MiniLSM(d, memtable_limit=3)
for i in range(5):
db.put(f"k{i}", f"v{i}")
db.delete("k1")
print(db.get("k0"), db.get("k1"), db.get("k4"))
print(sorted(os.listdir(d)))
db.put("k5", "v5")
db.close()
recovered = MiniLSM(d, memtable_limit=3) # replays the WAL
print(recovered.get("k5"))
recovered.close()Running it prints:
v0 None v4
['000000.sst', '000001.sst', 'wal.log']
v5The first flush happens after k2. The delete of k1 fills the memtable again and triggers a second flush, so the tombstone sits in the newer SSTable and shadows the old k1. The write of k5 exists only in the WAL, and the reopened engine recovers it from there.
Edge cases and common mistakes
- Skipping fsync on the rename path. Flushing the data file but not the directory can lose the new file's name after a power failure. Production engines also fsync the directory.
- Truncating the WAL before the SSTable is durable. This opens a window where a crash loses the memtable's data entirely.
- Reading oldest-first. This returns stale values. The read order must be newest to oldest.
- Ignoring tombstone lifetime. As described above, premature removal resurrects deleted data.
- Unbounded memtable. Writes arriving during a flush need a second memtable, or the engine must pause writes. Real engines keep an immutable memtable being flushed alongside an active one.
Exercise
A node crashes right after appending a record to the WAL but before inserting it into the memtable. After restart, is the write visible, and why? What changes if the WAL append and fsync happen after the memtable update instead?
Show answer
The write is visible, because recovery replays the WAL into a fresh memtable and the record is in the log. With the reversed order, a crash after the memtable update but before the log append loses the write, even though a client may already have been told it succeeded (or a reader may have seen it). Logging first is what makes acknowledged writes durable.
Exercise
Key "x" is written as "old" and flushed to SSTable 1. It is then deleted and flushed to SSTable 2 as a tombstone. If compaction merges only SSTable 2 with a newer SSTable 3 and drops the tombstone, what does get("x") return, and what is the fix?
Show answer
It returns "old", because the tombstone that shadowed the value in SSTable 1 is gone. The fix is to drop a tombstone only when the compaction includes every older file that might hold the key (or after a grace period long enough for every replica to have seen the delete).