Sub topic 8
Reading a Key Across Memtable and SSTables
This chapter assumes you know hash maps, sorted arrays, binary search, and the difference between memory and disk. It also assumes you have seen the memtable and SSTable from earlier chapters. Here you will trace a point lookup and see why the order of the search matters.
Why a read must check several places
A write goes to the memtable. When the memtable fills, a flush turns it into an immutable SSTable. Over time the same key can appear in several places, each with a different value. Only the newest entry is correct. A read therefore has to search from newest data to oldest and stop at the first hit.
The search order
- Check the memtable. It holds the most recent writes.
- Check each SSTable from newest to oldest.
- Stop at the first entry for the key. That entry decides the result.
- If no place has the key, the key does not exist.
The code
The get method of TinyLSM follows this order exactly.
def get(self, key):
if key in self.memtable:
value = self.memtable[key]
return None if value is TOMBSTONE else value
for table in reversed(self.sstables): # newest first
found, value = table.get(key)
if found:
return None if value is TOMBSTONE else value
return Noneself.sstables is stored oldest first, so reversed gives newest first. Inside each SSTable, bisect_left runs a binary search over the sorted keys, so one table lookup costs O(log n).
Note that found is separate from value. A stored tombstone is a real entry, so found is True and the lookup stops. If the code kept searching older tables, a deleted key would reappear with its old value.
Cost of a read
A key that was written recently is found early. A key that is old, or missing, forces the read to visit every SSTable. With many tables, each lookup may touch many files. This cost is called read amplification.
Two mechanisms reduce it:
- A block index lets a table find the right block of a file without scanning the whole file.
- A Bloom filter per table lets the read skip a table that definitely lacks the key. Later chapters cover both.
Compaction also helps by reducing the number of tables.
Common errors
- Searching oldest first. This returns stale values.
- Treating a tombstone as "not present in this table" and moving on. This resurrects deleted data.
- Returning
Nonefor both "missing" and "deleted" is fine for a point read. A range scan needs to keep the tombstone until the merge finishes.
Exercise
A TinyLSM has the memtable {"a": 1} and two SSTables. The older table holds {"a": 0, "b": 5}. The newer table holds {"b": TOMBSTONE}. What do get("a") and get("b") return, and how many SSTables does each lookup read?
Show answer
get("a") returns 1 from the memtable and reads no SSTables. get("b") is not in the memtable, so it checks the newer table first, finds the tombstone, and returns None. It reads one SSTable and never reaches the older table, so the old value 5 stays hidden.