Skip to main content

Under the Hood of Database Engines: B-Trees vs. LSM-Trees Explained

Updated 4 min readMarkdown
Under the Hood of Database Engines: B-Trees vs. LSM-Trees Explained

When building high-throughput systems, choosing the right database is one of the most critical architecture decisions you will make. However, developers often evaluate databases based solely on query syntax or feature lists, overlooking the most fundamental component: the storage engine.At the core of almost every modern database—from PostgreSQL and MySQL to Cassandra and RocksDB—is a data structure optimized either for read-heavy or write-heavy workloads.In this deep dive, we will unpack the internal mechanics of the two dominant storage engine paradigms: B-Trees and Log-Structured Merge-Trees (LSM-Trees).1. The Core Bottleneck: Disk I/O MechanicsTo understand why database engines are designed the way they are, we must look at physical storage hardware (HDDs and NVMe SSDs).Sequential I/O is significantly faster than Random I/O.SSD Wear & Amplification: Random writes cause block erasure overhead (Garbage Collection) on SSDs, reducing hardware lifespan and increasing latency spikes.Storage engines are fundamentally trade-off engines designed to manage this disk I/O reality.2. B-Trees: The In-Place Update ParadigmIntroduced by Rudolf Bayer and Edward M. McCreight in 1970, B-Trees (and their variants like \(B^+\)-Trees) remain the default storage engine structure for traditional relational databases like PostgreSQL (InnoDB/Heap) and MySQL.Architectural LayoutA B-Tree breaks the database down into fixed-size pages (typically 4KB to 16KB) and maps directly to the underlying hardware disk blocks. [ Root Page ] /
[ Internal Page ] [ Internal Page ] / | \ |
[Leaf] [Leaf] [Leaf] [Leaf] [Leaf] (Contains actual rows/pointers) Pages: The tree consists of Root Pages, Internal Pages, and Leaf Pages.In-Place Updates: When a row is updated, the engine overwrites the specific page on disk containing that record.\(B^+\)-Tree Variation: Leaf pages form a doubly linked list, enabling highly efficient sequential range scans (\(O(\log N)\) point lookups + sequential traversal).The Trade-offPros (Fast Reads): Point lookups require traversing only \(O(\log N)\) depth. Since pages are balanced, read latency is deterministic and low.Cons (Random Write Overhead): Every insert/update requires modifying random pages on disk. To prevent corruption during crashes, B-Trees require a Write-Ahead Log (WAL), meaning every write is written twice (once to the WAL sequentially, once to the page randomly).3. LSM-Trees: The Append-Only Paradigmpopularized by Google’s Bigtable paper and used in Cassandra, ScyllaDB, and RocksDB, the Log-Structured Merge-Tree (LSM-Tree) turns random writes into sequential writes.Architectural ComponentsInstead of overwriting data in place, LSM-Trees treat disk writes as append-only immutable logs.[ Write ] ──> 1. WAL (Disk, Sequential) │ ▼ 2. MemTable (In-Memory RAM Buffer / Red-Black Tree) │ ▼ (Flush when full) 3. SSTables (Sorted String Tables on Disk) [ Level 0 ] ──(Compaction)──> [ Level 1 ] ──> [ Level 2 ] MemTable: An in-memory write buffer (usually implemented as a SkipList or Red-Black Tree). Incoming writes (INSERT, UPDATE, DELETE) are appended here in sorted order.SSTable (Sorted String Table): When the MemTable reaches capacity, it is flushed to disk as an immutable, sorted file called an SSTable.Compaction: Background threads merge overlapping SSTables, removing deleted/overwritten records to reclaim disk space and keep read performance manageable.The Trade-offPros (Blazing Fast Writes): Writes append sequentially to the WAL and MemTable in RAM, bypassing random disk I/O entirely.Cons (Read & Compaction Overhead): To read a key, the database must check the MemTable, then search down through multiple SSTable levels. Databases use Bloom Filters in RAM to avoid reading SSTables that do not contain the target key.4. Deep Comparison: B-Tree vs. LSM-TreeFeatureB-Tree (B+-Tree)LSM-TreePrimary WorkloadRead-heavy / Transactional (OLTP)Write-heavy / Ingestion / Time-seriesWrite MechanismIn-place update (Random Disk I/O)Append-only (Sequential Disk I/O)Read Complexity\(O(\log N)\) (Direct page lookup)Variable (MemTable + Bloom Filter + SSTables)Space AmplificationMedium (Fragmented pages/padding)Variable (Increases until compaction runs)Write AmplificationHigh (WAL + Page Overwrites)Medium-High (Repeated Compaction cycles)ACID SuitabilityExcellent for strong isolation levelsRequires extra concurrency controlExamplesPostgreSQL, MySQL (InnoDB), SQLiteRocksDB, Apache Cassandra, LevelDB5. Decision Framework: Which One Should You Choose?When designing system architecture, use this rule of thumb:Choose a B-Tree Engine (e.g., PostgreSQL, MySQL) if your application requires strict ACID transactions, complex join queries, and predictable point-read performance (e.g., e-commerce order management, financial ledgers).Choose an LSM-Tree Engine (e.g., Cassandra, RocksDB) if your workload is append-heavy, involves massive log/metric ingestion, or demands maximum write throughput with high availability (e.g., IoT data streams, messaging apps, event logging).ConclusionNeither structure is inherently superior; each represents a different compromise between read amplification, write amplification, and space amplification (the RUM Conjecture).Understanding these underlying storage mechanics allows you to select database technologies based on hardware realities rather than marketing 恋みくじ hype.

21 views

About the author

  • 日本文化と日常の小さな楽しみを、Webで気軽に体験できるサイト 一禅堂 を個人で企画・開発しています。 一禅堂では、今の恋愛運や相手との関係を楽しく占える「恋みくじ」、毎日の運勢を気軽に楽しめる「おみくじ」、漢字の読み方・意味・筆順を調べられる「漢字辞典」など、実用性と日本らしい体験を大切にしたコンテンツを公開しています。 Hashnodeでは、サイト開発を通して得た知識を中心に、フロントエンド開発、UI/UX、多言語対応、プライバシーに配慮した設計、SEO、静的サイトの運用について発信します。
    一禅堂の 恋みくじ 公式サイト
    漢字辞典: 漢字書き順
    神社 おみくじ
Hhaleo2mo ago

A useful follow-up would be a benchmark comparing the two approaches under mixed workloads rather than pure reads or writes. Read/write ratios, key distribution, cache size, compaction strategy, and storage hardware can all change the result.

Ddozen2mo ago

B-Trees remain compelling for applications that need frequent point reads and ordered range queries. Their update path may be less write-friendly, but predictable lookup behavior can be more valuable than maximizing raw ingestion throughput.

Jjkwho2mo ago

Bloom filters are an interesting part of the LSM design. They can avoid many unnecessary table lookups, but they also introduce memory costs and false positives. Choosing the right filter size becomes another workload-dependent trade-off.

Llove2mo ago

Compaction is the part of LSM-Trees that deserves special attention. Fast writes can look ideal in a benchmark, but write amplification, temporary disk usage, and latency spikes during compaction can change the production picture significantly.

Jjohson2mo ago

The most useful takeaway is that neither structure is universally better. B-Trees often provide predictable reads and range scans, while LSM-Trees trade additional read and compaction work for efficient sequential writes. The workload should drive the choice.