Skip to main content
← CONCEPTS / DATABASES & STORAGE
An end-to-end domain learning journey

B-Tree vs. LSM-Tree
Storage Engines.

B-Trees update fixed-size disk pages (4-16 KiB) in place for fast, predictable point and range reads, whereas LSM-Trees buffer writes sequentially in memory (MemTable + WAL) and merge immutable sorted runs (SSTables) in the background for orders-of-magnitude higher write throughput.
Start the journey7 sections· Last modified Nov 29, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

To keep storage layouts predictable as data grows, B-Trees optimize read latency and predictability at the cost of random-write amplification, while LSM-Trees maximize sequential write throughput at the cost of background compaction I/O and multi-level read amplification.

TL;DR30-second simplified summary
▾

Core Mechanics: Storage engines bridge volatile RAM and persistent block storage (NVMe/SSD).

Visual & Structural Flow: Depicts B+Tree Mutable Page Lookup vs. LSM-Tree MemTable/SSTable Hierarchy (Root / MemTable -> Internal / L0 SST -> L1..Ln SSTables -> Leaf 8-16KiB); WAL + MemTable -> Immutable L0 -> Leveled Compaction (PUT(user:4812) -> Immutable MemTable -> L0 -> L1 Compaction -> vLog / Titan (opt)); Multi-Raft Consensus -> RocksDB LSM + Bloom + Block Cache (Multi-Raft Leader -> RocksDB / Pebble -> Titan vLog (SSD)).

Trade-Offs & Production: Compare page unit, read/write amplification, and compaction behavior across the three dominant disk-backed index families. Distributed NewSQL/KV engines like TiKV and CockroachDB (Pebble) run an LSM-Tree per node underneath Multi-Raft consensus groups.

Failure Modes & Application: Explore LSM storage design, Cassandra tombstone scans, and B-Tree index invalidation.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
PRIME Core Invariants & Workload Constraints
Establish concrete scale, latency, memory, and concurrency bounds for B-Tree vs. LSM-Tree Storage Engines before selecting data structures or storage components.
Failure Boundaries & Operational Trade-Offs
Identify hot-key skew, partial failures, resource leaks, and when simpler single-node or standard alternatives outperform complex designs.
Full walkthrough · 7 stages
01
STAGE 01 · WHAT IT ISL4 · FUNDAMENTALS

What are B-Trees and LSM-Trees.

Why this matters: The mechanism: understand how B-Trees and LSM-Trees works from first principles.

Storage engines bridge volatile RAM and persistent block storage (NVMe/SSD). A B+Tree (8 KiB pages in PostgreSQL, 16 KiB in InnoDB) organizes keys in mutable, fixed-size pages linked in sorted order; with height 3–4 for 1B+ rows, internal nodes stay cached in RAM so point lookups need at most 1–2 disk reads.

A Log-Structured Merge-Tree (LSM-Tree) (RocksDB, Cassandra, Pebble) never mutates on-disk blocks in place. Writes append to a sequential WAL and an in-memory skiplist (MemTable), flushing immutable sorted SSTables (~64 MiB) to disk and merging them asynchronously in the background.

Storage Layout

B+Tree Mutable Page Lookup vs. LSM-Tree MemTable/SSTable Hierarchy

Root / MemTableRAM hot index / skiplistInternal / L0 SSTL1..Ln SSTablesPage 0Leaf 8-Page 2Page 3

1.B+Tree Read Path: Traverses 3-4 cached internal pages to a single mutable leaf page (predictable p99).

2.LSM Write Path: Appends sequentially to WAL + MemTable; zero random page rewrites on the hot path.

3.Bloom Filter Guard: 10 bits/key (~1% FP) lets LSM point reads skip SSTables that do not contain the key.

B+Trees pay random-write amplification for 1-lookup reads; LSM-Trees batch sequential writes and pay background compaction.

02
STAGE 02 · WHY WE NEED ITL4 · FUNDAMENTALS

Why we need LSM-Trees (and the RUM Conjecture trade-offs).

Why this matters: The problem: see what breaks without LSM-Trees under real concurrency or scale.

Under heavy random-key INSERT/UPDATE workloads (time-series, IoT, write-heavy KV), B+Trees suffer 10x–30x+ write amplification because modifying 100 bytes dirties an entire 8–16 KiB page (plus full-page WAL writes).

