Home CS Fundamentals B-Tree vs LSM-Tree: Deep Dive into Database Storage Engines
Advanced 3 min · July 13, 2026

B-Tree vs LSM-Tree: Deep Dive into Database Storage Engines

Explore B-Tree and LSM-Tree storage engines: internals, trade-offs, real-world incidents, and debugging techniques.

N
Naren Founder & Principal Engineer

20+ years shipping production systems from the metal up. Notes here come from systems that actually shipped.

Follow
Production
production tested
July 13, 2026
last updated
2,165
articles · all by Naren
Before you start⏱ 20-25 min read
  • Basic understanding of databases and SQL
  • Familiarity with data structures (trees, hash tables)
  • Knowledge of disk I/O and caching concepts
 ● Production Incident 🔎 Debug Guide ⚙ Triage Commands
Quick Answer
  • B-Trees provide balanced tree structures for efficient point lookups and range scans.
  • LSM-Trees use append-only writes and compaction for high write throughput.
  • B-Trees are better for read-heavy workloads; LSM-Trees excel in write-heavy scenarios.
  • Both have trade-offs in space amplification, write amplification, and read performance.
  • Real-world databases like MySQL (InnoDB) use B-Trees; Cassandra and LevelDB use LSM-Trees.
✦ Definition~90s read
What is Database Internals?

A B-Tree is a self-balancing tree data structure that maintains sorted data for efficient insertion, deletion, and search operations, while an LSM-Tree is a log-structured merge tree that optimizes write throughput by batching writes and merging sorted files.

Imagine a library.
Plain-English First

Imagine a library. A B-Tree is like a well-organized card catalog where every book has a fixed spot, making it easy to find a specific book quickly. An LSM-Tree is like a pile of new books on a desk that are periodically sorted and merged into the shelves. Adding a new book is fast (just put it on the pile), but finding an old book might require checking multiple piles.

When you query a database, the storage engine silently works behind the scenes to fetch or write data efficiently. Two dominant data structures power most modern databases: B-Trees and LSM-Trees. Understanding their internals is crucial for optimizing performance, diagnosing production issues, and designing scalable systems. B-Trees, used by MySQL InnoDB and PostgreSQL, offer balanced read performance with predictable latency. LSM-Trees, powering Cassandra, RocksDB, and LevelDB, prioritize write throughput by batching writes and deferring organization. This article dissects both structures, compares their trade-offs, and provides practical debugging guides. You'll learn how to choose the right engine for your workload, diagnose common pitfalls, and avoid production incidents.

B-Tree Internals: Structure and Operations

A B-Tree is a self-balancing tree data structure that maintains sorted data and allows searches, sequential access, insertions, and deletions in logarithmic time. It is optimized for systems that read and write large blocks of data. The tree consists of nodes: internal nodes contain keys and pointers to child nodes, while leaf nodes contain actual data or pointers to data. The height of the tree is kept low by having a high branching factor (often hundreds of children per node). This minimizes disk I/O because each node corresponds to a disk page. Insertions and deletions may cause node splits or merges to maintain balance. B-Trees are the default storage engine for many relational databases (e.g., InnoDB, PostgreSQL). They excel at point queries and range scans due to their sorted structure. However, they suffer from write amplification because updates often require rewriting entire pages.

b-tree-schema.sqlSQL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
-- Example: Creating a B-Tree index in MySQL (InnoDB)
CREATE TABLE employees (
    id INT PRIMARY KEY,
    name VARCHAR(100),
    department VARCHAR(50),
    salary DECIMAL(10,2),
    INDEX idx_department (department)
) ENGINE=InnoDB;

-- Insert some data
INSERT INTO employees VALUES
(1, 'Alice', 'Engineering', 90000),
(2, 'Bob', 'Marketing', 80000),
(3, 'Charlie', 'Engineering', 95000);

