Storage Engines: B-Tree vs LSM
- Describe the write and read paths of a page-oriented B-tree engine and of an LSM tree
- Explain the write-ahead log, checkpoints and torn-page protection, and why they make commits durable
- Compare compaction strategies (size-tiered, leveled, time-window) and what Bloom filters buy you
- Reason about write, read and space amplification for a given workload
- Pick a storage engine family for a write-heavy ledger, an event log, or a product catalog, and defend the choice
TL;DR
- B-tree engines (InnoDB, Postgres, SQL Server, Oracle, WiredTiger) keep data in fixed-size pages updated in place (or, in Postgres, by appending new tuple versions in the heap). Reads are predictable; random writes cost page I/O.
- LSM engines (RocksDB, LevelDB, Cassandra, ScyllaDB, HBase, Pebble) buffer writes in a memtable, flush immutable sorted files (SSTables), and compact them in the background. Writes are sequential and cheap; reads may check several files.
- Both rely on a write-ahead log for durability: the commit is durable when its log record is flushed, not when data pages are written.
- The RUM trade-off: you can optimize two of read, update (write) and memory/space amplification, rarely all three. Leveled compaction favors reads and space; size-tiered favors writes.
- Bloom filters let an LSM skip SSTables that cannot contain a key: about 10 bits per key gives roughly a 1% false-positive rate.
- Postgres's MVCC heap + VACUUM and InnoDB's in-place update + undo log are different answers to the same versioning problem, with different bloat and purge behavior.
- For ledgers, transactions and constraints usually matter more than raw write throughput: stay on a relational B-tree engine (partitioned, append-only) until you have evidence you need more; LSM-based distributed SQL is the next step, not a NoSQL wide-column store.
Why it matters
The storage engine decides what is cheap and what is expensive. A payment platform ingesting card authorizations at peak, an event log storing every cart action, and a ledger that must answer "balance as of any timestamp" have very different write-to-read ratios and access patterns. Interviewers ask "why Cassandra?" or "why not just Postgres?" to see whether you can reason from the engine's mechanics rather than from popularity. Understanding amplification also explains production symptoms: SSD wear, compaction stalls, vacuum backlogs, and latency spikes during checkpoints.
Core concepts
Page-oriented B-tree engines
Data lives in fixed-size pages (Postgres 8 KB, InnoDB 16 KB) organized as B+trees (and, in Postgres, heap files plus B-tree indexes; see Indexing). Pages are cached in a buffer pool (shared_buffers, innodb_buffer_pool_size).
Key mechanisms:
- Write-ahead rule: a page change may only reach disk after the log record describing it is durable. On crash, recovery replays the log from the last checkpoint (redo), and rolls back uncommitted work (undo; in Postgres, MVCC visibility makes explicit undo unnecessary).
- Group commit: many concurrent transactions share one log flush, so commit throughput can far exceed fsync rate.
- Checkpoints bound recovery time by flushing dirty pages and recording a position from which replay starts. Too frequent means more page writes; too rare means long recovery and large bursts.
- Torn pages: a crash can leave a page half-written (an 8 or 16 KB page spans several disk sectors). Postgres writes a full page image to the WAL on the first modification after each checkpoint (
full_page_writes); InnoDB writes pages first to the doublewrite buffer. Both add write amplification.
Versioning: Postgres vs InnoDB
| Aspect | Postgres heap | InnoDB |
|---|---|---|
UPDATE | Writes a new tuple version (in the heap, ideally on the same page as a HOT update); old version stays | Modifies the row in the clustered index in place; previous version goes to the undo log |
| Readers of old snapshots | Read the old tuple directly from the heap | Reconstruct old versions by applying undo records |
| Cleanup | VACUUM / autovacuum marks dead tuples' space reusable | Purge threads discard undo no longer needed |
| Failure mode | Table and index bloat when vacuum cannot keep up or long transactions pin old snapshots | Undo history (history list length) growth, slow reads of long-running snapshots |
| Extra | Transaction ID wraparound requires freezing (see PostgreSQL Deep Dive) | Separate binlog for replication, kept consistent with redo through an internal two-phase commit |
Log-structured merge trees
An LSM tree turns random writes into sequential ones by never modifying files in place.
- Write path: append to the commit log (durability), insert into the memtable (typically a skip list or balanced tree), acknowledge. When the memtable reaches its size limit it becomes immutable and is flushed to disk as an SSTable: a sorted, immutable file with data blocks, a sparse index, and a Bloom filter.
- Read path: check the memtable, then immutable memtables, then SSTables from newest to oldest. The first version found wins. Each SSTable lookup uses its Bloom filter to skip files that cannot contain the key, then its index to find the block.
- Updates and deletes are writes: an update writes a new version; a delete writes a tombstone. Old versions and tombstones disappear only during compaction.
- Compaction merges SSTables, keeping the newest version of each key and dropping shadowed versions and expired tombstones.
Compaction strategies
| Strategy | How | Write amp | Read amp | Space amp | Typical use |
|---|---|---|---|---|---|
| Size-tiered (STCS) | Merge several similarly sized SSTables into a bigger one | Low | Higher (key may be in many files) | High (temporary 2× during big merges; duplicates linger) | Write-heavy, Cassandra's long-standing default |
| Leveled (LCS) | Each level is a set of non-overlapping files, ≈ 10× larger than the previous; compact a file into the overlapping range of the next level | High (a key may be rewritten once per level) | Low (about one file per level) | Low (≈ 10% overhead) | Read-heavy, RocksDB's default |
| Time-window (TWCS) | Group SSTables by time window; never compact across windows; drop whole windows when data expires | Low | Low for recent-time queries | Low with TTLs | Time-series, event logs with TTL |
| FIFO | Delete the oldest files when over a size limit | Minimal | Depends | Bounded | Caches, short-retention logs |
Cassandra 5.0 adds a Unified Compaction Strategy designed to cover these cases with tunable parameters; RocksDB also supports a "universal" (tiered) style. Exact behavior and defaults vary by version.
Bloom filters. A Bloom filter answers "definitely not present" or "possibly present" using a bit array and k hash functions. With about 10 bits per key and an appropriate number of hashes, the false-positive rate is roughly 1%; false negatives are impossible. That turns a point lookup that would check ten SSTables into, on average, about one real read. Bloom filters do not help range scans, which must merge iterators across all overlapping files (RocksDB offers prefix Bloom filters for prefix scans).
Write, read and space amplification
- Write amplification = bytes written to storage ÷ bytes written by the application. B-tree: writing a 100-byte row can dirty an 8 KB page (plus a full-page image in the WAL after a checkpoint, plus index pages). LSM: each byte is written to the log, flushed once, then rewritten at each compaction (leveled compaction can reach a write amp in the tens, rough).
- Read amplification = storage reads per logical read. B-tree: about the tree height, with upper levels cached. LSM: memtable plus potentially one probe per level or tier, mitigated by Bloom filters and block cache.
- Space amplification = bytes on disk ÷ logical data size. B-tree: free space in pages (fill factor, fragmentation, Postgres bloat). LSM: obsolete versions and tombstones awaiting compaction; size-tiered can temporarily need about double the space.
The RUM conjecture (Athanassoulis et al., 2016) formalizes the intuition: an access method that is optimal for two of read overhead, update overhead and memory/space overhead cannot also be optimal for the third. Every engine is a point in this space, and most expose knobs to move along it.
Write amplification matters for cost, not just speed: SSD endurance is rated in total bytes written, and cloud block storage often bills or throttles by IOPS and throughput.
Real engines at a glance
| Engine | Family | Notes |
|---|---|---|
| InnoDB (MySQL) | B+tree, clustered by PK | Redo + undo logs, doublewrite buffer, change buffer for secondary indexes, binlog for replication |
| PostgreSQL | Heap + B-tree (and GIN, GiST, BRIN) | MVCC in the heap, WAL with full-page images, VACUUM, HOT updates |
| WiredTiger (MongoDB) | B-tree with compression | Document-level concurrency, checkpoints plus journal |
| RocksDB | LSM (leveled by default) | Embedded library; underlies MyRocks, TiKV (TiDB), YugabyteDB's DocDB, Kafka Streams state stores, and many others |
| Pebble | LSM, Go | RocksDB-inspired engine used by CockroachDB |
| Cassandra / ScyllaDB | LSM per node, distributed | Partition key decides node; commit log + memtable + SSTables; tunable consistency |
| HBase | LSM on HDFS | Bigtable model |
| Bitcask (Riak) | Log + in-memory hash index | All keys must fit in memory; very fast point reads and writes |
| TigerBeetle | Purpose-built financial ledger | Debit/credit accounting primitives in the engine itself; LSM-based storage |
A toy log-structured store in Go
The core LSM idea in a few lines, without compaction: append everything, keep an index of the latest offset per key (this is the Bitcask design; an LSM replaces the hash index with sorted files so it can range-scan and exceed memory).
package logkv
import (
"bufio"
"encoding/binary"
"io"
"os"
)
// Store is an append-only key-value log with an in-memory index.
type Store struct {
f *os.File
index map[string]int64 // key -> offset of latest record
end int64
}
func Open(path string) (*Store, error) {
f, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0o644)
if err != nil {
return nil, err
}
s := &Store{f: f, index: make(map[string]int64)}
return s, s.rebuild()
}
// Put appends a record: keyLen, valLen, key, value. Durability needs f.Sync().
func (s *Store) Put(key string, val []byte) error {
var hdr [8]byte
binary.LittleEndian.PutUint32(hdr[0:4], uint32(len(key)))
binary.LittleEndian.PutUint32(hdr[4:8], uint32(len(val)))
rec := append(append(hdr[:], key...), val...)
if _, err := s.f.Write(rec); err != nil {
return err
}
s.index[key] = s.end
s.end += int64(len(rec))
return nil
}
func (s *Store) Get(key string) ([]byte, bool, error) {
off, ok := s.index[key]
if !ok {
return nil, false, nil
}
var hdr [8]byte
if _, err := s.f.ReadAt(hdr[:], off); err != nil {
return nil, false, err
}
kl := int64(binary.LittleEndian.Uint32(hdr[0:4]))
vl := int64(binary.LittleEndian.Uint32(hdr[4:8]))
val := make([]byte, vl)
if _, err := s.f.ReadAt(val, off+8+kl); err != nil {
return nil, false, err
}
return val, true, nil
}
// rebuild scans the log on startup: the last record for each key wins.
func (s *Store) rebuild() error {
if _, err := s.f.Seek(0, io.SeekStart); err != nil {
return err
}
r := bufio.NewReader(s.f)
var off int64
for {
var hdr [8]byte
if _, err := io.ReadFull(r, hdr[:]); err == io.EOF {
break
} else if err != nil {
return err // a torn final record would surface here; real engines checksum and truncate
}
kl := int(binary.LittleEndian.Uint32(hdr[0:4]))
vl := int(binary.LittleEndian.Uint32(hdr[4:8]))
key := make([]byte, kl)
if _, err := io.ReadFull(r, key); err != nil {
return err
}
if _, err := r.Discard(vl); err != nil {
return err
}
s.index[string(key)] = off
off += int64(8 + kl + vl)
}
s.end = off
return nil
}
What a real engine adds: checksums per record, fsync policy, compaction to reclaim space from overwritten keys, tombstones for deletes, sorted segments for range queries, and Bloom filters.
Choosing for ledgers and event logs
Ledger (double-entry, balances, statements). Requirements: multi-row atomic writes (a journal's entries must commit together), constraints (sum to zero, no negative balances where forbidden), point-in-time queries, ad-hoc audit queries, strong consistency. Write pattern: append-only inserts plus balance updates. A relational B-tree engine handles this well into thousands of transactions per second on a single primary (rough; depends on hardware, transaction shape and durability settings), especially with time-partitioned entry tables, BRIN indexes on time, and hot-row mitigations (see Locking & Concurrency Control). When one primary is not enough, the usual next steps are sharding by account or customer, or a distributed SQL database (CockroachDB, TiDB, YugabyteDB, Spanner), which uses LSM storage under a transactional layer. A wide-column store without multi-partition transactions is a poor fit for the ledger of record. See Double-Entry Ledger Design.
Event log / activity stream (cart events, clickstream, notifications, device telemetry): append-only, high volume, time-ordered, often with TTL, read mostly by recent time range or by entity. LSM engines with time-window compaction (Cassandra/ScyllaDB) or a log system (Kafka, see Message Queues & Event Streaming) shine here, as can a partitioned Postgres table with retention by dropping partitions, at lower volumes.
Catalog and read-heavy OLTP: B-tree engines (or leveled LSM) for predictable read latency.
Trade-offs
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| B-tree, update in place (InnoDB) | Predictable reads, efficient range scans on PK, mature tooling | Random write I/O, page splits, doublewrite cost | General OLTP, read-heavy, PK-clustered access |
| Heap + MVCC (Postgres) | Rich indexing, cheap rollbacks, readers never block | Bloat, vacuum tuning, xid wraparound management | General OLTP, complex queries, extensions |
| LSM, leveled | Good write throughput, low space amp, decent reads | High write amp from compaction, compaction CPU/IO | Mixed workloads at large scale (RocksDB-based stores) |
| LSM, size-tiered | Highest ingest rate, low write amp | Read amp, space amp, tombstone problems | Write-heavy, append-mostly data |
| LSM, time-window | Cheap TTL expiry by dropping whole files | Out-of-order writes break windows | Time-series, event logs with retention |
| Log only (Kafka-style) | Sequential everything, replay | No random access by key (only offsets), retention-bound | Event streaming, CDC, audit trails consumed by others |
In practice
- Know your durability settings: Postgres
synchronous_commit,fsync,full_page_writes; InnoDBinnodb_flush_log_at_trx_commit,sync_binlog, doublewrite; Cassandracommitlog_sync(periodicby default, meaning a node crash can lose up to the sync period unless replicas cover it). - Watch engine-specific health signals: Postgres dead tuples and autovacuum lag; InnoDB history list length and buffer pool hit rate; RocksDB/Cassandra pending compactions, SSTables per read, tombstones scanned per query.
- Checkpoint spikes: Postgres spreads checkpoint writes over
checkpoint_completion_target(0.9 of the interval by default); sizemax_wal_sizeso checkpoints are triggered by time, not WAL volume, during peaks. - LSM tuning starts with memtable size, level sizes, compaction concurrency, block cache size and Bloom filter bits; measure with the engine's own statistics before tuning.
- Cassandra tombstones: a query that scans many tombstones is slow and can fail (
tombstone_failure_threshold); deletes are only purged aftergc_grace_seconds(default 10 days) and compaction. Model deletes and TTLs deliberately (see NoSQL Data Modeling).
Common pitfalls
- Choosing an LSM store for "write-heavy" without checking the read pattern. Symptom: point reads fine, but range scans and secondary lookups are slow and expensive.
- Treating deletes as free in an LSM. Symptom: queue-like tables in Cassandra (insert, read, delete) accumulate tombstones and time out.
- Ignoring write amplification on cloud disks. Symptom: IOPS throttling at a fraction of the expected throughput; SSD wear alerts on self-hosted hardware.
- Turning off
fsyncor full-page writes to "speed up" Postgres. Symptom: corruption after a power loss. Usesynchronous_commit = offfor tolerable loss without corruption, or better hardware. - Long transactions on MVCC engines. Symptom: Postgres bloat and vacuum unable to clean; InnoDB undo growth and slow consistent reads.
- Assuming "append-only" means no B-tree cost. Random-key indexes on an append-only table (UUIDv4, customer id) still cause random index writes; only time-ordered keys append at the edge.
Interview angle
- Prompts: "Why is Cassandra good for writes?", "B-tree vs LSM?", "How does a database make a commit durable?", "What would you store a ledger in? An event log?"
- A strong answer walks the write path (log, memtable or page, flush or checkpoint), names the amplification trade-offs, and connects them to the workload's read pattern, not just its write rate.
- Expect follow-ups on Bloom filters (false positives, bits per key), compaction strategies, tombstones, and torn pages.
- Show judgment: a ledger needs transactions and constraints first; throughput is solved by partitioning and sharding before switching engine families.
- Red flags: "LSM is faster", "NoSQL scales, SQL doesn't", not knowing what fsync does at commit.
Self-check
1. Why can a B-tree engine acknowledge a commit before writing data pages to disk?
Because of the write-ahead log: the commit is durable once its log records are flushed. After a crash, recovery replays the log from the last checkpoint, re-applying changes to pages that had not yet been written. Dirty data pages can therefore be flushed later in larger, smoother batches.
2. Walk through an LSM read for a key that does not exist.
Check the memtable and immutable memtables (miss), then for each SSTable or level consult its Bloom filter. With a well-sized filter, almost every file answers "definitely not here", so few or no data blocks are read. Without Bloom filters, a missing key would require probing every level, which is the worst case for LSM reads.
3. Compare size-tiered and leveled compaction in terms of amplification.
Size-tiered merges similar-sized files, so each byte is rewritten relatively few times (low write amp), but a key may live in several overlapping files (higher read amp) and obsolete versions linger, with temporary doubling during big merges (high space amp). Leveled keeps non-overlapping files per level so a read checks about one file per level and space overhead is small, but each byte is rewritten as it moves through levels, giving higher write amp.
4. How do Postgres and InnoDB differ in storing old row versions, and what operational problem does each create?
Postgres writes new tuple versions into the heap and leaves old ones in place until VACUUM removes them, so the risk is table and index bloat and vacuum lag (plus xid wraparound management). InnoDB updates the clustered row in place and keeps old versions in the undo log for consistent reads, so the risk is undo history growth when long transactions prevent purge, slowing reads that must walk version chains.
5. Why are tombstones a problem, and how do you design around them in Cassandra?
Deletes write tombstones that must be read and skipped until compaction removes them after gc_grace_seconds, so delete-heavy or queue-like access patterns make reads scan many tombstones, slowing or failing queries. Design so data expires by TTL with time-window compaction and whole SSTables drop, partition by time bucket so reads target recent partitions, and avoid using Cassandra as a queue.
6. Scenario: a fintech expects 20,000 ledger postings per second within two years. The team proposes Cassandra. What do you say?
Ask what the ledger must guarantee: multi-entry atomic journals, balance checks, constraints and auditable queries. Cassandra lacks multi-partition transactions, so a journal touching two accounts on different partitions cannot commit atomically, and balance checks need lightweight transactions per partition, which are expensive. Prefer a relational ledger sharded by account or customer, or a distributed SQL database, and use Cassandra or Kafka for high-volume derived event history if needed.
Exercise
Observe write amplification and versioning in Postgres.
docker run --name pg-engine -e POSTGRES_PASSWORD=pg -p 5432:5432 -d postgres:17
docker exec -it pg-engine psql -U postgres
CREATE EXTENSION pgstattuple;
CREATE TABLE ledger_entry (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
account_id bigint NOT NULL, amount_minor bigint NOT NULL,
created_at timestamptz NOT NULL DEFAULT now());
CREATE TABLE balance (account_id bigint PRIMARY KEY, balance_minor bigint NOT NULL);
INSERT INTO balance SELECT g, 0 FROM generate_series(1, 100000) g;
-- 1. WAL generated by 100k appends
SELECT pg_current_wal_lsn() AS start \gset
INSERT INTO ledger_entry (account_id, amount_minor)
SELECT (random() * 100000)::bigint + 1, 100 FROM generate_series(1, 100000);
SELECT pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), :'start'));
-- 2. WAL generated by 100k in-place-style updates
SELECT pg_current_wal_lsn() AS start \gset
UPDATE balance SET balance_minor = balance_minor + 100;
SELECT pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), :'start'));
- Compare the WAL volume of steps 1 and 2 relative to the logical data written. Run
CHECKPOINT;and repeat step 2 to see the effect of full-page images. - Inspect
SELECT * FROM pgstattuple('balance');before and afterVACUUM balance;and note dead tuples and free space. - Check
n_tup_updandn_tup_hot_updinpg_stat_user_tablesforbalance. Add an index onbalance_minor, repeat the update, and compare. - Optional: run
cassandra:5.0in Docker, create a table withcompaction = {'class': 'TimeWindowCompactionStrategy'}and a TTL, insert data, and inspect SSTables withnodetool tablestats.
Done when you can explain the WAL numbers in terms of page writes, full-page images and index maintenance, and predict how an LSM engine would differ.
Further reading
- Martin Kleppmann, Designing Data-Intensive Applications, ch. 3 "Storage and Retrieval".
- Alex Petrov, Database Internals — B-tree and LSM internals in depth.
- Patrick O'Neil et al., "The Log-Structured Merge-Tree (LSM-Tree)" (Acta Informatica, 1996).
- Fay Chang et al., "Bigtable: A Distributed Storage System for Structured Data" (OSDI 2006).
- Manos Athanassoulis et al., "Designing Access Methods: The RUM Conjecture" (EDBT 2016).
- RocksDB wiki on GitHub: "RocksDB Overview", "Compaction", "RocksDB Bloom Filter".
- PostgreSQL documentation, "Reliability and the Write-Ahead Log".
Related
- Indexing — B+tree structure and clustered vs heap tables.
- PostgreSQL Deep Dive — WAL, MVCC, vacuum and checkpoints in operation.
- NoSQL Data Modeling — modeling for LSM-based wide-column stores.
- File Systems & Durable Storage — fsync, page cache and what the disk really guarantees.
- Data Structures Inside Real Systems — skip lists, Bloom filters and B-trees.
- Double-Entry Ledger Design — what the ledger needs from its storage.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).