Notes

Part 3 of 10

Building and merging SSTables

SSTables are great for reads, but you cannot add keys out of order to a sorted file, and rewriting the file on every insert is far too slow. The log-structured approach solves this in four steps:

  1. A new write goes into a sorted map in memory, called the memtable, such as a red-black tree, a skip list, or a trie.
  2. When the memtable grows past a few MB, it is written to disk as a new SSTable segment, while a fresh memtable takes new writes.
  3. A read checks the memtable, then the newest segment, then older ones, and stops at the first match; if no file has the key, it does not exist.
  4. In the background, segments are merged and compacted, and overwritten or deleted values are thrown away.

Guess first

fig was written long ago, and written again a moment ago. Where should a read for fig look first?

fig was written long ago, and written again a moment ago. Where should a read for fig look first?

From memtable to sorted files

Step 1 of 5

Writes go into the memtable, a map in memory kept sorted by key. kiwi was written first, but fig sorts ahead of it. An older segment already sits on disk.

Merging works like the merge step of mergesort. You read the input files side by side and always output the smallest key next. If a key shows up in several files, you keep only the newest value. The output is still sorted, and the merge needs very little memory.

A few more details make this safe:

  • Crash log: the memtable would vanish in a crash, so each write is also added to a separate, unsorted log on disk.
  • That log is used only to rebuild the memtable after a crash, and it is thrown away once its memtable is flushed.
  • Tombstones: a delete adds a special marker called a tombstone, which hides older values for that key during merges.
  • Once the tombstone has been merged into the oldest segment, nothing older is left to hide, so the tombstone itself can go.
  • Immutable files: a segment is written once, in one pass, and never changed afterward.
  • Background compaction: a background thread builds the merged files while reads keep using the old ones, then reads switch over and the old files are deleted.
  • Easy recovery: if a crash cuts off a half-built segment, you just delete it and build it again.
  • Checksums: after a crash or a full disk, the crash log may end in a half-written record, and a checksum lets the engine spot and drop it.
  • Object storage: files that are written once and never edited fit cloud object storage well.

The whole design, a cascade of sorted files merged in the background, is called an LSM-tree (log-structured merge tree).