Storage engines: B-tree vs LSM¶
What you'll be able to do¶
- Trace a durable write and a point read through B-tree and LSM storage engines.
- Choose a reasonable engine for a workload, including the costs hidden by a fast write benchmark.
- Explain why deletion, compaction, and column layout affect disk space and query speed.
The physical problem behind a database write¶
An index tells a database where a key belongs. A storage engine decides how to keep that index and its data on persistent storage. Memory is quick to change but volatile: a process or machine can lose its contents. Storage persists, yet scattered small writes cost more than sequential writes, even on SSDs. The difference is especially pronounced on spinning disks; SSDs also have internal write and erase work. Two common designs make different bargains with these costs.
First, consider durability. A write-ahead log (WAL) records a change by appending it before changing the main data structure. After a crash, the engine can replay committed changes that were logged but not yet applied. An operating system may keep recently written bytes in its own memory. A successful write() therefore does not, by itself, mean those bytes survived power loss. An fsync-style operation asks the OS to flush them to stable storage. The engine must also decide when it acknowledges a commit: acknowledging before the required log sync can lose acknowledged writes. Actual guarantees depend on its configuration and storage stack.
One log, two jobs
The WAL protects against losing recent changes. The main index organizes data for later reads. Logging first does not make every later page update free; it gives the engine a recovery path while those updates happen.
B-tree family: update pages near the key¶
A B-tree family index keeps keys in a balanced tree of fixed-size pages. Internal pages point toward smaller key ranges; leaf pages hold keys and either values or references to rows. To look up a key, follow one path from root to leaf. Nearby keys tend to be near each other in leaf order, which makes range scans natural. PostgreSQL, MySQL/InnoDB, and SQLite use B-tree family structures, though their complete storage designs differ.
Fan-out is the number of branches an internal page can address. With an illustrative fan-out of 500, three branch choices cover roughly 500 × 500 × 500 = 125,000,000 positions. Real capacity depends on page size, key size, fill level, and what counts as a level. The point is that even a large index can be shallow, and upper pages may stay cached in memory.
A write logs its change, then updates the relevant page or pages in place. Inserts may split a full page; deletes and updates can leave partly used space. This is fragmentation. B-tree reads are often efficient, especially point lookups and ordered scans, but a write can require page rewrites in addition to the WAL append. Transactions, buffer caches, and batching change the practical cost; “B-tree” alone does not specify a latency number.
SQLite makes the layout visible: a database file is divided into pages containing table and index B-trees plus pages tracking reusable space. A deleted row can make space reusable inside the file without making the file smaller. Reclaiming the file's size may need a vacuum operation; details depend on the database and its settings.
LSM family: write now, merge later¶
An LSM tree trades immediate page updates for later merging. A write goes to an append-only WAL and a sorted in-memory memtable. When the memtable fills, the engine writes it out as an immutable, sorted file called an SSTable. New writes go into a new memtable. RocksDB, LevelDB, and Cassandra-style storage use this family of ideas, with different compaction policies.
For a point read, check the memtable first, then disk tables from newest to oldest so an overwrite wins. An SSTable's sorted order supports binary search and range iteration, but checking many tables is expensive. A Bloom filter is a small probabilistic summary of keys in a table: “definitely absent” lets the reader skip it; “possibly present” requires a real lookup. False positives waste a lookup, but false negatives would break correctness. A filter cannot replace the table.
Deleting a key writes a tombstone, a marker that hides older values. Simply removing the key from the memtable would let an older SSTable's value reappear. Compaction merges sorted files, keeps the newest version, and can discard overwritten entries and tombstones once no older copy or reader still needs them. That background work costs writes and temporary disk space. A database can run out of disk during compaction even when its final compacted data would fit.
old = {"a": "v1", "b": "keep"}
new = {"a": "v2", "b": None} # None stands for a tombstone here
visible = {**old, **new}
print({key: value for key, value in sorted(visible.items()) if value is not None})
# {'a': 'v2'}
Compaction is a dial, and the best setting moves¶
Compaction has a tunable shape. Picture the levels of an LSM tree, each about T times larger than the one above (T = 10 is a common illustration). Give each level a limit of K sorted runs. K = 1 is leveling: one run per level, so reads probe little, but each merge rewrites much of the level below. K = T is tiering: a level collects many runs before merging, so writes are cheaper, but reads probe more runs and old versions linger longer.
A simplified model of one level shows the trade. A merge into a level with limit K rewrites, on average, about 1/(2K) of that level, so the write amplification the level adds is on the order of T/(2K). A lookup for an absent key probes up to K runs, and each probe costs a disk read only when its Bloom filter gives a false positive, so read cost grows roughly with K × false-positive rate. Raising K lowers write cost and raises read cost. The model assumes absent-key lookups and ignores caches and CPU, so use it for direction, not for numbers.
Workloads shift: a nightly bulk load favors a large K, a daytime read burst a small one. Changing K is where the cost hides. A greedy change merges the level down at once, which means heavy I/O and write stalls. A lazy change waits until the level fills and merges anyway, which costs nothing now but applies late. The FLSM-tree (Mo et al., 2023) lets runs of different sizes sit in the same level. Runs already sealed stay untouched and only the capacity of the active run changes, so the switch moves no data and applies to the very next entry. The price is a few extra runs to probe until the older data merges away.
RusKey, the store built on it in the same paper, chooses K for each level while the workload runs, using reinforcement learning. Operations are grouped into missions. After each mission a critic scores the result with a mix of that level's latency and the whole system's latency, and an actor may move each level's K down one, up one, or leave it. Only the first two levels are learned online; deeper levels are inferred from them with a formula that assumes a particular Bloom filter memory allocation. In the authors' benchmarks no fixed K won every workload, while RusKey stayed close to the best one. Treat this as a research result: the experiments are single-machine and synthetic.
Choose by the work you actually do¶
The three amplifications are useful vocabulary. Read amplification is extra places or bytes consulted per logical read. Write amplification is physical data written per logical write, including logging, page rewrites, and compaction. Space amplification is extra disk occupied by old versions, free space, or files awaiting cleanup. Their exact sizes depend on workload and engine policy.
| Concern | B-tree family | LSM family |
|---|---|---|
| Point reads | Usually one tree path; cached upper pages help | May consult several tables; filters skip definite misses |
| Range scans | Leaf order makes them straightforward | Merge sorted runs; may read several files |
| Writes | WAL plus page updates and possible splits | WAL plus memtable; later flush and compaction |
| Write amplification | Page rewrites and log | Repeated merging plus log |
| Space amplification | Partly filled pages, reusable holes | Old versions and overlapping files until compaction |
| Throughput and latency tail | Often strong for read-heavy, transactional work; page work can slow writes | Often strong for sustained ingest; compaction can hurt tail latency |
Start with a B-tree-based relational engine for read-heavy, transactional applications and an LSM-style engine for heavy ingestion. Treat this as a starting hypothesis, not a rule: cache size, read/write mix, key order, range queries, compaction policy, hardware, and transaction needs can reverse a simple comparison. Benchmark data larger than the cache, with realistic keys, concurrency, and durability settings. Include long enough runs to see compaction, and watch write amplification because extra physical writes matter for SSD endurance.
Row layout, column layout, and file growth¶
The B-tree/LSM choice is about organizing updates and lookup paths. Row versus column layout asks how fields are placed near each other. A row store keeps one record's fields together, which suits “fetch this user and update their status.” A column store groups values from one field across many records, which suits “scan the loss column across millions of training runs.” If a query needs two fields out of twenty, reading column groups can avoid much of the other eighteen. This connects to choosing a datastore: analytics engines often favor columnar layout, while transaction processing commonly favors rows.
Column groups also compress well when adjacent values have similar patterns. Dictionary encoding replaces repeated strings such as status="complete" with small codes plus a dictionary. Compression saves storage and I/O, though decoding consumes CPU. Neither row nor column layout is automatically best for every query. Embedded key-value stores bring the same B-tree/LSM trade-offs into an application process; “embedded” says where the engine runs, not how it writes. Deletion usually marks space reusable before a vacuum or compaction can return bytes to the filesystem.
For AI engineers¶
For AI engineers
Your training script may append logs frequently, write large checkpoints occasionally, and scan immutable dataset shards repeatedly. Appending a log is friendly to sequential I/O; a checkpoint still needs a safe publication and sync policy if you claim it survives a crash. Parquet is a columnar file format: reading only the columns needed for an analysis can avoid unrelated features. Sorted, immutable dataset shards resemble SSTables in how they trade cheap creation for later merge or rewrite work. Analogy, not identity: some vector indexes also build immutable segments and merge them, but their search algorithms and guarantees differ from an LSM key-value store. High-rate metrics ingestion often fits LSM-style buffering and sequential flushes; retention and compaction costs still need capacity planning.
Common mistakes¶
- “LSM is always faster.” A point read may check multiple files, and compaction can make tail latency worse. Measure the workload you will run.
- Ignoring write amplification. A fast memtable write can lead to repeated later writes, using I/O budget and SSD endurance.
- Benchmarking only tiny data. If every index page and table fits in RAM, the test hides storage behavior.
- Equating
write()with durable commit. Check the engine's WAL sync and acknowledgment settings before promising crash survival. - Assuming a delete shrinks the file. Tombstones and free pages usually require later compaction or vacuum to release space.
Check yourself¶
A process acknowledges a write after appending a WAL record but before syncing it. What can a power loss do?
The OS may still have the record only in volatile cache. The acknowledged write can disappear. A durability claim needs a sync policy that covers the log before acknowledgment, plus a storage stack that honors it.
A key was flushed to an old SSTable and then deleted. Why must the delete leave a tombstone?
Without a tombstone, a read that misses the memtable could find the old value in the SSTable and resurrect it. The marker hides that value until safe compaction removes both.
An LSM store shows quick writes for five minutes, then p99 latency spikes and disk usage rises. What should you inspect?
Inspect flush and compaction activity, file counts, free disk, and physical bytes written. Merging old files can consume I/O and temporary space; a short benchmark missed this delayed cost.
A level in an LSM tree has K = 6, and the workload turns write-heavy so you want K = 10. Why can switching the setting hurt, and what does the FLSM-tree avoid?
A greedy switch merges the whole level down immediately, which costs a burst of I/O and can stall writes. A lazy switch costs nothing now but takes effect only after the next full merge. The FLSM-tree leaves sealed runs alone and changes only the active run's capacity, so no data moves and the new K applies to the next entry, at the cost of a few extra runs until older data merges.
A report reads two numeric fields from a table with twenty fields for every row. Which layout is a promising choice, and why?
A columnar layout is promising because it can read the two relevant field groups without fetching the other eighteen. Test it against actual query patterns and compression costs.
Lab¶
Build MiniLSM in code/storage-engines/, using only in-memory tables. Implement writes, overwrites, tombstones, and a memtable flush after its entry limit is exceeded. Make reads search newest first and make range scans return keys in order. Use a Bloom filter to skip definite misses, then compact old tables without changing visible values. Run: cd code/storage-engines && PYTHONPATH=starter python -m pytest tests -q
Go deeper¶
- Interactive: Designed to Scale – storage engines
- Prerequisites: indexes and transactions, choosing a datastore
- Your Software Engineering Handbook, ch. 3 “Cấu trúc dữ liệu & Big-O” (B+Tree)
- Book pointer: Kleppmann, Designing Data-Intensive Applications, chapter 3
- Paper: Mo, Chen, Luo, Shan, “Learning to Optimize LSM-trees: Towards A Reinforcement Learning based Key-Value Store for Dynamic Workloads” (arXiv 2308.07013, SIGMOD 2024)