-- Query using the index
EXPLAIN SELECT * FROM employees WHERE department = 'Engineering';
Output
id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra
1 | SIMPLE | employees | ref | idx_department | idx_department | 202 | const | 2 | Using index condition
🔥B-Tree vs B+Tree
📊 Production Insight
In production, monitor the buffer pool hit ratio. A low ratio indicates insufficient memory, leading to increased disk I/O and latency.
🎯 Key Takeaway
B-Trees provide balanced read performance with predictable latency, ideal for OLTP workloads with frequent point queries and range scans.

LSM-Tree Internals: Structure and Operations

An LSM-Tree (Log-Structured Merge-Tree) is designed for high write throughput by converting random writes into sequential writes. Data is first written to an in-memory memtable (often a sorted structure like a red-black tree). When the memtable reaches a threshold, it is flushed to disk as an immutable SSTable (Sorted String Table). Over time, multiple SSTables accumulate, and a background compaction process merges them to maintain order and reclaim space. Reads must check the memtable and all SSTables, so bloom filters are used to quickly skip irrelevant SSTables. LSM-Trees are used in NoSQL databases like Cassandra, HBase, and key-value stores like RocksDB and LevelDB. They excel in write-heavy workloads but can suffer from read amplification and compaction overhead. Write amplification is a key concern: each write may be rewritten multiple times during compaction.

lsm-tree-schema.cqlSQL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
-- Example: Creating a table in Cassandra (LSM-Tree based)
CREATE TABLE sensor_data (
    sensor_id UUID,
    timestamp TIMESTAMP,
    value DOUBLE,
    PRIMARY KEY (sensor_id, timestamp)
) WITH compaction = { 'class': 'LeveledCompactionStrategy' };

-- Insert some data
INSERT INTO sensor_data (sensor_id, timestamp, value) VALUES
(uuid(), '2023-01-01 00:00:00', 23.5),
(uuid(), '2023-01-01 00:01:00', 24.0);

-- Query using partition key
SELECT * FROM sensor_data WHERE sensor_id = ?;
Output
sensor_id | timestamp | value
--------------------------------------+----------------------------+-------
123e4567-e89b-12d3-a456-426614174000 | 2023-01-01 00:00:00.000000 | 23.5
123e4567-e89b-12d3-a456-426614174000 | 2023-01-01 00:01:00.000000 | 24.0
⚠ Compaction Strategies
📊 Production Insight
Monitor compaction backlog and write amplification factor. A high backlog indicates that compaction cannot keep up, leading to read amplification and potential disk space issues.
🎯 Key Takeaway
LSM-Trees optimize for write throughput by batching writes and deferring organization, but require careful tuning of compaction to avoid performance degradation.

Read and Write Amplification: The Hidden Cost

Amplification factors measure the extra I/O caused by the storage engine. Write amplification (WA) is the ratio of bytes written to disk to bytes written by the application. B-Trees have moderate WA due to page splits and writes, while LSM-Trees can have high WA during compaction. Read amplification (RA) is the number of disk reads per query. B-Trees have low RA for point queries (one or two page reads), but LSM-Trees may need to check multiple SSTables. Bloom filters reduce RA by eliminating unnecessary SSTable reads. Space amplification (SA) is the ratio of disk space used to logical data size. LSM-Trees can have high SA if compaction lags, leaving obsolete data. Understanding these trade-offs helps in selecting the right engine and tuning parameters. For example, in a write-heavy logging system, LSM-Tree with leveled compaction may be optimal, while a user profile database with frequent reads benefits from B-Tree.

amplification-metrics.sqlSQL
1
2
3
4
5
6
7
8
9
10
-- Check write amplification in MySQL (InnoDB)
SHOW GLOBAL STATUS LIKE 'Innodb_data_written';

-- Check disk space usage
SELECT table_schema, SUM(data_length + index_length) / 1024 / 1024 AS size_mb
FROM information_schema.tables
GROUP BY table_schema;

