Skip to main content
← CONCEPTS / ALGORITHMS & DATA STRUCTURES
An end-to-end domain learning journey

Database Indexing: B-Trees
vs LSM-Trees.

B-Trees organize sorted keys into fixed-size mutable pages optimized for fast, predictable point and range reads, whereas LSM-Trees buffer writes in memory and flush immutable sorted runs to disk for high write throughput.
Start the journey7 sections· Last modified Nov 29, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

If disk I/O or compaction stalls threaten tail latency, choose B-Trees for read-heavy OLTP workloads needing predictable p99 read latency and in-place updates; choose LSM-Trees for write-heavy ingestion, time-series, and high-compression workloads.

TL;DR30-second simplified summary
▾

Core Mechanics: Storage engines balance three competing costs (The RUM Conjecture): Read Amplification, Write (Update) Amplification, and Space (Memory) Amplification.

Visual & Structural Flow: Depicts B-Tree 3-Level Traversal & Covering Leaf Page (Root Page (RAM) -> Internal [A..M] -> Internal [N..Z] -> Leaf #8812); RocksDB Write-Optimized MemTable, L0/L1 SSTables & Bloom Filters (WAL + MemTable -> L0 SSTables -> L1-Ln Leveled -> Zstd SSTables).

Trade-Offs & Production: Within LSM-Trees, compaction strategy governs write vs. read vs. space amplification. Monitor l0_num_files (approaching level0_stop_writes_trigger freezes writes!), pending compaction bytes, and tombstone-to-live-row ratios on LSM nodes; on PostgreSQL B-Trees.

Failure Modes & Application: Dive deeper into LSM storage engines, Cassandra tombstone scans, B-Tree type-coercion invalidation, and PostgreSQL VACUUM bloat.

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 Database Indexing: B-Trees vs LSM-Trees 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 balance three competing costs (The RUM Conjecture): Read Amplification, Write (Update) Amplification, and Space (Memory) Amplification.

  • B-Trees (Update-in-Place): Store sorted keys in fixed-size mutable pages (8 KB in PostgreSQL, 16 KB in InnoDB) with 3–4 levels for 100M+ rows (O(log N) reads). Updates modify leaf pages in place via WAL and split full pages.
  • LSM-Trees (Out-of-Place): Append writes sequentially to a WAL + in-memory MemTable (skiplist), flushing immutable sorted SSTables to disk and merging them asynchronously via compaction.
Update-in-Place Index

B-Tree 3-Level Traversal & Covering Leaf Page

Root Page (RAM)Fan-out ~500 keysInternal [A..M]Internal [N..Z]Page 0Leaf #8Page 2Page 3

B-Trees traverse a fixed 3–4 level path to contiguous leaf pages, yielding tight, predictable p99 read and range-scan latency.

02
STAGE 02 · WHY WE NEED ITL4 · FUNDAMENTALS

Why Picking the Wrong Index Structure Causes IOPS Cliffs.

Why this matters: The problem: see what breaks without Why Picking the Wrong Index Structure Causes IOPS Cliffs under real concurrency or scale.

Think of Why Picking the Wrong Index Structure Causes IOPS Cliffs as the intuition layer for Database Indexing: B-Trees vs LSM-Trees: The problem: see what breaks without Why Picking the Wrong Index Structure Causes IOPS Cliffs under real concurrency or scale.

Picking a B-Tree for random high-velocity writes turns 100-byte inserts into random 8–16 KB page reads, splits, and full-page WAL writes; picking an LSM-Tree for uncached point lookups without Bloom filters fans out across dozens of SSTables.

LSM-Tree Read/Write Path

RocksDB Write-Optimized MemTable, L0/L1 SSTables & Bloom Filters

WAL + MemTable64MB Skiplist (us…L0 SSTablesOverlapping + Bloom 1%L1-Ln Leveled10x/level…Zstd SSTables~1.1x space, 2-4x…64MB Skiplist (uswrite)Overlapping + Bloom 1%10x/levelnon-overlapping

LSM-Trees turn random writes into sequential WAL + SSTable flushes while per-file Bloom filters (~10 bits/key) skip 99% of disk reads.

Engineering Decision Framework
Problem
How to implement Database Indexing: B-Trees vs LSM-Trees 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
If disk I/O or compaction stalls threaten tail latency, choose B-Trees for read-heavy OLTP workloads needing predictable p99 read latency and in-place updates; choose LSM-Trees for write-heavy ingestion, time-series, and high-compression workloads.
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 Database Indexing: B-Trees vs LSM-Trees experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

IoT Telemetry: InnoDB vs. RocksDB (120k Writes/Sec)

Random UUIDv4 primary keys saturated NVMe IOPS in InnoDB due to 16 KB page splits. Moving to RocksDB converted writes into sequential WAL + SSTable flushes, cutting write IOPS by 6x and disk footprint by 55%.

Covering B-Tree Index Dropping p99 from 45ms to 1.8ms

On a 400M-row Postgres orders table, adding (customer_id, created_at DESC) INCLUDE (status, total_cents) enabled Index-Only Scans without heap fetches.

03
STAGE 03 · WHERE IT IS USEDL5 · APPLIED DESIGN

Where B-Trees vs. 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 vs. LSM-Trees Belong as the intuition layer for Database Indexing: B-Trees vs LSM-Trees: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Match the storage engine to your read/write ratio, key ordering, and compression requirements.

ChoiceWhat it buysWhat it costs
B-Trees (PostgreSQL, MySQL InnoDB)Best for read-heavy OLTP, frequent in-place updates, fast `BETWEEN` range scans, and strict p99 read SLAs.Random UUIDv4 keys cause severe page splits and ~67% fill fragmentation.
LSM-Trees (RocksDB, Cassandra, ScyllaDB, Pebble)Best for write-heavy telemetry, event logs, time-series, and 2–4x Zstd SSTable compression.Background compaction can spike tail latency; deletes leave tombstones that slow range scans.
Avoid: Excessive Secondary Indexes on Write-Heavy TablesKeep only indexes justified by query plans.Every secondary index multiplies write amplification on every insert/update.
04
STAGE 04 · HOW IT IS MANAGEDL5 · APPLIED DESIGN

How to Tune Keys, Covering Indexes & LSM Compaction.

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

1.

Time-Ordered Keys on B-Trees: Use UUIDv7, ULID, or monotonic sequences so inserts append to the rightmost leaf page. 2. Equality-First Composite Columns: Order columns by equality predicates first, then range predicates: (tenant_id, created_at) + INCLUDE (status).

Lifecycle & Failure Recovery

How to Tune Keys, Covering Indexes & LSM Compaction

index scanfsync WALdeadlock / skewTx Active(Snapshot)Row Lock HeldWAL FlushedSerializationRetry
-- PostgreSQL covering B-Tree index enabling Index-Only Scans (no heap fetch)
CREATE INDEX CONCURRENTLY idx_orders_cust_recent
ON orders (customer_id, created_at DESC)
INCLUDE (status, total_cents);

-- Verify Index-Only Scan and zero heap fetches:
EXPLAIN (ANALYZE, BUFFERS)
SELECT status, total_cents FROM orders
WHERE customer_id = 48291 ORDER BY created_at DESC LIMIT 20;
05
STAGE 05 · ALTERNATIVESL6 · SCALE & TRADE-OFFS

Alternatives: Leveled (LCS) vs. Size-Tiered (STCS) vs. Time-Window (TWCS).

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

Within LSM-Trees, compaction strategy governs write vs.

read vs.

Design Trade-Off

Alternatives: Leveled (LCS) vs. Size-Tiered (STCS) vs. Time-Window (TWCS)

Before · Seq Scan + Unbounded Bloat
  • Implicit cast breaks B-Tree
  • Deadlock or XID wraparound risk
  • Long tx blocks VACUUM
After · Indexed Plan + Bounded MVCC
  • Index-only scan in <2 ms
  • Deterministic lock ordering
  • Autovacuum keeps bloat flat
ChoiceWhat it buysWhat it costs
Leveled Compaction (LCS — RocksDB Default)Low ~1.1x space amplification; non-overlapping L1..Ln bounds point-read checks.Higher 10–30x write amplification from frequent cross-level merges.
Size-Tiered Compaction (STCS — Cassandra Default)Low write amplification for pure append workloads.Requires 50% free disk headroom (up to 2x temporary space amplification) and hurts read latency.
Time-Window Compaction (TWCS)Drops expired 1-day time-series SSTable buckets instantly without compaction overhead.Only works when writes and TTLs align strictly with time windows.
06
STAGE 06 · PRODUCTION ARCHITECTUREL7 · STAFF / PRINCIPAL

Production Architecture: Avoiding Write Stalls & Tombstone Scans.

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

Think of Production Architecture: Avoiding Write Stalls & Tombstone Scans as the intuition layer for Database Indexing: B-Trees vs LSM-Trees: Production architecture: see how the components compose end to end under real load.

Monitor l0_num_files (approaching level0_stop_writes_trigger freezes writes!), pending compaction bytes, and tombstone-to-live-row ratios on LSM nodes; on PostgreSQL B-Trees, tune autovacuum and run REINDEX CONCURRENTLY when bloat exceeds 30%.

Prefix Bloom Filters for Short Range Scans

Storing a Bloom filter on key prefixes (e.g., tenant_id) lets LSM range scans (WHERE tenant_id = 'acme' AND ts >...) skip irrelevant SSTables.

Never Use LSM Tables as FIFO Queues

Rapidly inserting and deleting keys in an LSM store leaves millions of tombstones in L0–L2, slowing SELECT range scans from 2 ms to 2 seconds.

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

Problems solved & Related Concepts.

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

Think of Problems solved & Related Concepts as the intuition layer for Database Indexing: B-Trees vs LSM-Trees: Applied problems: connect these internals to concrete system design and debugging scenarios.

Dive deeper into LSM storage engines, Cassandra tombstone scans, B-Tree type-coercion invalidation, and PostgreSQL VACUUM bloat.

Component Topology

Problems solved & Related Concepts

Client TxingressQuery PlannercomputeWAL BufferstorageStorage PagescontrolSQL queryappend redocheckpoint flush
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 4
Score: 0/4

A PostgreSQL table uses random UUIDv4 primary keys and suffers severe NVMe IOPS saturation and WAL bloat during 50k/sec inserts. Why, and what fixes it?

Recommended Learning Flow