03. Data & Storage / Lesson 3 of 11

Storage Engines

How a database really writes bytes to disk: B-trees and LSM-trees.

  • 12 min
  • Advanced
  • 11 steps
  • Write speed100/s (bad)
  • Read cost—
  • Write amplification—

Overwrite in place

find the row's spot

✗ head jumps: 10 ms

✗ 100 writes a second

AppStorage engineDisk⚠ 10 ms a jump
  • Request
  • Write
  • Health check
Step 1/11

Step 1 of 11: A write has to land somewhere on the disk

Read every step as text
  1. Step 1: A write has to land somewhere on the disk

    A database keeps rows on disk, and a storage engine decides how. The simple way is to find the row's place and overwrite it. On a spinning disk the head must jump there first, say 10 ms, so it manages only about 100 such writes a second.

    Reads and writes are both slow when they are scattered over the disk. Each engine below is a different way to avoid scattering the work.

    SSDs have no head to move, but they still prefer big, ordered writes. The ideas below help on both.

  2. Step 2: Never jump: only add to the end of a file

    Appending to the end of a file needs no jump. A disk can write about 100 MB a second this way, which is 100,000 records of 1 KB a second, a thousand times faster than random writes.

    Reading is the problem. To find one key you must scan the log, and the latest value for a key is the last one written. For 1,000,000 records (1 GB) a full scan takes about 10 seconds.

    Fast writes and slow reads. Every real engine keeps the sequential write and adds a way to find data again.

  3. Step 3: B-tree: a sorted tree of pages, updated in place

    A B-tree splits the data into fixed pages (say 4 KB; real databases use 4 to 16 KB) and keeps them in a sorted tree. A lookup walks from the root down to one leaf page. For 1,000,000 records and 250 keys per page that is only 4 page reads.

    The price is on writes. To change one 1 KB record the engine rewrites its whole 4 KB page where it lies, a random write, so write amplification is 4× and the speed is back to about 100 a second on a spinning disk.

    Reads are excellent and ordered range scans are easy. Most classic databases are built this way.

  4. Step 4: The write-ahead log: write the plan first

    A page update in the middle of a crash can leave a half-written page. So before touching any page, the engine appends the change to a write-ahead log (WAL) and forces it to disk. Once that is done, the commit can be confirmed.

    The pages change later, in memory first, and are flushed in batches. After a crash the engine replays the log to repair them. The cost is one extra write: 4 KB page plus 1 KB log, so 5× amplification.

    Commit speed now depends on a sequential log write, not on random page writes. This is how B-tree databases stay both safe and quick.

  5. Step 5: LSM-tree: sort in memory, write in big batches

    A log-structured merge tree (LSM-tree) goes the other way. New writes go into a memtable, a sorted table in memory (and, for safety, into a write-ahead log on disk). No page is updated in place.

    A read looks in the memtable first, because it holds the newest values. Writes cost one memory insert and one log append.

    The idea: turn many small random writes into a few big sequential ones.

  6. Step 6: When the memtable is full, flush it as a sorted file

    At about 64 MB the memtable is written to disk in one go as an SSTable (sorted string table): a sorted file that is never changed again. Then the memtable and its log start empty.

    Over time files pile up. For 1 GB of data in 64 MB files that is 16 SSTables, and a lookup that misses the memtable may have to check up to 16 of them, newest first.

    An update or a delete is just a newer entry (a delete is a marker called a tombstone). The old value stays in an older file until it is cleaned up.

  7. Step 7: Compaction: merge the files in the background

    A background job reads several sorted SSTables and merges them into one new sorted file, keeping only the newest value of each key and dropping deleted ones. Because the inputs are sorted, the merge is a sequential read and a sequential write.

    With leveled compaction each level is about 10 times bigger than the one above, and a record may be rewritten up to about 10 times on each level it passes. For 3 levels that is up to about 30× write amplification. In return a lookup checks about one file per level: 3 files.

    Compaction uses disk and CPU all the time. If it falls behind, files pile up and reads slow down.

  8. Step 8: A Bloom filter says "definitely not in this file"

    Reads for a key that does not exist are the worst case: every file must be checked. A Bloom filter is a small bit array kept for each file. It answers "not here" with certainty, or "maybe here", and with about 10 bits per key it is wrong about 1% of the time on the "maybe".

    If 16 files have piled up, a missing key would cost 16 file reads. With filters it costs about 16 × 0.01 = 0.16 file reads on average.

    Filters never give a false "not here", so no real key is ever missed. The only cost is an occasional wasted read.

  9. Step 9: The trade-off is amplification

    Write amplification is the bytes written to disk for each byte the app writes. The B-tree with a log writes 5× (page plus log). The LSM-tree writes about 1× at first and up to about 30× after compaction in the numbers used here.

    Read amplification is the pieces touched per lookup: 4 pages for the B-tree, about 3 files plus the memtable for the LSM-tree. LSM-trees also hold old versions until compaction, so they may use more disk space.

    Neither design wins everywhere. B-trees favour reads and steady latency; LSM-trees favour heavy, continuous writes.

  10. Step 10: Real databases pick one

    B-tree family: PostgreSQL indexes, MySQL with InnoDB, SQLite, and most classic relational databases. They suit mixed reads and writes with steady response times.

    LSM-tree family: RocksDB, LevelDB, Cassandra and HBase. They suit write-heavy loads such as logs, time series and messaging. RocksDB is also used as the engine inside other databases.

    Choosing a database is partly choosing its storage engine. Know which one is under it.

  11. Step 11: Storage engines in one picture

    Random writes are slow, sequential writes are fast. A B-tree updates pages in place and reads in about 4 page reads, with a write-ahead log for safety. An LSM-tree buffers in a memtable, flushes sorted files and merges them later.

    Compaction and Bloom filters keep LSM reads under control. The price of the LSM write speed is more background work and more write amplification.