-- For Cassandra, check compaction metrics
SELECT * FROM system.compaction_history;
Output
Variable_name | Value
Innodb_data_written | 1234567890
+--------------+----------+
| table_schema | size_mb |
+--------------+----------+
| mydb | 1024.00 |
+--------------+----------+
💡Monitoring Amplification
📊 Production Insight
In production, set up alerts for high write amplification (e.g., >10) to detect compaction issues early.
🎯 Key Takeaway
Amplification factors directly impact performance and hardware costs. Choose an engine that aligns with your workload's read/write ratio and latency requirements.

Choosing Between B-Tree and LSM-Tree

The choice depends on your workload. B-Trees are ideal for OLTP applications with many point queries, small range scans, and moderate write rates. They provide strong consistency and predictable performance. LSM-Trees excel in write-heavy scenarios like time-series data, logging, and event sourcing. They offer higher write throughput and efficient compression. However, they may have higher read latency for point queries due to multiple SSTable lookups. Consider also the operational complexity: B-Trees require careful tuning of buffer pool size, while LSM-Trees need compaction tuning. Hybrid approaches exist, such as using a B-Tree for hot data and LSM-Tree for cold data. Many modern databases offer configurable storage engines (e.g., MySQL with MyRocks). Evaluate your access patterns: if writes dominate, LSM-Tree is likely better; if reads dominate, B-Tree is safer.

workload-analysis.sqlSQL
1
2
3
4
5
6
-- Analyze read/write ratio from MySQL performance_schema
SELECT
    (SUM(COUNT_READ) / (SUM(COUNT_READ) + SUM(COUNT_WRITE))) * 100 AS read_pct,
    (SUM(COUNT_WRITE) / (SUM(COUNT_READ) + SUM(COUNT_WRITE))) * 100 AS write_pct
FROM performance_schema.table_io_waits_summary_by_table
WHERE object_schema = 'mydb';
Output
read_pct | write_pct
70.0 | 30.0
🔥Hybrid Storage Engines
📊 Production Insight
When migrating, benchmark with realistic workloads. A sudden change in access patterns can expose engine weaknesses.
🎯 Key Takeaway
Analyze your workload's read/write ratio, latency requirements, and operational capacity before choosing a storage engine.

Concurrency and Crash Recovery

B-Trees use techniques like latch-free B-Trees or page-level locking to handle concurrent access. InnoDB uses a combination of row-level locks and MVCC (Multi-Version Concurrency Control) to allow concurrent reads and writes. Crash recovery is handled via a write-ahead log (WAL) that records changes before they are applied to pages. LSM-Trees also use WAL for durability. Compaction can be concurrent, but careful scheduling is needed to avoid conflicts. LSM-Trees typically have simpler concurrency because SSTables are immutable; reads and writes don't conflict. However, compaction may interfere with reads. Both engines rely on checkpoints to limit recovery time. Understanding these mechanisms is vital for tuning performance and ensuring data integrity.

crash-recovery.sqlSQL
1
2
3
4
5
6
7
8
-- Check InnoDB recovery status
SHOW ENGINE INNODB STATUS\G

-- Look for 'LOG' section for recovery progress
-- Example output snippet:
-- Log sequence number 123456789
-- Log flushed up to   123456789
-- Last checkpoint at  123456000
Output
LOG
---
Log sequence number 123456789
Log flushed up to 123456789
Last checkpoint at 123456000
0 pending log writes, 0 pending chkp writes
...
⚠ Crash Recovery Time
📊 Production Insight
Monitor checkpoint age and log file size. A growing log file may indicate that checkpoints are not keeping up, risking longer recovery.
🎯 Key Takeaway
Both engines use WAL for durability, but their concurrency models differ. LSM-Trees offer simpler concurrency due to immutable SSTables.

Performance Tuning and Best Practices

