Sub topic 4
The write-ahead log: durability for the memtable
This chapter assumes you know what a memtable is (an in-memory sorted or hashed buffer for recent writes), the difference between memory and disk, and how sequential and random I/O differ. You should also be able to read short Python programs.
The problem: memory is volatile
The memtable lives in RAM. If the process crashes or the machine loses power before a flush, every write still in the memtable is gone. Flushing after every write would fix this, but it would create one tiny file per write and lose the benefit of batching.
The write-ahead log (WAL) solves this. It is an append-only file on disk. Before the engine changes the memtable, it appends a record describing the change to the log. After a crash, the engine replays the log to rebuild the memtable.
The write path with a log
- Append the record (operation, key, value) to the end of the WAL.
- Make the record durable, if the configuration requires it.
- Apply the change to the memtable.
- Acknowledge the write to the client.
The order matters. If the engine updated the memtable first and crashed before logging, the client might have been told "success" for a write that no longer exists after restart.
Why appending is cheap
The WAL is written only at its end, so the disk sees sequential I/O. This is the same property that makes LSM trees fast in general. The log does not need to be sorted or searchable. It is only read during recovery.
A minimal WAL in Python
import json
import os
class WAL:
def __init__(self, path, sync=True):
self.path = path
self.sync = sync
self.file = open(path, "a", encoding="utf-8")
def append(self, op, key, value=None):
record = json.dumps({"op": op, "key": key, "value": value})
self.file.write(record + "\n")
self.file.flush()
if self.sync:
os.fsync(self.file.fileno())
def replay(self):
if not os.path.exists(self.path):
return
with open(self.path, "r", encoding="utf-8") as f:
for line in f:
try:
yield json.loads(line)
except json.JSONDecodeError:
break # torn final record from a crash; stop here
def close(self):
self.file.close()The flush() call moves data from Python's buffer to the operating system. The os.fsync() call asks the operating system to push it to the physical device. Without fsync, the data may sit in the OS page cache and be lost on power failure.
The durability trade-off
Calling fsync on every write is safe but slow. Many engines offer a choice.
| Setting | Behavior | Risk |
|---|---|---|
| Sync on every write | Each write is on disk before the acknowledgment | Lowest throughput |
| Sync periodically | Writes are grouped and synced every few milliseconds | May lose the last interval of writes on power failure |
| No explicit sync | The OS decides when to write | May lose more data on power failure. A process crash alone loses nothing, because the OS still holds the data |
Truncating the log
The log would grow forever if it were never trimmed. Once a memtable is flushed into an SSTable and that file is safely on disk, the log records for that memtable are no longer needed. The engine can delete that log file, or start a new one for the next memtable. Most engines keep one WAL per memtable for this reason.
Common errors
- Applying the memtable update before the log append.
- Forgetting
fsyncand assumingflush()is enough. - Deleting the old log before the SSTable is fully written and synced.
- Treating a half-written final record as fatal. A crash can leave one, and replay should stop cleanly there.
Exercise
A key-value store acknowledges a write after appending to the WAL with flush() but without fsync, then updating the memtable. The process is killed with SIGKILL. Is the write lost? What if the machine loses power instead?
Show answer
After a SIGKILL the write is not lost, because the data already reached the operating system, which still writes it to disk. After a power failure it may be lost, because the data could still be in the OS page cache and never reached the device. Only fsync (or an equivalent) guarantees survival of power loss.