However, the RUM Conjecture proves you cannot minimize Read, Update/Write, and Memory/Space overhead simultaneously. LSM-Trees face two signature failure modes: L0 Compaction Stalls (hitting level0_stop_writes_trigger, default 36 in RocksDB, freezes all writes) and Tombstone Scan Degradation on range queries over deleted keys.

LSM Write & Compaction Path

WAL + MemTable -> Immutable L0 -> Leveled Compaction

PUT(user:4812)Sequential WAL + MemTableImmutable MemTableFlush 64 MiB L0 SSTableL0 -> L1 CompactionMerge-sort + drop…vLog / Titan (opt)Separate values > 1 KiB

1.Sequential I/O: Writes never seek random B-Tree leaf pages; MemTable flushes sequentially.

2.Write-Stall Risk: If background compaction falls behind L0 flushes, RocksDB throttles or stops foreground writes.

3.WiscKey / Titan: Separating large values (>1 KiB) into an append-only vLog cuts compaction write amplification sharply.

LSM-Trees convert random writes into sequential flushes, but compaction bandwidth must keep pace with ingestion.

Engineering Decision Framework
Problem
How to implement B-Tree vs. LSM-Tree Storage Engines without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
To keep storage layouts predictable as data grows, b-Trees optimize read latency and predictability at the cost of random-write amplification, while LSM-Trees maximize sequential write throughput at the cost of background compaction I/O and multi-level read amplification.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When B-Tree vs. LSM-Tree Storage Engines experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

PostgreSQL Checkpoint Storms

In B-Trees, flushing thousands of dirty buffer-pool pages saturates NVMe queues unless checkpoint_completion_target is tuned (e.g. 0.9).

B-epsilon Trees

Hybrid B-epsilon trees attach small write buffers to internal B-Tree nodes to batch writes while preserving fast range scans.

03
STAGE 03 · WHERE IT IS USEDL5 · APPLIED DESIGN

Where B-Trees and LSM-Trees belong.

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Think of Where B-Trees and LSM-Trees belong as the intuition layer for B-Tree vs. LSM-Tree Storage Engines: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Match the storage engine to your read/write ratio, range-scan frequency, and latency SLA.

ChoiceWhat it buysWhat it costs
B+Tree (PostgreSQL, MySQL InnoDB)Predictable point & range read latency; strong in-place MVCC/row-lock semantics for OLTP.High random-write amplification (10-30x+) and page fragmentation under heavy random inserts.
Leveled LSM-Tree (RocksDB, Pebble, TiKV)High write throughput, ~10x space amplification control, fast point reads with Bloom filters.Higher compaction write amplification than Size-Tiered; L0 stalls if compaction lags.
Size-Tiered LSM (Cassandra STCS)Lowest write amplification for append-heavy time-series and logging workloads.Up to 50% temporary disk space overhead during major compactions; slower point/range reads.
04
STAGE 04 · HOW IT IS MANAGEDL5 · APPLIED DESIGN

How Compaction, Bloom Filters, and Checkpoints are tuned.

Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.

Tune each engine around its bottleneck:

  1. LSM-Tree: Size bits_per_key = 10 (~1% false positive Bloom filter), pin L0/L1 index & filter blocks in block cache, and dedicate enough background compaction threads (max_background_jobs) so L0 never hits level0_stop_writes_trigger.
  2. B+Tree: Keep working set in shared_buffers / innodb_buffer_pool_size (~70-80% RAM), set checkpoint_completion_target = 0.9, and use k-ordered primary keys (UUIDv7 / Snowflake) instead of random UUIDv4 to eliminate page splits.
Request & State Flow

How Compaction, Bloom Filters, and Checkpoints are tuned

Client TxPlanner / Lock MgrWAL / MemTableHeap / SSTable1. Acquire snapshot / index plan2. Append redo record + fsync WAL3. Flush dirty pages / compactSSTables4. Commit & release row locks
# Minimal LSM-Tree MemTable + SSTable Bloom Filter & Tombstone lookup (Python)
class MiniLsmEngine:
 def __init__(self, memtable_limit: int = 1024):
 self.memtable: dict[str, bytes | None] = {}
 self.sstables: list[tuple[set[str], dict[str, bytes | None]]] = [] # (bloom_approx, sorted_run)
 self.limit = memtable_limit

 def put(self, key: str, val: bytes | None) -> None:
 self.memtable[key] = val # None represents a deletion tombstone
 if len(self.memtable) >= self.limit:
 self._flush_to_l0()

 def get(self, key: str) -> bytes | None:
 if key in self.memtable:
 return self.memtable[key]
 for bloom, sstable in reversed(self.sstables): # newest L0 -> oldest Ln
 if key not in bloom: # Bloom filter skips SSTable I/O
 continue
 if key in sstable:
 return sstable[key] # returns None if tombstone
 return None
