Sub topic 2
The Single-Node Storage Engine: WAL, Memtable, and SSTables
This chapter assumes you know hash maps, sorted lists, and basic file I/O. It covers what each node in the cluster runs locally. Later chapters distribute these nodes.
Why a log-structured design
A node must accept many writes and survive a crash without losing acknowledged data. Updating a sorted file in place causes random disk writes, which are slow. A log-structured design turns every write into a sequential append. Sequential writes are fast on both disks and SSDs.
Three parts work together:
- The write-ahead log (WAL) is an append-only file. Each write is recorded here first, so it survives a crash.
- The memtable is a sorted in-memory structure that holds recent writes. Real systems use a skip list or balanced tree. The example below uses a dict and sorts it at flush time.
- An SSTable (sorted string table) is an immutable file of key-value pairs sorted by key. The memtable is written out as one when it grows too large.
The write and read paths
On a restart, the node replays the WAL into a fresh memtable. This restores every write that had not yet reached an SSTable.
A minimal implementation
This store keeps the logic small. Reads scan whole files, which real engines avoid with indexes and Bloom filters.
import json
import os
import tempfile
class TinyStore:
def __init__(self, directory, limit=3):
self.dir = directory
self.limit = limit
os.makedirs(directory, exist_ok=True)
self.wal_path = os.path.join(directory, "wal.log")
self.memtable = {}
self.tables = sorted(f for f in os.listdir(directory) if f.endswith(".sst"))
self._replay()
self.wal = open(self.wal_path, "a")
def _replay(self):
if os.path.exists(self.wal_path):
with open(self.wal_path) as f:
for line in f:
rec = json.loads(line)
self.memtable[rec["k"]] = rec["v"]
def _write(self, key, value):
self.wal.write(json.dumps({"k": key, "v": value}) + "\n")
self.wal.flush()
os.fsync(self.wal.fileno())
self.memtable[key] = value
if len(self.memtable) >= self.limit:
self._flush()
def put(self, key, value):
self._write(key, value)
def delete(self, key):
self._write(key, None) # None is the tombstone
def _flush(self):
name = f"{len(self.tables):06d}.sst"
with open(os.path.join(self.dir, name), "w") as f:
for k in sorted(self.memtable):
f.write(json.dumps([k, self.memtable[k]]) + "\n")
self.tables.append(name)
self.memtable = {}
self.wal.close()
self.wal = open(self.wal_path, "w")
def get(self, key):
if key in self.memtable:
return self.memtable[key]
for name in reversed(self.tables):
with open(os.path.join(self.dir, name)) as f:
for line in f:
k, v = json.loads(line)
if k == key:
return v
return None
store = TinyStore(tempfile.mkdtemp())
store.put("a", 1)
store.put("b", 2)
store.put("a", 3) # third distinct write triggers nothing yet: only 2 keys
store.put("c", 4) # 3 keys in memtable, so it flushes to 000000.sst
store.delete("b")
print(store.get("a"), store.get("b"), store.get("c")) # 3 None 4Deletes and tombstones
SSTables are immutable, so a delete cannot remove a key from an older file. The store writes a tombstone, a marker meaning "deleted". A read that finds the tombstone first stops and reports the key as missing. In the code above, None is the tombstone, and get returns it before looking at older files.
What this design costs
- Read amplification. A read may check several files. Real engines add Bloom filters and sparse indexes to skip files.
- Space and compaction. Old versions and tombstones pile up. Background compaction merges SSTables and drops overwritten entries.
- Durability cost.
fsyncon every write is safe but slow. Many systems batchfsynccalls, which risks losing the last few milliseconds of writes on a crash.
Exercise
A node crashes after writing a new SSTable but before it resets the WAL. What happens on restart, and is the data still correct?
Show answer
The node replays the whole WAL into the memtable. Those writes also exist in the SSTable, so they are duplicated. The data stays correct, because the memtable is checked first and holds the same values. The next flush writes them again, and compaction later removes the duplicates.