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.
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.
B-Tree 3-Level Traversal & Covering Leaf Page
B-Trees traverse a fixed 3–4 level path to contiguous leaf pages, yielding tight, predictable p99 read and range-scan latency.
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.
RocksDB Write-Optimized MemTable, L0/L1 SSTables & Bloom Filters
LSM-Trees turn random writes into sequential WAL + SSTable flushes while per-file Bloom filters (~10 bits/key) skip 99% of disk reads.
- 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.
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.
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.
| Choice | What it buys | What 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 Tables | Keep only indexes justified by query plans. | Every secondary index multiplies write amplification on every insert/update. |
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).
How to Tune Keys, Covering Indexes & LSM Compaction
-- 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;
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.
Alternatives: Leveled (LCS) vs. Size-Tiered (STCS) vs. Time-Window (TWCS)
- Implicit cast breaks B-Tree
- Deadlock or XID wraparound risk
- Long tx blocks VACUUM
- Index-only scan in <2 ms
- Deterministic lock ordering
- Autovacuum keeps bloat flat
| Choice | What it buys | What 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. |
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.
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.
Problems solved & Related Concepts
Practice: Make the trade-off yourself.
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?