For B-Trees, key tuning parameters include buffer pool size, page size, and index fill factor. A larger buffer pool reduces disk reads. Page size affects node fan-out: larger pages reduce tree height but increase write amplification. For LSM-Trees, tune memtable size, compaction strategy, and bloom filter false positive rate. Leveled compaction reduces read amplification at the cost of higher write amplification. Use compression to reduce disk space and I/O. Monitor compaction throughput and adjust number of compaction threads. Both engines benefit from SSD storage due to lower latency. Regularly rebuild indexes to reduce fragmentation. Use database-specific tools like MySQL's pt-online-schema-change for zero-downtime schema changes. For LSM-Trees, schedule compaction during off-peak hours.

tuning-parameters.sqlSQL
1
2
3
4
5
6
7
8
9
-- InnoDB tuning example
SET GLOBAL innodb_buffer_pool_size = 8 * 1024 * 1024 * 1024; -- 8GB
SET GLOBAL innodb_log_file_size = 2 * 1024 * 1024 * 1024; -- 2GB

-- Cassandra tuning (cqlsh)
ALTER TABLE sensor_data WITH compaction = {'class': 'LeveledCompactionStrategy', 'sstable_size_in_mb': 160};

-- Check current settings
SHOW VARIABLES LIKE 'innodb_buffer_pool_size';
Output
Variable_name | Value
innodb_buffer_pool_size | 8589934592
💡Monitor and Iterate
📊 Production Insight
Always test tuning changes in a staging environment first. A misconfigured buffer pool can cause out-of-memory errors.
🎯 Key Takeaway
Tuning requires understanding your workload and monitoring key metrics. Start with default settings and adjust based on observed bottlenecks.
● Production incidentPOST-MORTEMseverity: high

The Case of the Exploding Write Amplification

Symptom
Database write latency increased 10x, disk utilization hit 100%, and queries timed out.
Assumption
The team assumed a sudden traffic spike was overwhelming the database.
Root cause
An LSM-Tree compaction storm: a large number of small SSTables triggered cascading compactions, causing massive write amplification.
Fix
Tuned compaction strategy: increased the number of levels, adjusted size ratios, and throttled compaction threads.
Key lesson
  • Monitor compaction metrics (e.g., pending compactions, write amplification factor).
  • Set appropriate compaction triggers to avoid cascading merges.
  • Use leveled compaction instead of size-tiered for predictable write patterns.
  • Provision enough I/O bandwidth for compaction overhead.
  • Implement backpressure to throttle writes during compaction storms.
