Sub topic 6
Flushing the Memtable into a New SSTable
This chapter assumes you know what a memtable and an SSTable are, and that you can read short Python programs. Flushing is the step that turns the in-memory table into an immutable sorted file on disk.
Why flush
The memtable lives in RAM, so it cannot grow without limit. When it reaches a size threshold, the engine writes its contents to disk as one sorted file. This turns many small random updates into one large sequential write, which is the main reason LSM trees are fast at writing.
The flush steps
- Freeze the current memtable so it accepts no more writes.
- Start a new empty memtable (and a new log segment) so incoming writes continue.
- Read the frozen memtable in key order and write each entry to a new file.
- Sync the file to disk, then record it in the list of live tables.
- Delete the write-ahead log segment that covered the frozen memtable.
Step 5 must come last. Until the new file is safely on disk, the log is the only durable copy of those writes.
Flush in the tiny store
In TinyLSM, put calls flush when the memtable reaches its limit. The flush sorts the entries and appends a new SSTable.
def flush(self):
if not self.memtable:
return
self.sstables.append(SSTable(sorted(self.memtable.items())))
self.memtable = {}Three details matter here:
sorted(self.memtable.items())gives the sorted order that makes binary search possible later. The dict itself has no key order.- The new table is appended at the end, so
sstablesstays ordered from oldest to newest. The read path depends on this. - Tombstones are flushed like any other value. A delete is just a write.
Try it:
db = TinyLSM(memtable_limit=3)
db.put("a", 1)
db.put("b", 2)
db.delete("a") # third entry triggers a flush
print(len(db.sstables)) # 1
print(db.get("a")) # None, found as a tombstone in the table
print(db.get("b")) # 2The third write leaves the memtable at three entries, so it flushes. Key a was overwritten by the tombstone before the flush, so only the tombstone reaches disk.
Common errors
- Deleting the log too early. If the process crashes after the log is removed but before the file is synced, the data is lost.
- Blocking writes during flush. Real engines freeze the old memtable and keep accepting writes in a new one. If flushing is slower than writing, the engine must stall writers, which shows up as latency spikes.
- Publishing a partial file. Write to a temporary name, sync, then rename or record it in the manifest, so a crash never exposes a half-written table.
- Many tiny files. Flushing too often creates many small SSTables, which makes reads slower and gives compaction more work.
Exercise
A flush has written the new SSTable but has not synced it to disk. Why must the engine not delete the write-ahead log segment yet?
Show answer
Until the file is synced, a crash could lose it. The log segment is then the only durable copy of the frozen memtable's writes, and deleting it would lose that data permanently.