System Design · 03. Data & Storage · 12 min · Advanced
Storage Engines
How a database really writes bytes to disk: B-trees and LSM-trees.
In short
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.
Key ideas
- Fast writes and slow reads. Every real engine keeps the sequential write and adds a way to find data again. (step 2)
- 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. (step 4)
- The idea: turn many small random writes into a few big sequential ones. (step 5)
- Neither design wins everywhere. B-trees favour reads and steady latency; LSM-trees favour heavy, continuous writes. (step 9)
Good to know
- Reads are excellent and ordered range scans are easy. Most classic databases are built this way. (step 3)
- Filters never give a false "not here", so no real key is ever missed. The only cost is an occasional wasted read. (step 8)
- Choosing a database is partly choosing its storage engine. Know which one is under it. (step 10)
Watch out
- SSDs have no head to move, but they still prefer big, ordered writes. The ideas below help on both. (step 1)
- 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. (step 6)
- Compaction uses disk and CPU all the time. If it falls behind, files pile up and reads slow down. (step 7)
Key numbers
- Read cost
- 4 vs 3
- Write amplification
- 5× vs 30×
Terms
- Storage engine
- The part of a database that decides how data is laid out on disk and how it is read and written.
- Append-only log
- A file that is only ever added to at the end, which makes writes fast and sequential.
- B-tree
- A sorted tree of fixed-size pages that is updated in place and needs very few page reads per lookup.
- Write-ahead log (WAL)
- A log that records each change on disk before the data pages change, so a crash can be repaired by replaying it.
- Memtable
- The sorted in-memory table where an LSM-tree puts new writes first.
- SSTable
- A sorted file written from a full memtable that is never modified afterwards.
- LSM-tree
- A design that buffers writes in memory and writes them to disk as sorted files that are merged in the background.
- Compaction
- Merging sorted files in the background to drop old versions and deleted keys and to keep reads fast.
- Bloom filter
- A small bit array that says a key is definitely not in a file, or maybe is, so most files can be skipped.
- Write amplification
- The bytes written to disk for each byte the application writes.