Algorithms · Huge scale

LSM trees

Why Google’s LevelDB writes to a pile first. Tidying every time you save is slow. Toss it on a pile, sort the pile later.

The problem

Picture a service at Google that stores a huge number of small records: one key, one value, and new ones arriving all day. Every write must be saved safely, and every key must stay findable. Jeff Dean and Sanjay Ghemawat built LevelDB, a key-value store that Google open-sourced in 2011, for exactly this job.

The obvious way

Keep one big sorted file, and put each new key in its correct spot. Lookups stay easy, but every insert pushes everything after that spot one place to the right. With 1,000 keys already stored, a key landing in the middle shifts about 500 of them. As the file grows, each write gets more expensive, and on disk those scattered rewrites are especially painful.

The clever idea

Think of a desk. You don't file every paper into the cabinet the moment it arrives. You toss it on a pile, and when the pile is big enough you sort it once and file the whole stack. LevelDB works this way. New writes go into a small sorted in-memory memtable (plus an append-only log, so a crash can't lose them).

When the memtable fills, it's written out as an immutable sorted file called an SSTable. Later, background compaction merges small sorted files into bigger ones. This design is a log-structured merge-tree (LSM tree), described by O'Neil et al. in 1996. Every write becomes a cheap sequential append.

How the code does it

In the obvious version, this line adds up how many items each insert has to shove aside. The in-place insert gets pricier as the list grows, because a typical key lands somewhere in the middle of a longer and longer list.

The LSM version never inserts into a big list. It piles keys up, and flushes a sorted run every 64. Once four runs exist, a tiny compaction merges them pairwise. Run the code and compare the two bars: the pile-first approach moves far fewer items. The second chart shows the sorted runs it leaves behind.

Trade-offs

Fast writes cost you on reads. A key might be in the memtable or in any of several files, so a lookup may check them one by one. LevelDB can use Bloom filters to skip files that definitely lack the key. Compaction also rewrites data in the background. If your workload is mostly reads, or you need every lookup to touch one place, a plain sorted structure may suit you better.

Where else you'll see it

Bigtable, RocksDB and Cassandra use the same write-to-a-pile-first idea. To read the real thing, browse the source at github.com/google/leveldb.

In the code, what would happen if the memtable limit were 2000 instead of 64?

  • Merging work would explode
  • All keys flush once, so no merges happen
  • The sorted list gets slower
Show the answer

All keys flush once, so no merges happen. The pile only fills on the very last key, so there's one flush and one run. runs never reaches 4, and moved stays 0. The cost moves into one big sort.

Change it and see
  • Change 64 to 16
  • Change 2000 to 4000
  • Merge when len(runs) == 8

The code

Python, with what each line means beside it. It compares the clever way with keeping one sorted file and inserting into it every time.

import random, bisect, heapqBring in the tools we need
random.seed(7)Make results repeatable
keys = [random.randint(0, 10**6) for _ in range(2000)]Create 2000 random keys
# (a) obvious: one sorted list, insert in place
table, shifted = [], 0Start with an empty sorted list
for k in keys:For each key in turn
i = bisect.bisect(table, k)Find its correct sorted position
shifted += len(table) - iCount the items it pushes right
table.insert(i, k)Insert it there
# (b) LSM: small memtable, flush to sorted runs, merge pairs
memtable, runs, moved = [], [], 0Start with empty memtable and runs
for k in keys:For each key in turn
memtable.append(k)Drop it on the pile
if len(memtable) == 64:When the pile reaches 64 keys
runs.append(sorted(memtable))Sort it and save it as a run
memtable = []Start a fresh empty pile
if len(runs) == 4:When four runs exist
a = list(heapq.merge(runs[0], runs[1]))Merge runs one and two
b = list(heapq.merge(runs[2], runs[3]))Merge runs three and four
moved += len(a) + len(b)Count every item merged
runs = [a, b]Keep just the two merged runs
show([shifted, moved], "items moved: sorted list vs LSM")Draw both totals as bars
show([len(r) for r in runs], "sorted run sizes at the end")Draw the final run sizes

Read more

Run it. Then change it.

The code runs right in the page and draws as it goes. Free, nothing to install.

More on huge scale