SSTable
medium 24 minA sorted string table is a file of key-value pairs in key order that never changes after it is written.
See it run
How a sorted file is written, searched, skipped and merged.
Operations
Write a table
Six sorted entries, two in each block. The file is written from top to bottom.
Step 1 of 5
Sorted input
| Block 0 | ||
|---|---|---|
| Block 1 | ||
| Block 2 | ||
| Filter | ||
| Index | ||
| Footer |
apple, banana, cherry, date, elderberry, fig
The memtable hands over its entries in key order. The file is empty.
Step 1: Sorted input
def flush(memtable, out): for key, value in memtable.sorted_items(): block.add(key, value) bloom.add(key) if block.full(): index.add(block.first_key, out.position) out.write(block) out.write(bloom) out.write(index) out.write(footer) # last out.flush()- Disk work
- One sequential pass
- Memory
- Index and filter
- Updating in place
- moves everything behind
The footer comes last, because only then are the positions known.
In the real world
The same sstable doing real jobs. Pick one and step through it.
Fruit arrives, files pile up, one lookup, one merge.
Step 1 of 8
Empty memtable
In memory
empty
No files yet
Ready for writes.
Step 1: Empty memtable
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Treating maybe as yes
criticalA Bloom filter can be wrong about maybe. The key must still be looked up.
Wrongif bloom.may_contain(key): return TrueRightif not bloom.may_contain(key): return Falsereturn key in read_block(key)Writing unsorted keys
criticalThe index and the search inside a block rely on the order, so keys become impossible to find.
Wrongfor key in arrivals: table.add(key)Rightfor key in sorted(arrivals): table.add(key)Deleting inputs too early
criticalIf the merged file is not safely on disk, a crash loses both.
Wrongremove(inputs)write(merged)Rightwrite(merged)flush(merged)publish(merged)remove(inputs)Filter with the wrong size
minorA filter made for 1,000 keys and filled with 100,000 has all bits set and says maybe to everything.
WrongBloom(bits=10_000) # for any number of keysRightBloom(bits=10 * key_count)
Interview tips
How to explain it
- Sorted, sealed, written in one pass.
- Filter, index, one block.
- Merge keeps the newest.
Memory trick
- Sorted, Sealed Table.
- Better Lookup, Only Maybe.
- Memtable, Flush, Disk.
Numbers to say
- 10 bits per key, about 1%.
- 4 KB blocks for single keys.
- Index below 1% of the file.
Watch out
- Files piling up.
- Filters and ranges.
- Interrupted writes.