AlgoViz

SSTable

medium 24 min

A sorted string table is a file of key-value pairs in key order that never changes after it is written.

Video lesson · Chapter 1 of 5

Seal a sorted fruit catalog

0:00 / 3:19

A sorted, sealed file in 75 seconds

1:15Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

An SSTable, short for sorted string table, is a file that holds key-value pairs sorted by key. It is written once from start to end and never changed. The word string means a string of bytes: keys and values can be anything.

The file is cut into blocks of a few kilobytes. A small index says which block holds which keys, and a Bloom filter can tell that a key is certainly not in the file.

Why it exists

Changing a sorted file in place is slow: a new key in the middle would move everything behind it. So writes are collected in memory, sorted there and written as a new file in one sequential pass.

Because a finished file never changes, readers need no locks, copies are always consistent, and caches never hold stale data. The price comes later: several files may hold versions of one key, so they must be merged.

A short history

  1. 1970

    Burton Howard Bloom describes the filter that now sits inside many SSTables.

  2. 2006

    Google's Bigtable paper describes the SSTable file format: a persistent, ordered, immutable map from keys to values.

  3. 2008

    Cassandra is released. Its storage engine keeps memtables in memory and immutable SSTables on disk.

  4. 2011

    LevelDB is written in the style of the Bigtable tablet stack, without sharing its code.

Words to know

Memtable
The sorted structure in memory that becomes an SSTable when it is full.
Data block
A few kilobytes of neighbouring entries. Read, cached and compressed as one piece.
Sparse index
One entry for each block, not for each key.
Footer
A fixed-size end of the file that says where the index is.
Bloom filter
A compact bit array that answers "certainly not here" or "maybe here".
False positive
The filter says maybe, and the key is not there.
Merge
Reading several sorted files side by side and writing one, keeping the newest version of each key.

How it works

Step through the idea, or press Play.

Step 1 of 3

Sort in memory. The memtable collects writes in key order

Understand it

Start here

The photo album story

Somebody collects photos and sorts them by name. When there are five, they go into an album, and the album is sealed: nothing is added or moved. It is like a toy list in alphabetical order on paper. You can jump straight to R for robot, and nobody edits the paper.

Sealed albums, sorted by name
AnaBenCemDiaEliSorting on the table

Album 1 is never changed. A newer photo of Cem simply goes into a later album.

The idea

Why sorted and why sealed

  • Immutable

    Never modified after creation. No locks for readers.

  • Sorted

    Binary search, ranges and merging all work.

  • Sequential write

    The whole file is written in one pass.

  • Easy to copy

    A finished file is the same everywhere, so backups and replicas are simple.

From memory to file

Entries arrive in any order and leave in key order.

Structure

Inside the file

One SSTable and what stays in memory

A reader on one database server. In memory are the cached index and Bloom filter. On disk is one SSTable file with data blocks, meta blocks, an index block and a footer. The reader uses the memory parts first and then reads one data block.
Filter and index are usually kept in memory, so the only disk read is one data block.
PartHoldsExample
Data blocksSorted entriesBlock 0: a to d, 1: e to k, 2: l to q, 3: r to z
Meta blocksBloom filter, statistics, compression detailsOne filter for the file
Index blockA key and a position for each blocka at 0, e at 1, l at 2, r at 3
FooterPositions of the index and the meta blocks, and a magic numberFixed size, at the end
The footer is last because the writer knows the positions only when everything else is written. LevelDB and RocksDB files follow this layout.

Inside one data block

  1. 1

    Length of the key

    4 bytes in the simple format used in the Code tab. Real formats use numbers of variable length.

  2. 2

    Length of the value

    Another 4 bytes.

  3. 3

    Key, then value

    As many bytes as the lengths say, followed directly by the next entry.

  4. 4

    Checksum

    Real formats add one for each block, to notice damage.

Block compression

  • Each block is compressed on its own
  • Only one block is unpacked for a lookup
  • LZ4 and Snappy are quick, Zstandard is smaller
  • How much it saves depends on the data

Prefix compression

  • Neighbouring keys look alike: user:1001, user:1002
  • Store only the part that differs
  • Saves most when keys share long prefixes
  • A full key now and then keeps search possible

How small is the index?