05
STAGE 05 · ALTERNATIVESL6 · SCALE & TRADE-OFFS

Alternatives: B+Tree vs. Leveled LSM vs. Size-Tiered LSM.

Why this matters: The trade-off: compare competing approaches across latency, consistency, and operational cost.

Think of Alternatives: B+Tree vs. Leveled LSM vs. Size-Tiered LSM as the intuition layer for B-Tree vs. LSM-Tree Storage Engines: The trade-off: compare competing approaches across latency, consistency, and operational cost.

Compare page unit, read/write amplification, and compaction behavior across the three dominant disk-backed index families.

Component Topology

Alternatives: B+Tree vs. Leveled LSM vs. Size-Tiered LSM

Client TxingressQuery PlannercomputeWAL BufferstorageStorage PagescontrolSQL queryappend redocheckpoint flush
ChoiceWhat it buysWhat it costs
B+Tree (InnoDB / PostgreSQL)1-2 IOs on cold point reads; zero compaction stalls; fast ordered range scans.Random-write amplification and B-Tree page splits on random UUID keys.
Leveled Compaction LSM (RocksDB)Disjoint key ranges per level L1+; low space amplification (~1.1x) and good read p99.10-30x compaction write amplification as levels merge repeatedly.
Size-Tiered Compaction LSM (Cassandra STCS)Lowest write amplification; ideal for write-once immutable time-series.High read amplification and 2x disk headroom required for major compaction.
06
STAGE 06 · PRODUCTION ARCHITECTUREL7 · STAFF / PRINCIPAL

Production example: Distributed KV Store (Multi-Raft + RocksDB + Titan).

Why this matters: Production architecture: see how the components compose end to end under real load.

Think of Production example: Distributed KV Store (Multi-Raft + RocksDB + Titan) as the intuition layer for B-Tree vs. LSM-Tree Storage Engines: Production architecture: see how the components compose end to end under real load.

Distributed NewSQL/KV engines like TiKV and CockroachDB (Pebble) run an LSM-Tree per node underneath Multi-Raft consensus groups. Separating large values (>1 KiB) into an append-only Titan/vLog keeps the LSM key-index compact in RAM while bounding compaction I/O.

Distributed Storage Node

Multi-Raft Consensus -> RocksDB LSM + Bloom + Block Cache

Multi-Raft LeaderReplicates write batchRocksDB / PebbleWAL + MemTable + SSTTitan vLog (SSD)Values > 1 KiBQuorum commit -> Apply

1.Write-Group Batching: Coalesces concurrent Raft commits into a single RocksDB WriteBatch + fsync.

2.Block Cache Pinning: Pin L0/L1 filter and index blocks in RAM so point reads avoid extra SSD seeks.

3.Rate-Limited Compaction: Cap compaction MB/s so background merges never starve foreground read tail latency.

Pairing Multi-Raft with rate-limited RocksDB compaction delivers linearizable writes and predictable reads.

07
STAGE 07 · PROBLEMS SOLVED & FURTHER DEEP DIVEL7 · STAFF / PRINCIPAL

Problems solved by Storage Engine Tuning & Deep Dives.

Why this matters: Applied problems: connect these internals to concrete system design and debugging scenarios.

Think of Problems solved by Storage Engine Tuning & Deep Dives as the intuition layer for B-Tree vs. LSM-Tree Storage Engines: Applied problems: connect these internals to concrete system design and debugging scenarios.

Explore LSM storage design, Cassandra tombstone scans, and B-Tree index invalidation.

Lifecycle & Failure Recovery

Problems solved by Storage Engine Tuning & Deep Dives

index scanfsync WALdeadlock / skewTx Active(Snapshot)Row Lock HeldWAL FlushedSerializationRetry
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 4
Score: 0/4

Why does inserting random UUIDv4 primary keys into a large PostgreSQL or InnoDB B+Tree table degrade write throughput far more than inserting monotonic UUIDv7 / Snowflake IDs?

Recommended Learning Flow