1 of 4

Your RightSignal

How databases work · 7 of 91 / 3

LSM trees

The concept

Why some databases never edit a row where it lives on disk

A log-structured merge tree (LSM tree) never updates data in place. New writes go into a sorted table in memory called the memtable, and are also appended to the write-ahead log so a crash can't lose them.

When the memtable fills (say 64 MB), it is written out in one go as an SSTable (sorted string table): an immutable file of sorted keys. Change user:42 three times and three files may hold it; the newest wins.

Over time, a background job called compaction merges SSTables like merge sort does, keeping only the newest version of each key and dropping deleted ones. Files are arranged in levels, each about T times bigger than the one above.

What it’s forEstimates how many levels of files an LSM tree needs, which bounds how many places a read may have to look.

L ≈ log_T(N / M)

L
number of levels of SSTables on disk
T
size ratio between neighbouring levels, often 10
N
total size of the data
M
size of the memtable, e.g. 64 MB

What it givesThe number of levels; it grows only with the logarithm of the data size.

  1. N = 64 GB, M = 64 MB, so N / M = 1,000
  2. T = 10, and 10³ = 1,000
  3. L ≈ 3 levels below the memtable