64 MiB4 KiB=16,384 blocks16,384×30 B≈0.5 MB\frac{64\,MiB}{4\,KiB} = 16{,}384 \text{ blocks} \qquad 16{,}384 \times 30\,B \approx 0.5\,MB
Assuming 30 bytes for each index entry. Less than 1% of the file, so it fits in memory.

Write

Creating a table

  1. 1

    Collect

    Entries gather in the memtable, sorted by key.

  2. 2

    Flush

    When the memtable is full, a new file is started.

  3. 3

    Data blocks

    Written one after the other. The first key of each block is remembered.

  4. 4

    Filter and index

    Written after the data, because now the positions are known.

  5. 5

    Footer

    Written last. Only then is the file made visible to readers.

The write is sequential, so it runs at the speed of the device for large writes. That is the reason for the whole design: many small random writes became one large sequential one.

Read

Finding one key

Point lookup

The last no is a false positive: one wasted block read.

The index is sparse. To find grape, take the last block whose first key is not larger than grape. If the key exists in this file, it is in that block.

Range scan from user:100 to user:200

Find the start once, then read in sequence. A Bloom filter for whole keys cannot help here.

Skip

The Bloom filter

A Bloom filter behaves like a magic ball that says "definitely not here" or "might be here". It is never wrong about not here. It is an array of bits: to add a key, several hash functions each set one bit. To ask, check the same bits. One zero means the key was never added.

16 bits, 3 hash functions

StepBitsResult
Add apple2, 7, 14All three are set
Add banana5, 7, 117 was already set, 5 and 11 are new
State2, 5, 7, 11, 14 are 1Five bits for two keys
Ask cherryBit 3 is 0Certainly not in the set
Ask another key5, 7, 14 are all 1Maybe. Here it would be a false positive

False positive rate

p≈(1−e−k/b)kb=10, k=7:;p≈0.8%p \approx \left(1 - e^{-k/b}\right)^k \qquad b = 10,\ k = 7:; p \approx 0.8\%
bb is bits per key and kk the number of hash functions. The best kk is about 0.69 b0.69\,b.
Bits per keyHash functionsFalse positivesMemory for 1M keys
862.2%1 MB
1070.8%1.25 MB
1280.3%1.5 MB
16110.05%2 MB
Computed with the formula above. RocksDB's documentation gives 9.9 bits per key for 1%.

Good

  • About 10 bits per key, whatever its length
  • A check takes k bit tests
  • No false negatives, ever
  • With 1% false positives, 99 of 100 useless file reads are avoided

Limits

  • False positives, so a read can still be wasted
  • Single keys cannot be removed
  • Keys cannot be listed
  • Size and accuracy must be balanced

Merge

Several files become one

Merge, newest wins

c is in both files. The newer value 4 is kept.

Because every input is sorted, the merge reads each file once from start to end and needs little memory. When to merge which files is called compaction, and it belongs to the LSM tree. So does the question of how deletes work.

Compare

SSTable or B-tree page?

SSTablesB-tree
Write patternSequential, whole filesScattered pages
Read of one keyMaybe several filesOne path
Extra spaceOld versions until mergedPartly empty pages
RewritingMerging repeats the same dataA small change rewrites a page
Best forWrite-heavy workRead-heavy work
Real results depend on the workload and on memory. Measure before you decide.

Is it a good fit?

Numbers

Defaults you can quote

SettingValueFrom
Block size4 KBRocksDB and LevelDB default
Block size64 KBBigtable paper, typical; HBase default
Target file size64 MBRocksDB, first level
Target file size2 MBLevelDB
File size, leveled160 MBScyllaDB
Bloom filterabout 10 bits per keyRocksDB's example setting
Small blocks suit single-key reads; large blocks suit scans and compress better.

Summary

The whole topic in one minute.

An SSTable is written in one pass from sorted data and then sealed. A reader loads the footer, the index and the filter once; after that a lookup costs about one block read, or none when the filter says no.

Sorting pays off three times: binary search works, ranges are read in sequence, and several files can be merged in one pass. Immutability makes concurrency and copying easy and makes merging necessary.

  • An SSTable is sorted, sealed and written in one pass.
  • Data blocks, meta blocks with a filter, an index block, a footer.
  • Lookup: filter, sparse index, one block.
  • A Bloom filter is never wrong about no; 10 bits per key give about 1% wrong yes.
  • Sorted files merge in one pass; the newest version wins.

Sources