Sub topic 2
The big picture: memory, log, and sorted files
This chapter gives you the working model of an LSM storage engine. Later chapters take each part in detail. It assumes you know hash maps, sorted arrays, binary search, the difference between memory and disk, and sequential versus random I/O. You should also be able to read short Python programs.
The three parts
An LSM engine splits storage into three parts, each with one job.
- The memtable is a sorted structure in memory. Every write lands here first.
- The write-ahead log (WAL) is an append-only file on disk. Each write is also appended here, so the memtable can be rebuilt after a crash.
- SSTables (sorted string tables) are immutable sorted files on disk. When the memtable grows too large, the engine writes it out as a new SSTable.
A fourth activity runs in the background. Compaction merges SSTables, which keeps their number under control.
Following a write and a read
A write takes two cheap steps: one sequential append to the log, and one insert into memory. No existing file is modified. When the memtable reaches its size limit, the engine writes it to disk in key order as one new SSTable and starts an empty memtable.
A read has to look in more places. It checks the memtable first, because that holds the newest data. Then it checks SSTables from newest to oldest. The first match wins, since a newer value for a key hides any older one.
A minimal version
The sketch below shows all of this in a few lines. It leaves out the WAL, which a later chapter covers.
import bisect
class SSTable:
"""Immutable sorted run of (key, value) pairs."""
def __init__(self, items):
self.keys = [k for k, _ in items]
self.values = [v for _, v in items]
def get(self, key):
i = bisect.bisect_left(self.keys, key)
if i < len(self.keys) and self.keys[i] == key:
return True, self.values[i]
return False, None
class TinyLSM:
def __init__(self, memtable_limit=4):
self.memtable = {}
self.sstables = [] # oldest first, newest last
self.memtable_limit = memtable_limit
def put(self, key, value):
self.memtable[key] = value
if len(self.memtable) >= self.memtable_limit:
self.flush()
def flush(self):
if not self.memtable:
return
self.sstables.append(SSTable(sorted(self.memtable.items())))
self.memtable = {}
def get(self, key):
if key in self.memtable:
return self.memtable[key]
for table in reversed(self.sstables): # newest first
found, value = table.get(key)
if found:
return value
return None
db = TinyLSM(memtable_limit=2)
db.put("a", 1)
db.put("b", 2) # memtable is full, so it is flushed
db.put("a", 3) # newer value for "a" sits in the memtable
print(db.get("a"), db.get("b"), len(db.sstables))The program prints 3 2 1. The old value of a is still inside the first SSTable. It is hidden, not erased.
Why this layout helps and what it costs
Writes become sequential I/O, which disks handle well. Immutable files are simple to read concurrently and to cache.
The cost is on the read side and in background work. A read may touch several files, and stale versions take up space until compaction removes them. Most of the rest of this tutorial deals with these two costs.
Exercise
A key was written twice. The first value was flushed into an SSTable, and the second value is still in the memtable. Which value does a read return, and why?
Show answer
It returns the second value. A read checks the memtable first, and the first match wins. The older value remains in the SSTable until compaction removes it.