Production debug guideSymptom to Action4 entries
Symptom · 01
High read latency on point lookups
Fix
Check B-Tree page cache hit ratio; if low, increase buffer pool size. For LSM-Tree, check bloom filter effectiveness; rebuild if false positive rate is high.
Symptom · 02
Write latency spikes periodically
Fix
For LSM-Tree, examine compaction logs; tune compaction trigger thresholds. For B-Tree, check for page splits due to high insert volume; consider increasing page size.
Symptom · 03
Disk space grows unexpectedly
Fix
For LSM-Tree, check for old SSTables not yet compacted; force a major compaction. For B-Tree, check for fragmented pages; rebuild indexes.
Symptom · 04
Range scans are slow
Fix
For B-Tree, ensure index is covering; check for excessive random I/O. For LSM-Tree, check if too many levels are involved; optimize compaction strategy.
★ Quick Debug Cheat SheetCommon symptoms and immediate actions for B-Tree and LSM-Tree engines.
High read latency
Immediate action
Check cache hit ratio
Commands
SHOW ENGINE INNODB STATUS;
SELECT * FROM cache_stats;
Fix now
Increase buffer pool size or add more memory.
Write latency spikes+
Immediate action
Check compaction status
Commands
SELECT * FROM compaction_history;
SHOW PROCESSLIST;
Fix now
Throttle writes or trigger manual compaction.
Disk space growing+
Immediate action
Check SSTable count
Commands
SELECT COUNT(*) FROM sstables;
SHOW TABLE STATUS;
Fix now
Force major compaction or rebuild indexes.
Slow range scans+
Immediate action
Check index usage
Commands
EXPLAIN SELECT * FROM table WHERE key BETWEEN 1 AND 1000;
SHOW INDEX FROM table;
Fix now
Optimize index or change compaction strategy.
FeatureB-TreeLSM-Tree
Read performanceExcellent for point queries and range scansGood, but may require multiple SSTable lookups
Write performanceModerate, suffers from page splitsExcellent, sequential writes
Write amplificationLow to moderateHigh, but tunable
Read amplificationLowHigher, mitigated by bloom filters
Space amplificationLowHigher if compaction lags
ConcurrencyComplex (latching, MVCC)Simpler (immutable SSTables)
Crash recoveryWAL-based, can be slowWAL-based, typically fast
Use casesOLTP, relational databasesTime-series, logging, key-value stores
⚙ Quick Reference
6 commands from this guide
FileCommand / CodePurpose
b-tree-schema.sqlCREATE TABLE employees (B-Tree Internals
lsm-tree-schema.cqlCREATE TABLE sensor_data (LSM-Tree Internals
amplification-metrics.sqlSHOW GLOBAL STATUS LIKE 'Innodb_data_written';Read and Write Amplification
workload-analysis.sqlSELECTChoosing Between B-Tree and LSM-Tree
crash-recovery.sqlSHOW ENGINE INNODB STATUS\GConcurrency and Crash Recovery
tuning-parameters.sqlSET GLOBAL innodb_buffer_pool_size = 8 * 1024 * 1024 * 1024; -- 8GBPerformance Tuning and Best Practices

Key takeaways

1
B-Trees optimize for reads with balanced tree structure; LSM-Trees optimize for writes with append-only logs and compaction.
2
Write amplification is a critical metric for LSM-Trees; monitor and tune compaction to avoid storms.
3
Choose storage engine based on workload
B-Tree for read-heavy, LSM-Tree for write-heavy.
4
Both engines require careful tuning of memory, page size, and compaction parameters for optimal performance.
5
Use monitoring tools to track key metrics like cache hit ratio, compaction backlog, and amplification factors.

Common mistakes to avoid

3 patterns
×

Using default compaction settings for LSM-Tree without tuning.

×

Setting buffer pool too large for B-Tree, causing swapping.

×

Ignoring bloom filter false positive rate in LSM-Tree.

INTERVIEW PREP · PRACTICE MODE

Interview Questions on This Topic

Q01SENIOR
Explain how a B-Tree handles insertions and what happens when a node bec...
Q02SENIOR
Describe the compaction process in an LSM-Tree and its impact on perform...
Q03SENIOR
Compare the read performance of B-Tree and LSM-Tree for point queries.
Q01 of 03SENIOR

Explain how a B-Tree handles insertions and what happens when a node becomes full.

ANSWER
When a node is full, it splits into two nodes, and the middle key is promoted to the parent. This may cascade up the tree. The tree remains balanced.
FAQ · 5 QUESTIONS

Frequently Asked Questions

01
What is the main difference between B-Tree and LSM-Tree?
02
Which storage engine is better for time-series data?
03
Can I use both B-Tree and LSM-Tree in the same database?
04
What is write amplification and why does it matter?
05
How do bloom filters help LSM-Trees?
N
Naren Founder & Principal Engineer

20+ years shipping production systems from the metal up. Notes here come from systems that actually shipped.

Follow
Verified
production tested
July 13, 2026
last updated
2,165
articles · all by Naren
🔥

That's DBMS. Mark it forged?

3 min read · try the examples if you haven't

Previous
SQL Query Optimization and Execution Plans
16 / 19 · DBMS
Next
NoSQL Database Types: Document, Key-Value, Graph, Columnar