Notes

Part 2 of 10

Log-structured storage

A hash map over the log

The first upgrade keeps the append-only file and adds an in-memory hash map. The map points from each key to the byte position of that key's newest record in the file.

  • Write: add the record to the file, then update the map.
  • Read: look up the position, jump there, and read one record.

A log with a hash map

Step 1 of 4

set(fig, 3) adds a line at the end of the file, which starts at byte 0. The map in memory notes that fig starts at byte 0.

This works, but it has four problems:

  • Old values are never removed, so the file keeps growing and wastes disk.
  • The map lives only in memory, so a restart must scan the whole file to rebuild it, which makes restarts slow.
  • Every key must fit in memory, and a hash map kept on disk is slow, because it needs lots of random reads, is costly to grow, and needs fiddly logic for collisions.
  • Range queries, like "all keys from order100 to order199", need a separate lookup for every key.

SSTables and the sparse index

Hash tables are rarely used as database indexes. Structures sorted by key are far more common. An SSTable (Sorted String Table) is a file of key-value pairs, sorted by key, where each key appears at most once.

  • The pairs are grouped into blocks of a few KB.
  • A sparse index keeps only the first key of each block, not every key.
  • To find kiwi, find the two block start keys it falls between, say grape and lemon, jump to the grape block, and scan that small block.
  • Since each block is small, that scan is quick.
  • Each block can be compressed, which saves disk space and I/O bandwidth at the cost of some CPU.