Storage Engines: B-tree vs LSM-tree
"The LSM-tree uses an algorithm that defers and batches index changes, migrating the changes out to disk in a particularly efficient way reminiscent of merge sort." — Patrick O'Neil, Edward Cheng, Dieter Gawlick, Elizabeth O'Neil, The Log-Structured Merge-Tree (LSM-Tree), Acta Informatica 33(4), 1996
Summary: A storage engine decides how bytes sit on disk. B-trees update fixed pages in place and win on reads; LSM-trees buffer writes in memory, append sorted files and merge them later, and win on writes; every design pays in read, write or space amplification. Focus: Pages and the buffer pool, B+tree in-place updates, the LSM write and read paths (WAL, memtable, SSTable, levels, bloom filters, block cache), compaction styles (leveled, size-tiered, TWCS, FIFO), tombstones, write stalls, SSDs, copy-on-write and Bε-trees, and how PostgreSQL, InnoDB, MyRocks, RocksDB, WiredTiger, Cassandra, TiKV, CockroachDB and Redis apply them. Learning goal: Given a workload, name the engine family that fits, predict its read, write and space amplification, set the handful of knobs that matter (write_buffer_size, level0_file_num_compaction_trigger, compaction style, gc_grace_seconds), and spot a write stall or tombstone storm before it pages you.
This page is the complete reference for on-disk storage structures: what a storage engine is, how a B+tree and an LSM-tree take a write and serve a read, what compaction costs, and how real products configure it. It does not re-teach neighbours. How a single index is laid out, its fan-out and splits are on B-Tree vs B+Tree; index types and design on Indexing; page and tuple layout on Database Internals; the WAL and crash recovery on Durability & Crash Recovery; bloom filter maths on Bloom Filters; InnoDB vs MyISAM on MySQL Storage Engines; Cassandra operations on Cassandra & ScyllaDB; row vs columnar analytics on OLTP vs OLAP.
Page map
| If you are looking for | Go to |
|---|---|
| The tables to memorise | Everything in one minute |
| Why two designs exist and the trade-off | Why storage engines differ |
| Bayer & McCreight, Comer, O'Neil, LevelDB, RocksDB | Where it comes from |
| Handler API, pages, buffer pool, B+tree update path | B-tree side |
| Write, read and space amplification, RUM | The three amplifications |
| Memtable, WAL, SSTable, bloom filter, block cache | LSM side |
| Leveled, size-tiered, universal, TWCS, FIFO | Compaction |
| Tombstones, range deletes, write stalls | Deletes and debt |
| SSD, copy-on-write B-trees, Bε-trees, heap vs clustered | Other designs and hardware |
| PostgreSQL, InnoDB, MyRocks, WiredTiger, Cassandra, TiKV, CockroachDB, Redis | What each product really does |
| RocksDB and Cassandra knobs, stall messages | Mechanics and knobs |
| Picking an engine, write bursts, tombstone storms | Solving the classic problems |
| Benchmarks that lie | Benchmarking pitfalls |
| Workload → engine table | Choosing an engine |
| Monolith to distributed SQL | In architecture |
Teaching LSM, heap vs clustered sizes, ldb | Lab |
| Wrong beliefs, summary, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The two families.
| B+tree (update in place) | LSM-tree (log-structured, merge later) | |
|---|---|---|
| A write does | Find the leaf page, change it, write the whole page back later | Append to WAL, insert into memtable; flush a sorted file later |
| A point read does | Root-to-leaf walk: 3-4 pages, upper levels cached | Memtable, then files newest first; bloom filters skip most files |
| A range scan does | Walk linked leaves in order | Merge an iterator over every level |
| A delete does | Removes the entry (PostgreSQL marks the tuple dead for VACUUM) | Writes a tombstone; space returns only after compaction |
| Background work | Checkpoints, page splits, VACUUM / purge | Flushes and compaction, forever |
| Wins at | Read-heavy OLTP, predictable latency | Write-heavy ingest, compression, flash endurance |
| Products | PostgreSQL, InnoDB, SQL Server, Oracle, SQLite, WiredTiger, LMDB, bbolt | RocksDB, LevelDB, Pebble, MyRocks, Cassandra, ScyllaDB, HBase, TiKV, Badger |
The three costs.
| Cost | Plain words | B+tree | Leveled LSM | Size-tiered LSM |
|---|---|---|---|---|
| Write amplification | Bytes the device writes per byte you wrote | High for small random updates (a whole page per change) | Medium to high (rewrite at every level) | Lowest |
| Read amplification | Pages or files touched per lookup | Lowest | Low with bloom filters | Higher (more runs) |
| Space amplification | Disk bytes per live byte | Fragmentation, half-empty pages | Lowest (~1.1×) | Up to ~2× during merges |
The knobs that matter first.
| Product | Knob | Default | What it moves |
|---|---|---|---|
| RocksDB | write_buffer_size | 64 MB | Memtable size: bigger = fewer, larger L0 files |
| RocksDB | max_write_buffer_number | 2 | Memtables allowed before writes stop |
| RocksDB | level0_file_num_compaction_trigger | 4 | L0 files that start L0→L1 compaction |
| RocksDB | target_file_size_base | 64 MB | SST size at L1 |
| RocksDB | compaction_style | kCompactionStyleLevel | Leveled vs universal vs FIFO |
| Cassandra | compaction class | STCS (UCS recommended for new tables) | Compaction strategy per table |
| Cassandra | gc_grace_seconds | table property | How long tombstones must live |
| PostgreSQL | fillfactor | 100 heap, 90 B-tree | Free space left in pages for updates |
| InnoDB | innodb_page_size / innodb_fill_factor | 16384 / 100 | Page size, free space at index build |
| MongoDB WiredTiger | checkpoint interval | 60 s | How much journal recovery replays |
Why storage engines differ
Every engine must answer the same three questions: where does a new value go, how do I find it again, and how do I get space back from old values. A disk (spinning or flash) is fast at large sequential transfers and slow, or wearing, at small random overwrites. Memory is fast but lost on power failure. The two designs pick opposite answers.
| Update in place (B+tree) | Out of place (LSM-tree) |
|---|---|
| One home per key; reads go straight there | A key may exist in several files; the newest wins |
| Random writes; each dirty page is written whole | Sequential writes only; files are never edited |
| Space reclaimed in place (free space in pages, VACUUM, purge) | Space reclaimed by rewriting files (compaction) |
| Background cost: checkpoints and splits | Background cost: compaction, which never ends |
| Latency predictable; write throughput bounded by random I/O | Write throughput high; read latency has a long tail during compaction debt |
The analogy we reuse on this page: the library and the inbox tray. A B+tree is a library with a card catalogue: every book has one shelf, and adding a book means walking to that shelf and squeezing it in (when the shelf is full, you split it across two shelves). An LSM-tree is a librarian with an inbox tray: new books go in the tray (memtable) with a line in the logbook (WAL); when the tray is full, its books are sorted and boxed (SSTable); at night boxes are merged into the big sorted stacks (compaction). Shelving is fast all day; finding a book means checking the tray and some boxes first, with a "not in this box" sticker on each (bloom filter) to skip most of them.
Three common misunderstandings, up front
- "LSM writes less." It writes sequentially, and often writes more total bytes than a B-tree, because compaction rewrites each value several times. What it avoids is the page-sized rewrite for a tiny change and the random I/O.
- "LSM reads are slow." Point reads with bloom filters and a warm block cache touch about one data block. Range scans, misses without filters, and anything during compaction debt are the slow cases.
- "Pick the engine and forget it." An LSM is a background process you operate: compaction style, stall triggers and tombstone hygiene decide its behaviour more than the choice of LSM itself. A B-tree needs VACUUM, fill factor and key design.
Where it comes from
A storage engine is the layer under SQL (or under a key-value API) that decides how bytes sit on disk: how a key is found, how a change is written, how space is reclaimed. The parser and planner above it see rows and indexes; the engine sees pages, files and I/O. Two designs dominate, and they come from papers twenty-four years apart.
The B-tree came from Bayer and McCreight at Boeing in 1972. By 1979 Douglas Comer could open his ACM Computing Surveys article with the claim that B-trees had become the standard file organization, and a page later he was more precise:
"The B-tree is, de facto, the standard organization for indexes in a database system." — Douglas Comer, The Ubiquitous B-Tree, ACM Computing Surveys 11(2), 1979
Comer's survey is also where the B+-tree gets its standard meaning: "In a B+-tree, all keys reside in the leaves." The inner levels are only a roadmap, and the leaves are linked left to right so a range scan walks them in order.
The Log-Structured Merge-tree came from O'Neil, Cheng, Gawlick and O'Neil (UMass Boston, DEC and Oracle). They were looking at a TPC-A-style bank that writes a History row per transaction and wants an index on account id. With a B-tree that index dirties a random leaf per insert; their calculation is that standard disk-based structures "will effectively double the I/O cost of the transaction to maintain an index such as this in real time". Their answer was a memory component (C0) merged into disk components (C1, C2…) with large multi-page sequential writes, so that "Newly merged blocks are written to new disk positions". They named the price: "Only finds that require immediate response remain relatively costly."
LevelDB (Google) turned the idea into a small library; its implementation notes describe it as similar to a single Bigtable tablet. RocksDB (Facebook) forked LevelDB "with the initial focus on fast storage (especially Flash storage)". Pebble (CockroachDB) re-implemented RocksDB's design in Go. Most production LSM engines descend from one of these. In 2016 Athanassoulis et al. gave the trade-off its name, the RUM conjecture.
The B-tree side: engines, pages and updates in place
Each block follows the same order: plain words, the usual wrong belief, a definition, a timeline, real scenarios, how products differ, and the fix or the knob.
Storage engine and the handler API boundary Must-know
In plain words: the storage engine is the part of the database that actually reads and writes the files. Everything above it (SQL parser, planner, executor) calls it through a fixed interface.
Common misunderstanding: "The database is its storage engine." MySQL can run InnoDB, MyRocks or MyISAM under the same SQL layer; PostgreSQL has had a pluggable table access method API since version 12; MongoDB once offered MMAPv1 and WiredTiger. The SQL behaviour you see (locking, MVCC, crash safety) often comes from the engine, not the SQL layer.
Definition: the engine owns on-disk format, caching, concurrency control below the row level, logging and recovery. The boundary is an API:
- MySQL: "MySQL Server uses a pluggable storage engine architecture that enables storage engines to be loaded into and unloaded from a running MySQL server." The C++ boundary is the handler class (
ha_innobase,ha_rocksdb); you pick it withENGINE=per table. - PostgreSQL: the table access method interface, which "manage[s] the storage for tables". Each method is a row in
pg_amwhose handler returns aTableAmRoutine;heapis the built-in one.CREATE TABLE ... USING <am>picks it. - MongoDB: the storage engine API under the document layer; WiredTiger is the default.
- Embedded libraries (RocksDB, LevelDB, Pebble, LMDB, bbolt, Badger, SQLite's B-tree layer) are the engine; a server (TiKV, CockroachDB, MyRocks, etcd) wraps them.
SQL layer Engine (InnoDB / MyRocks)
1 parse SELECT ... WHERE id = 7
2 plan index lookup on PRIMARY
3 exec handler->index_read_map(key=7) -> find key 7 (B+tree or LSM)
4 <- row bytes
5 exec apply WHERE, project, send rowReal scenario: a team moves a write-heavy MySQL table from InnoDB to MyRocks with ALTER TABLE t ENGINE=ROCKSDB and keeps every query; a PostgreSQL extension ships a columnar access method for an append-only events table; an etcd cluster's latency is really bbolt's B+tree behaviour.
| Product | Boundary | How you choose |
|---|---|---|
| MySQL / MariaDB | handler API, pluggable engines | ENGINE=InnoDB / ENGINE=ROCKSDB per table |
| PostgreSQL | table access method (pg_am), index AM | CREATE TABLE ... USING heap (default) |
| MongoDB | storage engine API | --storageEngine wiredTiger (default) |
| CockroachDB, TiKV, etcd | embedded KV library | Built in: Pebble, RocksDB, bbolt |
| SQL Server, Oracle, SQLite | single built-in engine | Table options (clustered index, IOT, WITHOUT ROWID) |
Fix / how to use it: check the engine before tuning anything.
-- MySQL: which engine holds each table?
SELECT table_name, engine FROM information_schema.tables WHERE table_schema = DATABASE();
-- PostgreSQL: which access method?
SELECT c.relname, a.amname FROM pg_class c JOIN pg_am a ON a.oid = c.relam WHERE c.relkind = 'r';Pages and the buffer pool Must-know
In plain words: disks are read in fixed-size pages, and the database keeps recently used pages in a memory cache. Every read and write goes through that cache.
Common misunderstanding: "A write goes to disk when I commit." In a B-tree engine the log record reaches disk at commit; the changed data page stays dirty in memory and is written back later by a checkpoint or background writer.
Definition: PostgreSQL stores "Every table and index" as "an array of pages of a fixed size (usually 8 kB, although a different page size can be selected when compiling the server)"; InnoDB's innodb_page_size defaults to 16384. The cache is PostgreSQL shared_buffers (plus the OS page cache), InnoDB's buffer pool (innodb_buffer_pool_size), WiredTiger's cache, RocksDB's block cache. A page is dirty when changed in memory and not yet written. Eviction of a dirty page forces a write.
Session Buffer pool Disk
1 UPDATE ... WHERE id=7 page 42 not cached -> read page 42 (8/16 KB)
2 page 42 cached, change row; page 42 = dirty
3 COMMIT WAL record for the change -> fsync WAL (small, sequential)
4 ...minutes later...
5 checkpoint -> write page 42 whole (random)Real scenario: a working set that fits in the buffer pool makes a B-tree look like an in-memory index; when the data outgrows memory, latency jumps because every lookup now reads a leaf from disk. A checkpoint storm after a bulk update causes an I/O spike minutes after the update finished.
Fix / how to use it: size the cache to the hot set (shared_buffers ~25% of RAM is the usual PostgreSQL starting point, innodb_buffer_pool_size 50-75% on a dedicated server), and watch hit ratios (pg_stat_database.blks_hit / (blks_hit + blks_read), Innodb_buffer_pool_reads vs Innodb_buffer_pool_read_requests).
B+tree in-place update and page splits Must-know
In plain words: to change a key, a B+tree walks from the root to the one leaf page that holds it, changes that page, and later writes the whole page back to the same place on disk.
Common misunderstanding: "Updating 100 bytes writes 100 bytes." It writes at least one whole page (8 or 16 KB), plus WAL, plus (InnoDB) the doublewrite buffer copy, plus any page that split.
Definition: a lookup descends root → internal → leaf. Fan-out is what makes it shallow: hundreds of keys per page mean three or four levels for billions of rows. A write modifies the leaf. When the leaf is full, PostgreSQL's B-tree documentation describes the split: "A page split operation makes room for items that originally belonged on the overflowing page by moving a portion of the items to a new page", and the parent gets a new downlink (which can split the parent in turn). Splits leave pages about half to two-thirds full; random inserts therefore settle near 70% fill, sequential inserts near 100% (PostgreSQL and InnoDB both special-case the rightmost split).
Insert key 4711 into a full leaf (sequence numbers are steps)
1 descend root -> internal -> leaf L (keys 4600..4800, full)
2 WAL: log "split L, insert 4711"
3 allocate new page L'; move upper half of L to L'
4 insert 4711 into L or L'; parent gets downlink (4705 -> L')
5 L, L' and parent are dirty; later written whole, in placeReal scenario: a UUIDv4 primary key on a 500 GB InnoDB table: every insert lands on a random leaf, so the buffer pool must hold the whole index or every insert reads and later writes a random page. Switching to a time-ordered key (UUIDv7, ULID, bigint identity) makes inserts land on the right-most leaf; see ID Generation. A table with frequent updates to non-indexed columns in PostgreSQL benefits from fillfactor below 100 so HOT updates stay in the same page.
| Product | Page | Split / space knob |
|---|---|---|
| PostgreSQL B-tree | 8 kB | fillfactor (index default 90, heap 100); deduplication and bottom-up deletion delay splits |
| InnoDB | 16 KB (innodb_page_size) | innodb_fill_factor (default 100) at index build; MERGE_THRESHOLD for merges |
| SQL Server | 8 KB | FILLFACTOR, PAD_INDEX |
| Oracle | DB_BLOCK_SIZE (8 KB typical) | PCTFREE |
| SQLite | page_size (4096 default) | VACUUM to repack |
| WiredTiger | variable in-memory pages, reconciled on write | leaf_page_max, internal_page_max |
Fix: keep keys monotonic where you can, leave free space for updates (fillfactor), rebuild bloated indexes (REINDEX CONCURRENTLY, OPTIMIZE TABLE), and keep the hot part of the tree in memory.
The three amplifications
Write amplification Must-know
In plain words: how many bytes really hit the disk for each byte your application wrote.
Common misunderstanding: "Write amplification is an LSM problem." Both families have it. A B-tree rewrites a whole 8-16 KB page for a 100-byte change (≈80-160× for that write, before WAL and doublewrite). A leveled LSM rewrites each value once per level it passes through (about the fan-out, 10×, per level in the worst case). The SSD then adds its own amplification underneath.
Definition: WA = bytes written to storage ÷ bytes written by the application. Count WAL, data files, compaction output, and (if you can measure it) the device's internal writes. MyRocks' site claims "a 10x less write amplification compared to InnoDB, giving you better endurance of flash storage".
One 100-byte row update, followed through two engines
1 B+tree: WAL record (~150 B) + full leaf page at checkpoint (16 KB) [+ doublewrite 16 KB]
2 LSM: WAL record (~150 B) + memtable flush (100 B in a 64 MB sequential file)
3 LSM: L0->L1 compaction rewrites it (100 B), L1->L2 (100 B + its share of 10x overlap)...
4 LSM: by the last level the row was written ~ (1 + levels x fan-out share) times,
but always inside large sequential writes; B+tree wrote 16 KB once per checkpointReal scenario: a metrics service on cloud SSD burns through its provisioned write IOPS; an NVMe drive's endurance (TBW) runs out in a year; a replica cannot keep up because each logical write turns into many physical ones.
Fix: measure it. RocksDB prints W-Amp per level in its compaction stats in the LOG file; on Linux compare iostat device writes with application bytes; in PostgreSQL compare pg_stat_wal.wal_bytes and pg_stat_bgwriter/pg_stat_checkpointer buffers written with your row volume.
Read amplification Important
In plain words: how many pages or files a single lookup has to touch.
Common misunderstanding: "Read amplification is the number of disk reads." It is the number of places checked; caches and bloom filters turn most of them into memory probes. It matters when the cache misses.
Definition: B+tree: tree height (3-4), almost always one disk read for the leaf when inner pages are cached. LSM: memtables + every L0 file + one file per deeper level; each probe is a bloom check, then index block, then one data block. Range scans have no bloom shortcut and must merge all levels.
Real scenario: a Cassandra table under STCS with 30 SSTables per partition shows p99 reads ten times the p50; nodetool tablehistograms reports "SSTables per read" climbing during a backlog.
Fix: keep L0 small (compaction keeping up), use leveled compaction for read-heavy tables, give bloom filters enough bits, and keep index and filter blocks in cache (cache_index_and_filter_blocks).
Space amplification Important
In plain words: how much disk you use compared to the live data.
Common misunderstanding: "Deleting data frees disk." In an LSM a delete adds a tombstone; space returns only when compaction merges it with the old value. In PostgreSQL a delete leaves a dead tuple until VACUUM; InnoDB purge frees the record but not the file.
Definition: SA = bytes on disk ÷ bytes of live data. Sources: obsolete versions not yet compacted, tombstones, half-empty B-tree pages, and temporary space during a merge (size-tiered compaction can need as much free space as the runs it merges). RocksDB's leveled design keeps about 90% of data in the last level, which bounds SA near 1.1×.
Fix: leave headroom (50% for STCS, ~10-20% for leveled), monitor live vs total size (rocksdb.estimate-live-data-size, pg_relation_size vs pgstattuple), and prefer whole-file expiry (TWCS, FIFO, partition drops) over row deletes.
The RUM conjecture Important
In plain words: you can make reads cheap, updates cheap or memory/space small, but not all three at once.
Common misunderstanding: "A better engine beats the trade-off." Engines move along it; bloom filters, for example, spend memory to buy back reads.
"An access method that can set an upper bound for two out of the read, update, and memory overheads, also sets a lower bound for the third overhead." — Athanassoulis et al., Designing Access Methods: The RUM Conjecture, EDBT 2016
| Design | Optimises | Pays with |
|---|---|---|
| B+tree | Reads | Updates (random page writes), some space |
| Leveled LSM | Space, reads (vs tiered) | Writes (compaction) |
| Size-tiered / universal LSM | Writes | Reads and space |
| FIFO / TWCS | Writes and space for TTL data | Reads across files; only works for time-ordered data |
| Hash index (Bitcask, Redis dict) | Point reads and updates | Memory (all keys in RAM), no range scans |
| Bloom filters | Reads | Memory (~10 bits per key for ~1% false positives) |
The LSM side: memtable, WAL, SSTables, filters and cache
Memtable and immutable memtable Must-know
In plain words: the memtable is a sorted in-memory buffer that takes every write. When it is full it is frozen (immutable) and a new one takes over, while the frozen one is written to disk.
Common misunderstanding: "The memtable is a cache." It is the only place recent writes exist besides the WAL; it is not evictable. A read cache is the block cache.
Definition: RocksDB, LevelDB and Pebble use a skip list by default (concurrent inserts, ordered iteration). A memtable switches to immutable when it reaches write_buffer_size (RocksDB default 64 MB); up to max_write_buffer_number (default 2) memtables may exist at once. A background thread flushes an immutable memtable to one L0 SSTable. Cassandra and HBase call it the memtable / memstore; HBase flushes a region's memstore to a store file at hbase.hregion.memstore.flush.size.
Writer Memtables Flush thread
1 Put(a) Put(b) ... M1 active
2 M1 reaches write_buffer_size M1 -> immutable, M2 active
3 Put(c) ... M2 active, M1 immutable -> flush M1 to 000012.sst (L0)
4 M2 full, M1 still flushing max_write_buffer_number reached: WRITES STOP
5 M1 flushed, freed <- writes resumeReal scenario: a bulk import into TiKV stalls every few seconds because flushes cannot keep up with two 64 MB memtables; raising the number of write buffers and background jobs removes the stall at the cost of memory.
Fix: budget memory for write_buffer_size × max_write_buffer_number per column family (RocksDB's tuning page: "You need to budget for 2 x your worst case memory use"), or cap it globally with db_write_buffer_size / a WriteBufferManager.
WAL for memtable durability Must-know
In plain words: before a write goes into the memtable it is appended to a log on disk, so a crash cannot lose it.
Common misunderstanding: "LSM engines don't need a WAL because files are immutable." The SSTables are durable; the memtable is not. Without the WAL, every write since the last flush disappears on crash.
Definition: RocksDB's WAL page:
"Every update to RocksDB is written to two places: 1) an in-memory data structure called memtable (to be flushed to SST files later) and 2) write ahead log(WAL) on disk." — RocksDB Wiki, Write Ahead Log (WAL)
"In the default configuration, RocksDB guarantees process crash consistency by flushing the WAL after every user write" — that is a write to the OS, not an fsync; WriteOptions.sync = true adds the fsync per commit, disableWAL = true drops the log. A WAL file can be deleted once every memtable it covers has been flushed. Cassandra calls it the commit log (commitlog_sync: periodic by default), HBase the WAL (HLog), WiredTiger the journal.
Put(k, v) in RocksDB / the teaching LSM on this page
1 append record to WAL (wal.log) sequential, buffered in OS
2 if sync=true: fsync WAL durability against power loss
3 insert into memtable memory only
4 ack to client
5 ... memtable flushed to SSTable, fsync SST, then the old WAL is deletedFix: decide your durability per write: sync=true (or group commit) for money, sync=false for data you can rebuild. The teaching snippet below replays its WAL on Open to show recovery.
SSTable format: data, index and filter blocks Must-know
In plain words: an SSTable is an immutable file of key-value pairs sorted by key, cut into small blocks, with an index of blocks and a filter at the end.
Common misunderstanding: "An SSTable is one big sorted list you binary-search on disk." Reads use the in-file index to jump to one small block; the filter avoids even that when the key is absent.
Definition: RocksDB's default table, BlockBasedTable, inherits LevelDB's layout: data blocks (sorted, prefix-compressed keys, default block_size 4 KB, optionally compressed), then meta blocks (filter block, index block, compression dictionary, range-deletion block, properties), a metaindex block, and a fixed-size footer. The wiki: "The sequence of key/value pairs in the file are stored in sorted order and partitioned into a sequence of data blocks." Each entry carries an internal key (user key + sequence number + type: value, deletion, merge, range deletion).
<beginning_of_file>
1 [data block 1] [data block 2] ... [data block N] sorted, ~4 KB each
2 [filter block] bloom filter over all keys
3 [index block] last key of each data block -> BlockHandle(offset, size)
4 [range deletion block] range tombstones
5 [properties block] counts, sizes, compression
6 [metaindex block] [Footer: handles of metaindex + index, magic number]
<end_of_file>Fix: use sst_dump --file=... --show_properties to see entries, tombstones, index and filter sizes (see Lab).
Bloom filters Must-know
In plain words: a small bit array per file that can say "this key is definitely not here" without reading the file.
Common misunderstanding: "A bloom filter tells me where the key is." It only answers no or maybe; a maybe can be wrong (false positive), a no never is.
Definition: RocksDB: the filter "may be used to determine if the key may exist or definitely does not exist in the key set", and its typical setting "generates filters using about 10 bits of space per key", roughly a 1% false-positive rate. Filters are per SST (full filters) or partitioned; prefix bloom filters (prefix_extractor) help prefix seeks. Range scans cannot use ordinary bloom filters. Cassandra exposes the same trade as the per-table bloom_filter_fp_chance option. The maths is on Bloom Filters.
Get("user:42") over 5 SSTables, 10 bits/key
1 memtable: miss
2 L0 file #9: bloom says NO -> skip (0 I/O)
3 L0 file #8: bloom says MAYBE -> index block -> data block -> not found (false positive, 1 read)
4 L1 file covering "user:*": bloom MAYBE -> index -> data block -> FOUND
5 total: 2 data-block reads, 4 bloom probes in memoryFix: keep 10 bits/key as the default; raise to 15-20 for FIFO or many-L0 layouts (RocksDB's FIFO page recommends it); use optimize_filters_for_hits when most lookups hit, to drop filters for the last level and save memory.
Block cache Important
In plain words: the LSM's read cache: recently used uncompressed blocks from SST files, plus (optionally) index and filter blocks.
Common misunderstanding: "Give the block cache all the memory." RocksDB's tuning page recommends about one third of the memory budget and leaving the rest to the OS page cache, which holds compressed blocks.
Definition: "Block cache is where RocksDB caches data in memory for reads." It stores uncompressed blocks, is sharded ("By default each cache will be sharded into at most 64 shards") and comes as LRUCache or ClockCache. cache_index_and_filter_blocks=true charges index and filter blocks to it, with pin_l0_filter_and_index_blocks_in_cache keeping L0 hot.
Fix: share one cache across column families and DBs in a process, size it with the page cache in mind, and watch rocksdb.block.cache.hit / miss counters.
Compaction: leveled, size-tiered, universal, TWCS, FIFO
Compaction and sorted runs Must-know
In plain words: compaction is the background merge that turns many small sorted files into fewer large ones, throwing away overwritten values and expired deletes on the way.
Common misunderstanding: "Compaction is maintenance you can schedule for the weekend." It is part of the write path. An LSM's sustainable write rate is its compaction rate; RocksDB notes "The overall write throughput of an LSM database directly depends on the speed at which compactions can occur".
Definition: a sorted run is a set of files that together hold each key at most once in key order (one memtable flush; one leveled level). Compaction reads N runs with a merge iterator, keeps the newest version per key (by sequence number, unless a snapshot still needs an older one), writes new files, and atomically swaps them in via the MANIFEST (RocksDB, LevelDB, Pebble) or the SSTable set (Cassandra). LevelDB states the goal: migrate updates downwards "using only bulk reads and writes (i.e., minimizing expensive seeks)".
L0: [a=1 c=3] [a=2 b=5] (two flushes, newest right)
L1: [a=0 b=4 d=7]
1 trigger: L0 files >= level0_file_num_compaction_trigger
2 merge iterator over {L0 #1, L0 #2, overlapping L1 files}
3 a: versions 2,1,0 -> keep a=2 b: 5,4 -> keep b=5 c=3, d=7 copied
4 write new L1 file(s) [a=2 b=5 c=3 d=7]; record in MANIFEST
5 delete inputs; disk usage was input+output during step 4Leveled compaction (LCS, RocksDB Level) Must-know
In plain words: every level is one sorted run, about ten times larger than the one above; a file moves down by merging into the few overlapping files below it.
Common misunderstanding: "Leveled means every write is rewritten ten times." Up to the fan-out per level, in the worst case, and RocksDB's default is really hybrid: L0 is tiered (overlapping files), L1+ are leveled.
Definition: RocksDB: "Each level (except level 0) is one data sorted run"; "Compaction triggers when number of L0 files reaches level0_file_num_compaction_trigger"; then any level over its target picks a file and merges it "with the overlapping range" of the next level. Targets grow by max_bytes_for_level_multiplier (10) from max_bytes_for_level_base (256 MB); with level_compaction_dynamic_level_bytes (default true in current RocksDB) targets are computed from the last level so that "90% of data is stored in the last level". The wiki's summary: "Classic Leveled compaction, introduced by LSM-tree paper by O'Neil et al, minimizes space amplification at the cost of read and write amplification." Cassandra's LCS: "optimized for read heavy workloads, or workloads with lots of updates and deletes."
Use when: read-heavy, update-heavy, delete-heavy, disk space tight.
Size-tiered and universal compaction (STCS, RocksDB Universal) Must-know
In plain words: wait until several files of similar size exist, then merge them into one bigger file.
Common misunderstanding: "Size-tiered is the simple, safe default." It is Cassandra's default for compatibility, but it needs free space as large as the biggest merge and lets many runs pile up for reads.
Definition: RocksDB's universal page: "leveled compaction tends to aggressively merge a smaller sorted run into a larger one, while 'tiered' waits for several sorted runs with similar size and merge them together", and "Universal Compaction Style is a compaction style, targeting the use cases requiring lower write amplification, trading off read amplification and space amplification." ScyllaDB's STCS triggers "when the system has enough (four by default) similarly sized SSTables." Cassandra: "STCS is the default compaction strategy, because it is useful as a fallback when other strategies don't fit the workload", while "UCS is a good choice for most workloads and is recommended for new workloads" (Unified Compaction Strategy, Cassandra 5.0, which can behave as tiered or leveled per its scaling parameter).
"Universal typically results in lower write-amplification but higher space- and read-amplification than Level Style Compaction." — RocksDB Wiki, RocksDB Overview
Use when: write-heavy ingest, bulk loads, data that is mostly appended and rarely read by key.
Time-window compaction (TWCS) Important
In plain words: group files by the time their data was written; compact inside the current window only; when a whole window has expired, drop its file.
Common misunderstanding: "TWCS works for any table with timestamps." It works when data arrives roughly in time order and expires by TTL. Out-of-order writes, updates to old rows, or explicit deletes defeat it, because old windows then hold live and dead data mixed.
Definition: Cassandra: "The TimeWindowCompactionStrategy (TWCS) is the recommended compaction strategy for time-series and expiring Time-To-Live (TTL) workloads." Windows are set with compaction_window_unit and compaction_window_size; "operators should select a compaction_window_unit and compaction_window_size pair that produces approximately 20-30 windows", for example "If writing with a 90 day TTL, for example, a 3 Day window would be a reasonable choice". Inside the current window it uses STCS. ScyllaDB has the same TWCS.
FIFO compaction Good to know
In plain words: never merge; when the total size exceeds a limit, delete the oldest file.
Definition: RocksDB: "In FIFO compaction, all files are in level 0. When total size of the data exceeds configured size (CompactionOptionsFIFO::max_table_files_size), we delete the oldest table file. This means that write amplification of data is always 1 (in addition to WAL write amplification)." And the warning: "it can drop data without informing users." Options: ttl, allow_compaction for light merging of fresh L0 files.
Use when: logs, caches, query logs, short-lived telemetry where losing the oldest data is the point.
| Strategy | Products | Write amp | Read amp | Space amp | Trigger knobs |
|---|---|---|---|---|---|
| Leveled | RocksDB kCompactionStyleLevel (default), LevelDB, Pebble, Cassandra/ScyllaDB LCS | High | Low | ~1.1× | level0_file_num_compaction_trigger, max_bytes_for_level_base, sstable_size_in_mb (LCS, 160 MB) |
| Size-tiered / universal | Cassandra/ScyllaDB STCS, RocksDB kCompactionStyleUniversal, HBase (exploring) | Low | Higher | Up to ~2× | min_threshold (4), size_ratio, max_size_amplification_percent |
| Unified (UCS) | Cassandra 5.0 | Tunable | Tunable | Tunable | scaling_parameters |
| Incremental (ICS) | ScyllaDB Enterprise | Low | Medium | Lower than STCS | sstable_size_in_mb |
| Time-window | Cassandra/ScyllaDB TWCS | Low | Few windows | Freed per window | compaction_window_unit, compaction_window_size |
| FIFO | RocksDB kCompactionStyleFIFO | 1 (+WAL) | Every file | Capped | max_table_files_size, ttl |
Deletes, tombstones and compaction debt
Tombstones Must-know
In plain words: in an LSM you cannot erase a value inside an immutable file, so a delete writes a marker, the tombstone, that hides older values until compaction removes both.
Common misunderstanding: "Delete frees space and speeds things up." A delete is a write; it adds data, and reads that scan over many tombstones get slower until compaction purges them.
Definition: a tombstone is an entry of type deletion with a newer sequence number than the value it shadows. It can be dropped only when it reaches the bottommost level containing the key (nothing older can exist below it) and no snapshot needs it. Cassandra adds a distributed rule: "The tombstone must be older than gc_grace_seconds" (default 864000, ten days), so that a replica that missed the delete is repaired before the tombstone disappears; otherwise deleted data re-appears ("zombie" rows). "Note that tombstones will not be removed until a compaction event even if gc_grace_seconds has elapsed." Cassandra also has tombstone_threshold and unchecked_tombstone_compaction to compact single SSTables full of tombstones, and warns/fails queries via tombstone_warn_threshold (1000) and tombstone_failure_threshold (100000) in cassandra.yaml.
Queue table in Cassandra: consume = DELETE row (anti-pattern)
1 INSERT job 1..100000 into partition 'queue'
2 workers DELETE jobs 1..99990 as they finish -> 99990 tombstones
3 SELECT ... FROM queue WHERE p='queue' LIMIT 10
4 scans 99990 tombstones to find 10 live rows -> tombstone_warn / TombstoneOverwhelmingException
5 compaction cannot drop them before gc_grace_seconds (10 days)Real scenario: a queue or inbox modelled as a Cassandra partition with deletes; a RocksDB-backed TiKV table where a nightly job deletes yesterday's keys and every range scan the next morning crawls; MyRocks with DELETE of millions of rows followed by a slow SELECT ... ORDER BY id LIMIT.
| Product | Delete writes | Purged when | Knobs |
|---|---|---|---|
| RocksDB / Pebble | Point tombstone (Delete, SingleDelete) | Bottommost compaction, no snapshot needs it | CompactOnDeletionCollector, bottommost_level_compaction |
| Cassandra / ScyllaDB | Cell, row, range or partition tombstone; TTL expiry | Compaction after gc_grace_seconds | tombstone_threshold, gc_grace_seconds, tombstone_*_threshold |
| HBase | Delete marker | Major compaction | hbase.hregion.majorcompaction |
| PostgreSQL (for contrast) | Sets xmax; tuple is dead | VACUUM | autovacuum settings (MVCC & VACUUM) |
| InnoDB (for contrast) | Delete-mark in place | Purge thread | innodb_purge_threads, innodb_max_purge_lag |
Fix: see avoiding tombstone storms.
Range deletes Important
In plain words: one marker that deletes every key in [start, end) instead of one tombstone per key.
Definition: RocksDB DeleteRange: "Under the hood, this creates a range tombstone represented as a single kv, which significantly speeds up write performance." Range tombstones live in the SST's range-deletion block; Pebble "inherits the RocksDB file formats and a few extensions such as range deletion" and uses them heavily (CockroachDB drops a whole table or range with one). Cassandra has range tombstones for clustering-key ranges and partition tombstones for DELETE FROM t WHERE pk = ?.
Fix: delete by prefix or range with DeleteRange (RocksDB/Pebble) or by partition (Cassandra), never by scanning and deleting key by key; better still, design keys so whole files or partitions expire (TWCS, FIFO, DROP PARTITION).
Compaction debt and write stalls Must-know
In plain words: if you write faster than compaction can merge, unmerged files pile up (debt). The engine then deliberately slows or stops writes so reads and disk space do not explode.
Common misunderstanding: "A write stall is a bug or a disk failure." It is a safety valve. Without it, RocksDB's page says the database would "Increase space amplification, which could lead to running out of disk space" and "Increase read amplification, significantly degrading read performance."
Definition: RocksDB stalls for three reasons, each with a log line you can grep:
| Cause | Slowdown at | Stop at | LOG message |
|---|---|---|---|
| Too many memtables | max_write_buffer_number - 1 (if > 3) | max_write_buffer_number (2) | Stopping writes because we have 5 immutable memtables (waiting for flush), max_write_buffer_number is set to 5 |
| Too many L0 files | level0_slowdown_writes_trigger (20) | level0_stop_writes_trigger (36) | Stalling writes because we have 4 level-0 files |
| Pending compaction bytes | soft_pending_compaction_bytes_limit (64 GB) | hard_pending_compaction_bytes_limit (256 GB) | Stalling writes because of estimated pending compaction bytes 500000000 |
During a slowdown writes are throttled to delayed_write_rate; "write stalls apply to the whole DB". WriteOptions.no_slowdown = true makes a write fail fast with Status::Incomplete() instead of blocking. Cassandra shows the same debt as rising PendingTasks in nodetool compactionstats and more SSTables per read; HBase blocks updates when memstores exceed hbase.regionserver.global.memstore.size.
Write burst on RocksDB with defaults
1 t=0s 100 MB/s writes, flush makes one L0 file every ~0.6 s
2 t=2s L0 = 4 files -> L0->L1 compaction starts (1 thread, max_background_jobs=2)
3 t=10s L0 = 20 files -> "Stalling writes": throttled to delayed_write_rate
4 t=20s L0 = 36 files -> "Stopping writes": p99 latency = seconds
5 burst ends; compaction drains L0; writes resume. Reads were slow the whole time.Fix: see tuning compaction for write bursts.
Other designs and the hardware underneath
LSM and B-tree on SSD: erase blocks and wear Important
In plain words: flash cannot overwrite a page in place. The drive writes new data elsewhere and erases whole blocks later, so small random overwrites cost the drive extra internal writes and wear.
Common misunderstanding: "SSDs have no seek time, so random writes are free." Random reads are cheap on SSD. Random small writes cause internal garbage collection in the flash translation layer (FTL): pages are programmed in units of a few KB, erased in blocks of hundreds of KB to MB, and live pages must be copied out before an erase. That is device-level write amplification, and flash cells survive a limited number of program/erase cycles. (Flash mechanics here are general background, not stated in the sources quoted on this page.)
Definition: an LSM writes large sequential files and deletes whole files, which lets the FTL erase whole blocks with little copying (and TRIM/discard tells it the space is free). This is why RocksDB started "with the initial focus on fast storage (especially Flash storage)" and why MyRocks advertises "better endurance of flash storage". A B-tree's random page writes are fine on SSD for read-heavy workloads; they become a cost when the working set exceeds memory and writes are small and random. InnoDB's innodb_doublewrite (on by default) doubles page writes to survive torn pages; innodb_flush_neighbors=0 is the usual SSD setting.
| Pattern | HDD | SSD |
|---|---|---|
| Random 4-16 KB reads | Slow (seek ~5-10 ms) | Fast (~0.1 ms) |
| Random small writes | Slow | Fast at first; FTL GC and wear add cost under sustained load |
| Large sequential writes | Fast | Fast, least wear |
| Whole-file delete + TRIM | Free | Lets the FTL reclaim blocks cheaply |
Copy-on-write B-trees (LMDB, bbolt) Important
In plain words: never change a page in place: write a changed copy of the leaf, then copies of every parent up to a new root, then switch the root pointer.
Common misunderstanding: "Copy-on-write means slow writes." Each commit rewrites one path (3-4 pages), sequentially appended or into free pages; there is no WAL and no recovery step. The cost is one writer at a time and free-page bookkeeping.
Definition: LMDB: "Data pages use a copy-on- write strategy so no active data pages are ever overwritten, which also provides resistance to corruption and eliminates the need of any special recovery procedures after a system crash." And: "The database structure is multi-versioned so readers run with no locks; writers cannot block readers, and readers don't block writers." bbolt (etcd) follows the same design. A long-lived reader pins old pages and the file grows (stale-reader checks exist for this reason).
Update key k in a copy-on-write B+tree
1 copy leaf L -> L' with k changed (new page)
2 copy parent P -> P' pointing to L'
3 copy root R -> R' pointing to P'
4 fsync data pages; atomically write meta page: root = R'
5 readers that started before step 4 still see R; old pages freed when they finishBε-trees and fractal trees Good to know
In plain words: a B-tree whose internal nodes also keep a buffer of pending changes; writes go into the root's buffer and are pushed down in batches when a buffer fills.
Definition: Bender et al.: a Bε-tree has "insert performance orders of magnitude faster than a B-tree" with point queries comparable to a B-tree; "The Bε-tree has since been used by both the high-performance, commercial TokuDB database [...] and the BetrFS research file system." Tokutek marketed it as the fractal tree (TokuDB for MySQL, TokuMX for MongoDB; Percona later maintained PerconaFT). It sits between B-tree and LSM on the RUM curve: batched writes like an LSM, one sorted structure like a B-tree. In TokuDB nodes are "approximately 4 MB".
Heap + B-tree (PostgreSQL) vs clustered B+tree (InnoDB) Must-know
In plain words: PostgreSQL stores rows in an unordered heap and every index points to a row's physical location; InnoDB stores rows inside the primary-key B+tree, and secondary indexes store the primary key.
Common misunderstanding: "Both are B-tree engines, so they store data the same way." Insert order, update cost, index size and range-scan locality all differ.
Definition: InnoDB: "Each InnoDB table has a special index called the clustered index that stores row data", "When you define a PRIMARY KEY on a table, InnoDB uses it as the clustered index", and every secondary index entry carries the primary key, so a secondary lookup is two tree walks. PostgreSQL: heap pages of 8 kB, tuples addressed by ctid (page, item); an UPDATE writes a new tuple version, and unless it is a HOT update (no indexed column changed, room on the same page) every index gets a new entry too. Details: Database Internals, MVCC & VACUUM.
INSERT 1M rows with random UUID primary key
1 PostgreSQL: heap append (next free page, sequential) + PK index insert (random leaf)
2 InnoDB: clustered index insert at a random leaf: the ROW itself moves into a random page
3 PostgreSQL: heap stays dense; PK index ~70% full after random splits
4 InnoDB: data pages ~50-70% full -> table larger, secondary indexes carry the 16-byte UUID
5 With bigint identity keys both append at the right edge and stay ~full| Aspect | PostgreSQL heap + B-tree | InnoDB clustered | SQL Server | Oracle |
|---|---|---|---|---|
| Row location | Heap, ctid | Leaf of PK B+tree | Clustered index if defined, else heap | Heap by default; IOT optional |
| Secondary index points to | ctid | Primary key value | Clustering key or RID | ROWID |
| Random PK inserts | Heap fine, PK index fragments | Whole table fragments | Like InnoDB when clustered | Heap fine |
| Range scan by PK | Index + scattered heap pages (unless CLUSTERed) | Sequential leaves | Sequential | IOT: sequential |
| Update of non-key column | New tuple; HOT avoids index writes | In place + undo | In place | In place + undo |
What each product really does
| Product | Engine family | What to know | Defaults worth naming |
|---|---|---|---|
| PostgreSQL | Heap + B-tree indexes, WAL | Out-of-place row versions in the heap; indexes point to ctid; VACUUM reclaims; B-tree has deduplication and "bottom-up index deletion" against version churn | 8 kB pages, fillfactor 100 heap / 90 B-tree |
| MySQL InnoDB | Clustered B+tree, redo + undo, doublewrite | Rows live in the PK tree; secondary indexes carry the PK; purge reclaims | 16 KB pages, innodb_doublewrite=ON |
| MyRocks (MySQL/MariaDB/Percona) | RocksDB under the MySQL handler | Facebook's wiki: it "uses much less space, and has a much smaller write volume (write amplification) with small read penalty compared to a B+ tree database implementation such as InnoDB"; myrocks.io: "2x better compression compared to compressed InnoDB" | ENGINE=ROCKSDB, column families per index |
| SQLite | B-tree file; rollback journal or WAL | Every table is a B-tree keyed by rowid (or PK with WITHOUT ROWID); one writer | 4096-byte pages; see SQLite |
| SQL Server | B+tree (clustered or heap) | Clustered index = InnoDB-like; heap + RID otherwise; FILLFACTOR | 8 KB pages, 64 KB extents |
| Oracle | Heap (default) or index-organised table | IOT = clustered; PCTFREE reserves update space | DB_BLOCK_SIZE usually 8 KB |
| MongoDB WiredTiger | B-tree with MVCC, checkpoints + journal; LSM experimental | "WiredTiger uses a write-ahead log, or journal, in combination with checkpoints to ensure data durability"; checkpoints "at intervals of 60 seconds"; WiredTiger's own docs warn its LSM "should be viewed as experimental code" | Snappy block compression, cache ~50% of (RAM − 1 GB) |
| RocksDB | Leveled LSM (hybrid), column families | Library; the reference for most tunables on this page | See knobs |
| LevelDB | Leveled LSM | The original Google library; single process, no column families | 4 MB memtable, 2 MB files |
| Pebble | Leveled LSM in Go | "a LevelDB/RocksDB inspired key-value store focused on performance and internal usage by CockroachDB"; RocksDB-compatible formats, range deletions | CockroachDB's only engine |
| Badger | LSM with key-value separation (WiscKey) | Keys in the LSM, values in a value log; lower write amplification for large values; value-log GC | Go, Dgraph |
| Cassandra | LSM per table (memtable, commit log, SSTables) | Compaction per table: STCS default, UCS recommended for new tables, LCS for reads, TWCS for TTL time series | gc_grace_seconds 864000 |
| ScyllaDB | LSM, shard-per-core C++ | Same SSTable family as Cassandra; STCS, LCS, TWCS, ICS | See Cassandra & ScyllaDB |
| HBase | LSM on HDFS (memstore, HFile, WAL) | Minor and major compactions; region servers block when memstores are full | hbase.hregion.memstore.flush.size |
| TiKV (TiDB) | RocksDB (two instances) | "TiKV uses RocksDB because RocksDB is mature and high-performance"; "All data in a TiKV node shares two RocksDB instances. One is for Raft log (often called raftdb), and the other is for user data and MVCC metadata (often called kvdb)." Column families default, write, lock, raft | Titan optional for large values |
| CockroachDB | Pebble | MVCC keys in one LSM per store; range deletes for drops | See Distributed SQL |
| LMDB, bbolt (etcd) | Copy-on-write B+tree, mmap | No WAL, single writer, lock-free readers | bbolt default page = OS page size |
| Redis | In-memory hash table + RDB snapshots / AOF log | Not a disk engine: the dataset lives in RAM; "RDB persistence performs point-in-time snapshots of your dataset at specified intervals"; "AOF persistence logs every write operation received by the server" | appendfsync everysec; see Redis |
Redis vs the disk engines. Redis keeps every key in memory, so reads and writes cost no disk I/O; persistence is a side channel. RDB is a fork-and-dump snapshot (fast restarts, loses writes since the last snapshot). AOF is an append-only command log, like a WAL with no data files behind it, fsynced per appendfsync always | everysec | no, and compacted by BGREWRITEAOF (an AOF rewrite is Redis's version of compaction). The trade: RAM cost per GB is far higher than disk, and the dataset must fit in memory.
Mechanics and knobs
RocksDB tunables that matter first
All defaults below are from RocksDB's options.h / advanced_options.h on main (read 2026-11-25); all are "Dynamically changeable through SetOptions() API" unless noted.
| Option | Default | Meaning | Raise it when | Cost of raising |
|---|---|---|---|---|
write_buffer_size | 64 MB | Size of one memtable | Write bursts, too many small L0 files | Memory; longer WAL replay |
max_write_buffer_number | 2 | Memtables (active + immutable) before writes stop | Flush cannot keep up with bursts | Memory |
min_write_buffer_number_to_merge | 1 | Immutable memtables merged in one flush | Many overwrites of hot keys | Read path checks more memtables |
level0_file_num_compaction_trigger | 4 | L0 files that start L0→L1 compaction | Fewer, larger compactions | More L0 files to read |
level0_slowdown_writes_trigger | 20 | L0 files that start throttling | Short bursts you want to absorb | Read amp during burst |
level0_stop_writes_trigger | 36 | L0 files that stop writes | Same | Same |
target_file_size_base | 64 MB | SST size at L1 (× target_file_size_multiplier per level) | Fewer files, fewer open handles | Coarser compactions |
max_bytes_for_level_base | 256 MB | Target size of L1 | Match to L0 size (≈ write_buffer_size × trigger) | Bigger L0→L1 merges |
max_bytes_for_level_multiplier | 10 | Fan-out between levels | Lower write amp needs lower (more levels) | Read/space amp |
level_compaction_dynamic_level_bytes | true | Compute level targets from the last level | Keep true | – |
max_background_jobs | 2 | Flush + compaction threads (DB option, SetDBOptions) | Compaction debt on a multi-core box | CPU, I/O |
soft_ / hard_pending_compaction_bytes_limit | 64 GB / 256 GB | Debt that slows / stops writes | Bulk loads | Disk usage |
compaction_style | kCompactionStyleLevel | Leveled / Universal / FIFO | – | Changing it needs a full compaction |
block_size (table option) | 4 KB | Data block size | Scan-heavy, compression ratio | Point-read cost |
filter_policy (table option) | none | e.g. NewBloomFilterPolicy(10) | Always for point reads | ~10 bits/key memory |
Cassandra, ScyllaDB and HBase knobs
| Product | Knob | Default | Purpose |
|---|---|---|---|
| Cassandra STCS | min_threshold / max_threshold | 4 / 32 | SSTables per minor compaction |
| Cassandra STCS | bucket_low / bucket_high, min_sstable_size | 0.5 / 1.5, 50MB | What counts as "similar size" |
| Cassandra LCS | sstable_size_in_mb | 160 | Target SSTable size |
| Cassandra TWCS | compaction_window_unit, compaction_window_size | DAYS, 1 | Window per SSTable |
| Cassandra (all) | tombstone_threshold | 0.2 | Ratio that triggers single-SSTable tombstone compaction |
| Cassandra (all) | unchecked_tombstone_compaction | false | Skip the eligibility pre-check |
| Cassandra table | gc_grace_seconds | 864000 (10 days) | Minimum tombstone age before purge |
| Cassandra UCS | scaling_parameters | T4 | T = tiered, L = leveled; "Using scaling_parameters:T8 will result in more SSTables per read." |
| HBase | hbase.hregion.memstore.flush.size | 128 MB | Memstore flush size |
| HBase | hbase.hregion.majorcompaction | 7 days | Major compaction period (purges deletes) |
B-tree engine knobs (for contrast)
| Product | Knob | Default | Effect on the storage structure |
|---|---|---|---|
| PostgreSQL | fillfactor (table / index) | 100 / 90 | Free space for HOT updates and fewer splits |
| PostgreSQL | shared_buffers | 128 MB | Page cache inside PostgreSQL |
| PostgreSQL | checkpoint_timeout, max_wal_size | 5 min, 1 GB | How often dirty pages are written; full-page writes after each checkpoint |
| PostgreSQL | full_page_writes | on | Torn-page protection (first change after checkpoint logs the whole page) |
| InnoDB | innodb_buffer_pool_size | 128 MB | Page cache |
| InnoDB | innodb_fill_factor | 100 | Space left on pages during sorted index build |
| InnoDB | innodb_doublewrite | ON | Torn-page protection: pages written twice |
| InnoDB | innodb_flush_neighbors | 0 (8.0+) | Flush adjacent dirty pages together (HDD-era) |
| InnoDB | innodb_redo_log_capacity | 100 MB | Redo space; checkpoint pressure |
| WiredTiger | storage.wiredTiger.engineConfig.cacheSizeGB | 50% of (RAM − 1 GB) | Cache size |
Error and log messages you will see
| Message | Product | Meaning | Action |
|---|---|---|---|
Stalling writes because we have 4 level-0 files | RocksDB LOG | L0 debt, throttling | Compaction threads, bigger memtables, check disk |
Stopping writes because we have 5 immutable memtables (waiting for flush) | RocksDB LOG | Flush behind | More write buffers / background jobs |
Stalling writes because of estimated pending compaction bytes | RocksDB LOG | Deep compaction debt | Fix compaction throughput; check max_bytes_for_level_base |
Status::Incomplete() with no_slowdown | RocksDB API | Write refused during a stall | Retry later or shed load |
Read 10 live rows and 1001 tombstone cells for query ... (warning) | Cassandra log | Over tombstone_warn_threshold (1000) | Model change; see tombstone storms |
Scanned over 100001 tombstones during query ...; query aborted / TombstoneOverwhelmingException | Cassandra | Over tombstone_failure_threshold (100000) | Same |
| Region server stops accepting updates ("new updates are blocked and flushes are forced") | HBase | Global memstore limit | Faster flush/compaction, more region servers |
could not extend file ... No space left on device | PostgreSQL | Disk full (bloat, WAL) | VACUUM, free space, archive WAL |
Solving the classic problems
Picking an engine
| Option | How | Advantage | Cost / limitation |
|---|---|---|---|
| Stay on B-tree (PostgreSQL / InnoDB) | Default; tune keys, fillfactor, partitions | One system, mature tooling, predictable reads | Write ceiling at random-I/O rate; bloat management |
| B-tree + application-level batching | Append-only event table + periodic fold (the Laravel snippet below) | LSM write pattern without a new engine | You own the "compaction" job |
| MyRocks inside MySQL | ENGINE=ROCKSDB per table | Less space and write amp, same SQL | Fewer features (no FK, gap-lock differences), fewer experts |
| RocksDB / Pebble embedded | Library in your service | Full control of the LSM | You build replication, backup, ops |
| Cassandra / ScyllaDB | Wide-column LSM cluster | Linear write scaling, TWCS for TTL | Query-first data modelling, tombstones, eventual consistency |
| TiDB / CockroachDB | Distributed SQL on RocksDB / Pebble | SQL + horizontal write scaling | Latency of consensus, operational complexity |
| Redis | In-memory | Microsecond latency | RAM cost, persistence is secondary |
-- MySQL: one write-heavy table on MyRocks, the rest stays InnoDB
CREATE TABLE events (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
device_id BIGINT NOT NULL,
ts DATETIME(6) NOT NULL,
payload JSON,
PRIMARY KEY (id),
KEY idx_device_ts (device_id, ts)
) ENGINE=ROCKSDB;
-- PostgreSQL: keep the B-tree, make writes cheap (monotonic key, room for HOT updates)
CREATE TABLE events (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
device_id bigint NOT NULL,
ts timestamptz NOT NULL,
payload jsonb
) WITH (fillfactor = 90);// Go: Pebble (CockroachDB's engine) as an embedded LSM.
package main
import (
"log"
"github.com/cockroachdb/pebble"
)
func main() {
db, err := pebble.Open("/var/lib/app/pebble", &pebble.Options{
MemTableSize: 64 << 20, // like RocksDB write_buffer_size
MemTableStopWritesThreshold: 4, // like max_write_buffer_number
L0CompactionThreshold: 4, // like level0_file_num_compaction_trigger
L0StopWritesThreshold: 36,
})
if err != nil {
log.Fatal(err)
}
defer db.Close()
if err := db.Set([]byte("device:7:2026-11-25T10:00"), []byte(`{"t":21.5}`), pebble.Sync); err != nil {
log.Fatal(err)
}
}// Laravel: choose the engine per table in a migration (MySQL/MariaDB only).
Schema::create('events', function (Blueprint $table) {
$table->engine('ROCKSDB'); // requires a MyRocks-enabled server; InnoDB otherwise
$table->id();
$table->unsignedBigInteger('device_id');
$table->dateTime('ts', precision: 6);
$table->json('payload')->nullable();
$table->index(['device_id', 'ts']);
});Tuning compaction for write bursts
| Option | How | Advantage | Cost / limitation |
|---|---|---|---|
| More background jobs | max_background_jobs = cores/2..cores | Compaction keeps up | CPU and I/O taken from foreground |
| Bigger memtables | write_buffer_size 128-256 MB, max_write_buffer_number 4-6 | Absorbs bursts, fewer L0 files | Memory, longer recovery replay |
| Match L1 to L0 | max_bytes_for_level_base ≈ write_buffer_size × min_write_buffer_number_to_merge × level0_file_num_compaction_trigger | L0→L1 compactions stay balanced | Needs recalculation when memtable changes |
| Raise stall triggers temporarily | level0_slowdown_writes_trigger, pending-bytes limits via SetOptions | No stalls during a known burst | Read amp and disk usage during the burst |
| Universal compaction for the hot CF | compaction_style = kCompactionStyleUniversal | Lower write amp | Space amp up to 2× |
| Bulk load via SST ingestion | Build sorted SSTs with SstFileWriter, IngestExternalFile | Bypasses memtable and most compaction | Data must be pre-sorted, non-overlapping ideally |
| Subcompactions | max_subcompactions > 1 | Parallel L0→L1 | CPU |
| Rate-limit the writers | Queue upstream; WriteOptions.no_slowdown and retry | Predictable latency | Writers wait somewhere else |
RocksDB OPTIONS file fragment for a burst-heavy ingest column family
[CFOptions "events"]
1 write_buffer_size=134217728 # 128 MB
2 max_write_buffer_number=4
3 min_write_buffer_number_to_merge=2
4 level0_file_num_compaction_trigger=4 # L0 ~ 4 x 2 x 128 MB = 1 GB
5 max_bytes_for_level_base=1073741824 # L1 = 1 GB to match L0
6 target_file_size_base=134217728
7 level0_slowdown_writes_trigger=30
8 level0_stop_writes_trigger=50
[DBOptions]
9 max_background_jobs=8// Go: back off when an embedded LSM is in a stall instead of piling up goroutines.
func writeWithBackoff(ctx context.Context, db *pebble.DB, k, v []byte) error {
for attempt := 0; ; attempt++ {
m := db.Metrics()
// L0 sublevels growing is Pebble's early warning of compaction debt.
if m.Levels[0].Sublevels < 20 || attempt >= 5 {
return db.Set(k, v, pebble.NoSync)
}
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(time.Duration(50<<attempt) * time.Millisecond):
}
}
}// Laravel: smooth the burst before it reaches the engine. Jobs carry batches,
// a rate limiter caps how many hit the database per second.
use Illuminate\Support\Facades\RateLimiter;
final class IngestReadings implements ShouldQueue
{
use Queueable;
public function __construct(public array $rows) {}
public function handle(): void
{
if (RateLimiter::tooManyAttempts('ingest', 200)) {
$this->release(RateLimiter::availableIn('ingest'));
return;
}
RateLimiter::increment('ingest');
DB::table('readings')->insert($this->rows); // one multi-row INSERT per job
}
}Avoiding tombstone storms
| Option | How | Advantage | Cost / limitation |
|---|---|---|---|
| Expire by file, not by row | TWCS + TTL (Cassandra), FIFO/ttl (RocksDB), DROP/DETACH PARTITION (PostgreSQL) | No tombstones at all | Data must be time-ordered |
| Range or partition deletes | DeleteRange (RocksDB/Pebble), DELETE ... WHERE pk = ? (Cassandra partition tombstone) | One marker instead of millions | Range tombstones still cost reads until compacted |
| Time-bucketed partitions | Partition key includes a day/hour bucket | Old buckets are never read again | Queries span buckets |
| Don't model queues on an LSM | Use a broker or a B-tree table with SKIP LOCKED | Deletes are cheap in a B-tree | Another system |
Lower gc_grace_seconds with regular repair | e.g. 1-3 days if repair runs more often than that | Tombstones purged sooner | Zombie data if repair misses the window |
| Deletion-triggered compaction | RocksDB NewCompactOnDeletionCollectorFactory; Cassandra tombstone_threshold, unchecked_tombstone_compaction | Purges dense-tombstone files early | Extra compaction I/O |
| Avoid null writes | Cassandra: unset values instead of null in prepared statements | Each null is a cell tombstone | Driver discipline |
-- Cassandra CQL: time series that expires by window, not by delete
CREATE TABLE metrics.readings (
device_id bigint,
day date,
ts timestamp,
value double,
PRIMARY KEY ((device_id, day), ts)
) WITH CLUSTERING ORDER BY (ts DESC)
AND default_time_to_live = 7776000 -- 90 days
AND gc_grace_seconds = 86400 -- only with repair running daily
AND compaction = {'class': 'TimeWindowCompactionStrategy',
'compaction_window_unit': 'DAYS',
'compaction_window_size': 3};
-- PostgreSQL equivalent: drop whole partitions instead of DELETE
ALTER TABLE readings DETACH PARTITION readings_2026_08 CONCURRENTLY;
DROP TABLE readings_2026_08;// Go + Pebble: delete a device's history with one range tombstone,
// not one tombstone per key.
func deleteDevice(db *pebble.DB, deviceID string) error {
start := []byte("device:" + deviceID + ":")
end := []byte("device:" + deviceID + ";") // ';' sorts right after ':'
return db.DeleteRange(start, end, pebble.Sync)
}// Laravel + PostgreSQL: retention by partition, scheduled.
Schedule::call(function () {
$old = now()->subMonths(3)->format('Y_m');
DB::statement("ALTER TABLE readings DETACH PARTITION readings_{$old}");
DB::statement("DROP TABLE IF EXISTS readings_{$old}");
})->monthly()->onOneServer();Reducing B-tree write amplification
| Option | How | Advantage | Cost |
|---|---|---|---|
| Monotonic keys | bigint identity, UUIDv7/ULID instead of UUIDv4 | Right-edge inserts, full pages, small hot set | Key reveals order/time |
| Fill factor | fillfactor=80-90 on update-heavy PostgreSQL tables | HOT updates, fewer splits | More pages |
| Fewer indexes | Drop unused (pg_stat_user_indexes.idx_scan = 0) | Every index is another random write | Some queries slower |
| Batch writes | Multi-row INSERT, COPY, LOAD DATA | Amortise WAL and page writes | Latency of the batch |
| Rebuild bloated indexes | REINDEX CONCURRENTLY, OPTIMIZE TABLE / ALTER TABLE ... FORCE | Dense pages again | I/O during rebuild |
Benchmarking pitfalls
Most published "B-tree vs LSM" numbers measure the setup, not the engine. Check every benchmark (including your own) against this list:
| Pitfall | Why it misleads | Do instead |
|---|---|---|
| Run too short | An empty LSM has no compaction debt; first minutes look great | Run until the LSM reaches steady state (levels full, compaction continuous): hours, not minutes |
| Data fits in RAM | Both engines become in-memory structures | Dataset several times larger than cache |
| Empty or freshly loaded B-tree | No fragmentation, no bloat | Age it with updates and deletes |
| Only point reads or only inserts | Hides the weak side (range scans for LSM, random writes for B-tree) | Use a mixed workload (YCSB A-F, sysbench OLTP, db_bench readwhilewriting) |
| Throughput averages | Write stalls and compaction show in p99/p999 | Report latency percentiles over time |
| Ignoring device effects | SSD state (fresh vs full, TRIM), cloud burst credits | Precondition the drive; run longer than burst credits |
| Different durability | sync=false vs fsync per commit; innodb_flush_log_at_trx_commit=2 vs 1 | Same durability on both sides |
| Different compression | LSM with zstd vs uncompressed InnoDB | Compare equal compression or report both |
| Not measuring space and write bytes | The win may be in amplification, not speed | Report bytes written (iostat) and disk used |
| Single client | No contention, no group commit | Realistic concurrency |
Tools: RocksDB db_bench (fillrandom, readrandom, readwhilewriting, overwrite), YCSB (workloads A-F, any store), sysbench (oltp_read_write, oltp_insert for MySQL/PostgreSQL), pgbench, Cassandra cassandra-stress / nosqlbench.
Choosing an engine
| Workload | Recommended | Extra technique | Reason |
|---|---|---|---|
| Read-heavy OLTP (orders, users, accounts) | B-tree: PostgreSQL / InnoDB | Monotonic PKs, right indexes, enough buffer pool | One home per key, predictable reads, mature tooling |
| Write-heavy time series / metrics with TTL | LSM with TWCS (Cassandra/ScyllaDB) or FIFO/universal (RocksDB); or PostgreSQL partitions | Time-bucketed keys, drop by window | Sequential writes, whole-file expiry |
| Event log / audit append-only | PostgreSQL/InnoDB append table, or LSM | Partition by time, BRIN index in PostgreSQL | Right-edge appends are cheap even in a B-tree |
| Large KV store, mostly point lookups | RocksDB / Pebble / Badger (large values) | Bloom filters, block cache, leveled | Space and write efficiency on flash |
| Write-heavy OLTP in MySQL running out of SSD | MyRocks for those tables | Keep InnoDB for the rest | Less space and write amp |
| Horizontally scaled SQL | TiDB (RocksDB), CockroachDB (Pebble) | Range splits, follower reads | LSM under consensus |
| Document store | MongoDB WiredTiger (B-tree) | Compression, checkpoints | Default and only supported engine |
| Embedded, read-mostly config/state | bbolt / LMDB / SQLite | One writer | Copy-on-write or B-tree, no ops |
| Cache, counters, sessions | Redis | AOF everysec if loss matters | RAM speed |
| Queue | Not an LSM | Broker, or B-tree table with SKIP LOCKED | Delete-heavy patterns create tombstones |
| Analytics scans | Columnar (see OLTP vs OLAP) | – | Neither row engine is built for it |
Go
Before
A sorted-pages store with in-place updates: the leaf level of a B+tree, without the inner nodes. It runs 100,000 sequential and 100,000 random inserts and counts how many distinct pages each checkpoint has to write back. Sequential keys fill pages at the right edge (about 1,660 page writes in total); random keys dirty pages all over the store (about 59,000 page writes for the same rows), and splits leave the pages about 70% full.
// Command before models an update-in-place, page-oriented store: the shape
// of a B+-tree's leaf level. It is a teaching model, not a real B-tree: there
// are no inner nodes, only sorted leaf pages found by binary search.
//
// What it shows is the write pattern. Every Put rewrites the page that holds
// the key, wherever that page is. Random keys mean random page writes, and a
// full page must split before it can take another key.
package main
import (
"fmt"
"math/rand/v2"
"sort"
)
const pageCapacity = 64 // entries per page; real engines use 8 KB or 16 KB pages
type entry struct {
key uint64
value []byte
}
type page struct {
entries []entry // sorted by key
}
// Store is an ordered list of pages, like the leaf level of a B+-tree.
type Store struct {
pages []*page
pageWrites int // pages rewritten in place (each costs a random write)
splits int
dirty map[*page]bool
}
func NewStore() *Store {
return &Store{pages: []*page{{}}, dirty: map[*page]bool{}}
}
// findPage returns the index of the page whose key range covers key.
func (s *Store) findPage(key uint64) int {
i := sort.Search(len(s.pages), func(i int) bool {
p := s.pages[i]
return len(p.entries) > 0 && p.entries[0].key > key
})
if i > 0 {
i--
}
return i
}
// Put updates the value in place, or inserts it into its sorted position.
func (s *Store) Put(key uint64, value []byte) {
pi := s.findPage(key)
p := s.pages[pi]
j := sort.Search(len(p.entries), func(j int) bool { return p.entries[j].key >= key })
if j < len(p.entries) && p.entries[j].key == key {
p.entries[j].value = value // overwrite in place
s.markDirty(p)
return
}
p.entries = append(p.entries, entry{})
copy(p.entries[j+1:], p.entries[j:])
p.entries[j] = entry{key: key, value: value}
s.markDirty(p)
if len(p.entries) > pageCapacity {
// Appending at the right edge keeps the old page full; this mirrors the
// rightmost-split heuristic real engines use for increasing keys.
rightEdge := pi == len(s.pages)-1 && j == len(p.entries)-1
s.split(pi, rightEdge)
}
}
// split moves the upper half of a full page into a new page. In a real
// B+-tree the parent also gains a separator key and may split in turn.
func (s *Store) split(pi int, rightEdge bool) {
p := s.pages[pi]
mid := len(p.entries) / 2
if rightEdge {
mid = len(p.entries) - 1
}
right := &page{entries: append([]entry(nil), p.entries[mid:]...)}
p.entries = p.entries[:mid:mid]
s.pages = append(s.pages, nil)
copy(s.pages[pi+2:], s.pages[pi+1:])
s.pages[pi+1] = right
s.splits++
s.markDirty(p)
s.markDirty(right)
}
func (s *Store) markDirty(p *page) { s.dirty[p] = true }
// Checkpoint writes every dirty page back to its own place on disk. With
// random keys the dirty pages are scattered, so these are random writes.
func (s *Store) Checkpoint() {
s.pageWrites += len(s.dirty)
clear(s.dirty)
}
func (s *Store) Get(key uint64) ([]byte, bool) {
p := s.pages[s.findPage(key)]
j := sort.Search(len(p.entries), func(j int) bool { return p.entries[j].key >= key })
if j < len(p.entries) && p.entries[j].key == key {
return p.entries[j].value, true
}
return nil, false
}
func main() {
const rows, batch = 100_000, 1_000
payload := []byte("v")
sequential := NewStore()
random := NewStore()
for i := range rows {
sequential.Put(uint64(i), payload)
random.Put(rand.Uint64N(1<<40), payload)
if (i+1)%batch == 0 {
sequential.Checkpoint()
random.Checkpoint()
}
}
// Sequential keys fill pages left to right: a batch of 1,000 rows dirties
// about 16 pages, all at the right edge. Random keys scatter the same batch
// over hundreds of pages, each of which must be written back whole.
fmt.Printf("sequential: %d pages, %d splits, %d page writes\n",
len(sequential.pages), sequential.splits, sequential.pageWrites)
fmt.Printf("random: %d pages, %d splits, %d page writes\n",
len(random.pages), random.splits, random.pageWrites)
// Random splits leave pages about half to three-quarters full: the
// fragmentation that REINDEX or OPTIMIZE TABLE later reclaims.
fill := float64(rows) / float64(len(random.pages)*pageCapacity)
fmt.Printf("random fill factor: %.0f%%\n", fill*100)
if v, ok := sequential.Get(42); ok {
fmt.Printf("get 42 -> %s\n", v)
}
}After
A teaching LSM in six files, stdlib only. The memtable is a sorted slice searched with sort.Search, and a delete stores a tombstone instead of removing anything:
// Package main is a teaching LSM-tree: a write-ahead log, a memtable,
// immutable sorted files ("SSTables") with a sparse index and a bloom filter,
// tombstones for deletes, newest-first lookups and a naive size-tiered
// compaction. It is not production code: there is no concurrency, no
// checksums, no levels and no manifest.
package main
import "sort"
type kv struct {
key string
value []byte
tomb bool // a tombstone: "this key was deleted", shadows older values
}
// Memtable is the in-memory, sorted write buffer (C0 in O'Neil et al.).
// Real engines use a skip list; a sorted slice keeps the idea visible.
type Memtable struct {
entries []kv
bytes int
}
// set inserts or overwrites a key. The cost is memory only; nothing touches
// the data files until the memtable is flushed.
func (m *Memtable) set(e kv) {
i := sort.Search(len(m.entries), func(i int) bool { return m.entries[i].key >= e.key })
if i < len(m.entries) && m.entries[i].key == e.key {
m.bytes += len(e.value) - len(m.entries[i].value)
m.entries[i] = e
return
}
m.entries = append(m.entries, kv{})
copy(m.entries[i+1:], m.entries[i:])
m.entries[i] = e
m.bytes += len(e.key) + len(e.value) + 1
}
func (m *Memtable) Put(key string, value []byte) { m.set(kv{key: key, value: value}) }
// Delete does not remove anything: older files may still hold the key, so
// the memtable records a tombstone that will shadow them.
func (m *Memtable) Delete(key string) { m.set(kv{key: key, tomb: true}) }
// Get reports found=true for a tombstone too, so the caller stops searching
// older files; the caller then treats the key as absent.
func (m *Memtable) Get(key string) (kv, bool) {
i := sort.Search(len(m.entries), func(i int) bool { return m.entries[i].key >= key })
if i < len(m.entries) && m.entries[i].key == key {
return m.entries[i], true
}
return kv{}, false
}The write-ahead log appends every record before it reaches the memtable, is replayed on Open, and is deleted after a flush. Like RocksDB's default it hands each record to the OS without fsync:
package main
import (
"bufio"
"encoding/binary"
"errors"
"io"
"os"
)
// WAL is the write-ahead log that makes the memtable durable. Every Put and
// Delete is appended here before it touches the memtable; after a crash the
// log is replayed to rebuild the memtable. Once the memtable is flushed to an
// SSTable, its log is no longer needed and is deleted.
type WAL struct {
f *os.File
w *bufio.Writer
}
func OpenWAL(path string) (*WAL, error) {
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
if err != nil {
return nil, err
}
return &WAL{f: f, w: bufio.NewWriter(f)}, nil
}
// Append writes one record and hands it to the OS. Like RocksDB's default
// (WriteOptions.sync=false) this survives a process crash but not a power
// loss; call Sync for that, at the cost of one fsync per commit.
func (l *WAL) Append(e kv) error {
if _, err := l.w.Write(encodeRecord(e)); err != nil {
return err
}
return l.w.Flush()
}
func (l *WAL) Sync() error { return l.f.Sync() }
func (l *WAL) Close() error { return errors.Join(l.w.Flush(), l.f.Close()) }
// ReplayWAL rebuilds a memtable from a log. A torn last record (the process
// died mid-write) ends the replay; everything before it is recovered.
func ReplayWAL(path string) (*Memtable, error) {
m := &Memtable{}
f, err := os.Open(path)
if errors.Is(err, os.ErrNotExist) {
return m, nil
}
if err != nil {
return nil, err
}
defer f.Close()
r := bufio.NewReader(f)
for {
e, err := readRecord(r)
if err == io.EOF || err == io.ErrUnexpectedEOF {
return m, nil
}
if err != nil {
return nil, err
}
m.set(e)
}
}
// encodeRecord is shared by the WAL and SSTables: a kind byte (0 = value,
// 1 = tombstone), then uvarint-length-prefixed key and value.
func encodeRecord(e kv) []byte {
var kind byte
if e.tomb {
kind = 1
}
rec := []byte{kind}
rec = binary.AppendUvarint(rec, uint64(len(e.key)))
rec = append(rec, e.key...)
rec = binary.AppendUvarint(rec, uint64(len(e.value)))
return append(rec, e.value...)
}
func readRecord(r *bufio.Reader) (kv, error) {
kind, err := r.ReadByte()
if err != nil {
return kv{}, err // io.EOF on a clean end of file
}
kl, err := binary.ReadUvarint(r)
if err != nil {
return kv{}, io.ErrUnexpectedEOF
}
key := make([]byte, kl)
if _, err := io.ReadFull(r, key); err != nil {
return kv{}, io.ErrUnexpectedEOF
}
vl, err := binary.ReadUvarint(r)
if err != nil {
return kv{}, io.ErrUnexpectedEOF
}
val := make([]byte, vl)
if _, err := io.ReadFull(r, val); err != nil {
return kv{}, io.ErrUnexpectedEOF
}
return kv{key: string(key), value: val, tomb: kind == 1}, nil
}A bloom filter built on hash/fnv with double hashing:
package main
import "hash/fnv"
// Bloom answers "definitely not in this file" or "maybe in this file".
// A negative answer lets a lookup skip the file without any disk read.
type Bloom struct {
bits []uint64
k uint64
}
// NewBloom sizes the filter at about 10 bits per key with 7 hash functions,
// which gives roughly a 1% false-positive rate.
func NewBloom(keys int) *Bloom {
m := max(64, keys*10)
return &Bloom{bits: make([]uint64, (m+63)/64), k: 7}
}
// hashes derives k positions from one 64-bit FNV-1a hash (double hashing).
func (b *Bloom) hashes(key string) (uint64, uint64) {
h := fnv.New64a()
h.Write([]byte(key))
sum := h.Sum64()
return sum & 0xffffffff, sum>>32 | 1
}
func (b *Bloom) Add(key string) {
h1, h2 := b.hashes(key)
m := uint64(len(b.bits) * 64)
for i := range b.k {
pos := (h1 + i*h2) % m
b.bits[pos/64] |= 1 << (pos % 64)
}
}
func (b *Bloom) MayContain(key string) bool {
h1, h2 := b.hashes(key)
m := uint64(len(b.bits) * 64)
for i := range b.k {
pos := (h1 + i*h2) % m
if b.bits[pos/64]&(1<<(pos%64)) == 0 {
return false
}
}
return true
}SSTables written in one sequential pass with the same record encoding as the WAL, a sparse index of every 16th key, and a reload path for restarts:
package main
import (
"bufio"
"io"
"os"
"sort"
)
const indexEvery = 16 // one sparse-index entry per 16 records
type indexEntry struct {
key string
offset int64
}
// SSTable is an immutable file of records sorted by key (same encoding as
// the WAL, see encodeRecord).
// The sparse index and bloom filter live in memory here; real formats store
// them as blocks in the file footer.
type SSTable struct {
path string
size int64
index []indexEntry
bloom *Bloom
tombs int // tombstones in this file, for the lab output
}
// WriteSSTable streams sorted entries to a new file in one sequential pass.
func WriteSSTable(path string, entries []kv) (*SSTable, error) {
f, err := os.Create(path)
if err != nil {
return nil, err
}
defer f.Close()
w := bufio.NewWriter(f)
t := &SSTable{path: path, bloom: NewBloom(len(entries))}
var off int64
for i, e := range entries {
if i%indexEvery == 0 {
t.index = append(t.index, indexEntry{e.key, off})
}
t.bloom.Add(e.key)
if e.tomb {
t.tombs++
}
rec := encodeRecord(e)
if _, err := w.Write(rec); err != nil {
return nil, err
}
off += int64(len(rec))
}
t.size = off
if err := w.Flush(); err != nil {
return nil, err
}
return t, f.Sync()
}
// Get checks the bloom filter, binary-searches the sparse index and scans at
// most one index interval of the file. found=true with e.tomb=true means
// "deleted here": the caller must stop and not look in older files.
func (t *SSTable) Get(key string) (e kv, found bool, err error) {
if !t.bloom.MayContain(key) {
return kv{}, false, nil // no disk read at all
}
i := sort.Search(len(t.index), func(i int) bool { return t.index[i].key > key }) - 1
if i < 0 {
return kv{}, false, nil
}
f, err := os.Open(t.path)
if err != nil {
return kv{}, false, err
}
defer f.Close()
if _, err := f.Seek(t.index[i].offset, io.SeekStart); err != nil {
return kv{}, false, err
}
r := bufio.NewReader(f)
for range indexEvery {
e, err := readRecord(r)
if err == io.EOF || (err == nil && e.key > key) {
return kv{}, false, nil // bloom false positive: one wasted read
}
if err != nil {
return kv{}, false, err
}
if e.key == key {
return e, true, nil
}
}
return kv{}, false, nil
}
// All reads every record in order; compaction uses it.
func (t *SSTable) All() ([]kv, error) {
f, err := os.Open(t.path)
if err != nil {
return nil, err
}
defer f.Close()
r := bufio.NewReader(f)
var out []kv
for {
e, err := readRecord(r)
if err == io.EOF {
return out, nil
}
if err != nil {
return nil, err
}
out = append(out, e)
}
}
// LoadSSTable reopens an existing file after a restart and rebuilds the
// in-memory sparse index and bloom filter (real engines read them from the
// file's index and filter blocks instead of scanning the data).
func LoadSSTable(path string) (*SSTable, error) {
entries, err := (&SSTable{path: path}).All()
if err != nil {
return nil, err
}
t := &SSTable{path: path, bloom: NewBloom(len(entries))}
var off int64
for i, e := range entries {
if i%indexEvery == 0 {
t.index = append(t.index, indexEntry{e.key, off})
}
t.bloom.Add(e.key)
if e.tomb {
t.tombs++
}
off += int64(len(encodeRecord(e)))
}
t.size = off
return t, nil
}The database: WAL then memtable, flush on a size threshold, newest-first lookup that stops at a tombstone, and a naive size-tiered step that merges the two age-adjacent files with the smallest combined size. Tombstones are dropped only when the merge produces the oldest file, because anywhere else they still shadow older values. Its counters show write amplification directly: more bytes reach the WAL and files than were ever Put.
package main
import (
"fmt"
"os"
"path/filepath"
"sort"
)
// DB ties the pieces together. tables is ordered oldest first, so a lookup
// walks it backwards: the newest version of a key always wins.
type DB struct {
dir string
wal *WAL
mem *Memtable
tables []*SSTable
limit int // flush when the memtable holds this many bytes
nextFile int
walBytes int64 // bytes appended to the WAL
written int64 // bytes written to SSTables: flushes plus compactions
droppedTombs int // tombstones purged by compaction into the oldest file
}
// Open recovers whatever a previous process left: SSTables are reopened and
// the WAL is replayed into a fresh memtable.
func Open(dir string, memtableLimit int) (*DB, error) {
db := &DB{dir: dir, limit: memtableLimit}
paths, err := filepath.Glob(filepath.Join(dir, "*.sst"))
if err != nil {
return nil, err
}
sort.Strings(paths) // file numbers grow with age, so names sort oldest first
for _, p := range paths {
t, err := LoadSSTable(p)
if err != nil {
return nil, err
}
db.tables = append(db.tables, t)
db.nextFile++
}
if db.mem, err = ReplayWAL(db.walPath()); err != nil {
return nil, err
}
if db.wal, err = OpenWAL(db.walPath()); err != nil {
return nil, err
}
return db, nil
}
func (db *DB) walPath() string { return filepath.Join(db.dir, "wal.log") }
// Put appends to the WAL first, then updates the memtable. Both are cheap:
// one sequential append and one in-memory insert.
func (db *DB) Put(key string, value []byte) error {
return db.apply(kv{key: key, value: value})
}
// Delete writes a tombstone. The old value stays on disk until compaction
// merges the tombstone with it.
func (db *DB) Delete(key string) error {
return db.apply(kv{key: key, tomb: true})
}
func (db *DB) apply(e kv) error {
if err := db.wal.Append(e); err != nil {
return err
}
db.walBytes += int64(len(encodeRecord(e)))
db.mem.set(e)
if db.mem.bytes >= db.limit {
return db.Flush()
}
return nil
}
// Flush writes the memtable out as one new sorted file (sequential, no
// matter how random the keys were), then starts a new WAL: the old log's
// contents are now safely in the SSTable.
func (db *DB) Flush() error {
if len(db.mem.entries) == 0 {
return nil
}
t, err := db.write(db.mem.entries)
if err != nil {
return err
}
db.tables = append(db.tables, t)
db.mem = &Memtable{}
if err := db.wal.Close(); err != nil {
return err
}
if err := os.Remove(db.walPath()); err != nil {
return err
}
db.wal, err = OpenWAL(db.walPath())
return err
}
func (db *DB) write(entries []kv) (*SSTable, error) {
path := filepath.Join(db.dir, fmt.Sprintf("%06d.sst", db.nextFile))
db.nextFile++
t, err := WriteSSTable(path, entries)
if err == nil {
db.written += t.size
}
return t, err
}
// Get checks the memtable, then every file from newest to oldest. Each file
// it has to consult is read amplification; the bloom filter keeps most of
// those consultations in memory. A tombstone ends the search: deleted.
func (db *DB) Get(key string) ([]byte, bool, error) {
if e, ok := db.mem.Get(key); ok {
return e.value, !e.tomb, nil
}
for i := len(db.tables) - 1; i >= 0; i-- {
e, ok, err := db.tables[i].Get(key)
if err != nil {
return nil, false, err
}
if ok {
return e.value, !e.tomb, nil
}
}
return nil, false, nil
}
// CompactSmallestPair is a naive size-tiered step: merge the two adjacent
// files whose combined size is smallest. Adjacent means adjacent in age, so
// the merged file still sits in the right place in newest-first order.
func (db *DB) CompactSmallestPair() error {
if len(db.tables) < 2 {
return nil
}
best := 0
for i := 1; i < len(db.tables)-1; i++ {
if db.tables[i].size+db.tables[i+1].size < db.tables[best].size+db.tables[best+1].size {
best = i
}
}
older, newer := db.tables[best], db.tables[best+1]
a, err := older.All()
if err != nil {
return err
}
b, err := newer.All()
if err != nil {
return err
}
merged := mergeNewerWins(a, b)
if best == 0 {
// Nothing older exists, so a tombstone has nothing left to shadow
// and can finally be dropped. Anywhere else, dropping it would
// resurrect the value in an older file.
merged = db.dropTombstones(merged)
}
t, err := db.write(merged) // the bytes rewritten here are write amplification
if err != nil {
return err
}
db.tables = append(db.tables[:best], append([]*SSTable{t}, db.tables[best+2:]...)...)
// The old files stay on disk until the merge is done: space amplification.
os.Remove(older.path)
os.Remove(newer.path)
return nil
}
func (db *DB) dropTombstones(in []kv) []kv {
out := in[:0]
for _, e := range in {
if e.tomb {
db.droppedTombs++
continue
}
out = append(out, e)
}
return out
}
// mergeNewerWins is the merge step of merge sort over two sorted runs. When
// both runs hold a key, the newer run's entry (value or tombstone) survives
// and the older one is garbage-collected.
func mergeNewerWins(older, newer []kv) []kv {
out := make([]kv, 0, len(older)+len(newer))
i, j := 0, 0
for i < len(older) && j < len(newer) {
switch {
case older[i].key < newer[j].key:
out = append(out, older[i])
i++
case older[i].key > newer[j].key:
out = append(out, newer[j])
j++
default:
out = append(out, newer[j])
i++
j++
}
}
out = append(out, older[i:]...)
return append(out, newer[j:]...)
}
// Close flushes the WAL buffer; the memtable is left for replay on Open.
func (db *DB) Close() error { return db.wal.Close() }package main
import (
"flag"
"fmt"
"log"
"math/rand/v2"
"os"
"path/filepath"
)
func main() {
keep := flag.String("dir", "", "keep files in this directory instead of a temp dir")
flag.Parse()
dir := *keep
if dir == "" {
var err error
if dir, err = os.MkdirTemp("", "lsm"); err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
} else if err := os.MkdirAll(dir, 0o755); err != nil {
log.Fatal(err)
}
db, err := Open(dir, 64<<10) // 64 KB memtable
if err != nil {
log.Fatal(err)
}
// 1. Random writes with many overwrites: flushes create small files.
var logical int64
for i := range 50_000 {
key := fmt.Sprintf("user:%06d", rand.IntN(20_000))
val := fmt.Appendf(nil, "v%d", i)
logical += int64(len(key) + len(val))
must(db.Put(key, val))
}
must(db.Put("user:000042", []byte("latest")))
must(db.Flush())
list(dir, "after flushes")
// 2. Deletes are writes: 5,000 tombstones become a new file.
for i := range 5_000 {
must(db.Delete(fmt.Sprintf("user:%06d", 10_000+i)))
}
must(db.Flush())
list(dir, "after 5,000 deletes")
// 3. Compaction merges runs, drops shadowed values and old tombstones.
for len(db.tables) > 4 {
must(db.CompactSmallestPair())
}
for len(db.tables) > 1 {
must(db.CompactSmallestPair())
}
list(dir, "after compaction")
fmt.Printf("bytes put: %d, WAL bytes: %d, SSTable bytes written: %d (write amp ~%.1fx)\n",
logical, db.walBytes, db.written, float64(db.walBytes+db.written)/float64(logical))
fmt.Printf("tombstones dropped at the bottom: %d\n", db.droppedTombs)
// 4. Crash safety: unflushed writes live only in the memtable and the WAL.
must(db.Put("session:1", []byte("unflushed")))
must(db.Close()) // simulate a crash: no Flush
db, err = Open(dir, 64<<10)
if err != nil {
log.Fatal(err)
}
for _, k := range []string{"user:000042", "user:010001", "user:999999", "session:1"} {
v, ok, err := db.Get(k)
must(err)
fmt.Printf("get %s -> %q found=%v\n", k, v, ok)
}
must(db.Close())
}
// list prints the directory the way `ls -l` would, so the lab can watch
// files appear (flush) and disappear (compaction).
func list(dir, label string) {
paths, err := filepath.Glob(filepath.Join(dir, "*"))
must(err)
fmt.Printf("%s: %d files\n", label, len(paths))
for _, p := range paths {
st, err := os.Stat(p)
must(err)
fmt.Printf(" %-12s %8d bytes\n", filepath.Base(p), st.Size())
}
}
func must(err error) {
if err != nil {
log.Fatal(err)
}
}The Go angle
Go is unusual in having serious storage engines written in the language itself, so you can read one. Pebble is "a LevelDB/RocksDB inspired key-value store focused on performance and internal usage by CockroachDB"; it "inherits the RocksDB file formats and a few extensions such as range deletion". Badger is an LSM whose design follows the WiscKey paper (keys in the tree, values in a separate log), built to "Optimize for SSDs". bbolt, the etcd fork of Bolt, inspired by LMDB, is a single-file copy-on-write B+tree; its README draws the line plainly: if you need "a high random write throughput (>10,000 w/sec)" an LSM such as LevelDB "could be a good choice", and if the application "is read-heavy or does a lot of range scans then Bolt could be a good choice." RocksDB itself is reachable through cgo wrappers (linxGnu/grocksdb), which is why most Go services pick Pebble or Badger instead.
Against PostgreSQL or MySQL, database/sql and pgx never see the engine; the choice shows up only in the shape of the writes you send: batch with pgx.Batch or CopyFrom, keep keys monotonic, avoid read-modify-write loops on hot rows.
Laravel
Before
A view counter on the post row, incremented per request. On InnoDB every view is a locked in-place update of one clustered-index row: an undo record, a redo record and a dirty 16 KB page. At thousands of views per second on a popular post, requests queue on that one row lock.
<?php
// database/migrations/2026_01_01_000000_create_posts_table.php
// The view counter lives on the post row itself.
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('posts', function (Blueprint $table) {
$table->engine('InnoDB'); // clustered B+-tree on the primary key
$table->id();
$table->string('title');
$table->unsignedBigInteger('views')->default(0);
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('posts');
}
};<?php
// app/Http/Controllers/PostViewController.php
// Every page view updates the same row in place. On InnoDB that is, per view:
// an exclusive row lock, an undo record, a redo record and a dirtied 16 KB
// page. At 10k views/sec on one popular post, every request queues on the
// same row lock, and the "cheap" in-place update becomes the bottleneck.
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
final class PostViewController
{
public function __invoke(Post $post): Response
{
DB::table('posts')->where('id', $post->id)->increment('views');
return response()->noContent();
}
}After
The request path only appends to post_view_events, whose auto-increment key puts every insert on the right-most leaf, with no secondary index to scatter writes. A scheduled command folds a batch into posts.views with one increment per post and deletes exactly the ids it counted. The table is still an InnoDB B-tree; the pattern is LSM's, moved into the application: buffer appends, compact later.
<?php
// database/migrations/2026_01_02_000000_create_post_view_events_table.php
// Append-only log of views. The auto-increment primary key means every insert
// lands on the right-most leaf of the clustered B+-tree: a sequential write.
// There is deliberately no index (and no foreign key, which would add one) on
// post_id: a secondary index on a random column would bring random writes back.
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('post_view_events', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('post_id');
$table->timestamp('created_at')->useCurrent();
});
}
public function down(): void
{
Schema::dropIfExists('post_view_events');
}
};<?php
// app/Http/Controllers/PostViewController.php
// The request path only appends. No row is shared between requests, so there
// is no lock to queue on. This is the LSM idea applied at the application
// level: buffer writes as an append-only log, fold them in later in batches.
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
final class PostViewController
{
public function __invoke(Post $post): Response
{
DB::table('post_view_events')->insert(['post_id' => $post->id]);
return response()->noContent();
}
}
// app/Console/Commands/AggregatePostViews.php
// The "compaction" step: read a batch of events in key order, apply one
// increment per post, delete exactly the events that were counted.
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
final class AggregatePostViews extends Command
{
protected $signature = 'posts:aggregate-views {--batch=5000}';
protected $description = 'Fold post view events into posts.views';
public function handle(): int
{
$batch = (int) $this->option('batch');
do {
$processed = DB::transaction(function () use ($batch): int {
$events = DB::table('post_view_events')
->orderBy('id')
->limit($batch)
->get(['id', 'post_id']);
if ($events->isEmpty()) {
return 0;
}
// One UPDATE per post per batch instead of one per view.
$perPost = $events->countBy(fn (object $event) => $event->post_id);
foreach ($perPost as $postId => $count) {
DB::table('posts')->where('id', $postId)->increment('views', $count);
}
// Delete by the exact ids we counted, not by "id <= max": an event
// that commits late with a lower id is simply picked up next run.
DB::table('post_view_events')
->whereIn('id', $events->pluck('id')->all())
->delete();
return $events->count();
});
} while ($processed > 0);
return self::SUCCESS;
}
}
// routes/console.php — one aggregator at a time, on one server, so no event
// can be counted twice. Both guards use a cache lock: withoutOverlapping and
// onOneServer need a shared cache store (database, memcached, dynamodb or
// redis), not the per-machine file store.
//
// use Illuminate\Support\Facades\Schedule;
//
// Schedule::command('posts:aggregate-views')
// ->everyMinute()
// ->withoutOverlapping()
// ->onOneServer();Choosing the engine per connection: Laravel's MySQL schema grammar appends engine = … from the connection's engine key, and $table->engine('InnoDB') overrides it per table. ROCKSDB works only against a server built with MyRocks.
<?php
// config/database.php (excerpt). The per-connection 'engine' key is appended
// as ENGINE=... to every CREATE TABLE that Laravel's schema builder emits on
// MySQL and MariaDB. A migration can override it with $table->engine(...).
return [
'connections' => [
// OLTP tables: InnoDB, a clustered B+-tree. null means "server default",
// which is InnoDB on MySQL 8.4.
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'strict' => true,
'engine' => null,
],
// Write-heavy, append-mostly tables on an LSM engine. ROCKSDB only works
// on a server built with the MyRocks storage engine (check SHOW ENGINES);
// stock MySQL 8.4 does not ship it, and CREATE TABLE will fail there.
'events' => [
'driver' => 'mysql',
'host' => env('EVENTS_DB_HOST', '127.0.0.1'),
'port' => env('EVENTS_DB_PORT', '3306'),
'database' => env('EVENTS_DB_DATABASE', 'events'),
'username' => env('EVENTS_DB_USERNAME', 'root'),
'password' => env('EVENTS_DB_PASSWORD', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_bin',
'strict' => true,
'engine' => 'ROCKSDB',
],
],
];The Laravel angle
The migration docs say $table->engine(...) "may be used to specify the table's storage engine when using MariaDB or MySQL"; Laravel's PostgreSQL grammar has no such option. The rest of the decision is in your write pattern: DB::table(...)->insert() of many rows at once, increment() in batches, Schedule::command(...)->withoutOverlapping()->onOneServer() for the compaction job, and partition drops instead of mass DELETE for retention.
The cache layer is a small storage-engine choice too. The file cache store writes each key to its own file under storage_path('framework/cache/data') (the path is a SHA-1 of the key) and leaves the layout to the filesystem; FileStore::increment reads the payload, adds, and puts it back, which is not atomic across concurrent requests. The redis store keeps keys in memory and makes INCR atomic on the server. For a hot counter, Redis plus periodic flush to the database is the usual pattern; see Redis.
In production systems
- PostgreSQL: heap tables plus B-tree indexes on 8 kB pages; the B-tree implementation "incrementally delete[s] version churn index tuples by performing bottom-up index deletion passes" to delay page splits caused by MVCC versions.
- MySQL InnoDB vs MyRocks: InnoDB is a clustered B+tree on 16 KB pages; MyRocks puts RocksDB under the same handler API and claims "10x less write amplification compared to InnoDB".
- MongoDB: WiredTiger is a B-tree engine with MVCC; "The new checkpoint becomes accessible and permanent when WiredTiger's metadata table is atomically updated to reference the new checkpoint", and "If MongoDB exits between checkpoints, it uses the journal to replay all data modified since the last checkpoint."
- Distributed SQL: TiKV runs two RocksDB instances per node (raftdb and kvdb); CockroachDB stores data in Pebble. See Distributed SQL & Consensus.
In architecture: from a single process to a distributed system
The storage engine is the lowest layer of every data decision. The higher you go, the less you choose it directly and the more you choose it through the products you adopt.
Monolith: one process, one database
One PostgreSQL or MySQL database with B-tree tables serves everything. The storage engine shows up as key design and write shape. Example: a shop's orders table with a bigint identity key and four secondary indexes handles 500 inserts/s easily; the same table keyed by UUIDv4 with ten indexes starts to fall behind when the indexes no longer fit in the buffer pool. The simplest correct usage: monotonic keys, only the indexes you query, batch inserts in background jobs, partitions for anything with retention.
Modular monolith and multiple databases
Modules own their tables, and sometimes their database. This is where a second engine first appears legitimately: the catalog module stays on PostgreSQL, the tracking module that ingests 20,000 click events per second writes to a MyRocks table (same MySQL server, different engine) or to its own ClickHouse/Cassandra store. Rule: one module owns each store, so the engine choice and its knobs (compaction style, retention) are that module's decision and its runbook.
Microservices
Each service picks the engine that fits its access pattern, and nothing about one engine's guarantees crosses a service boundary. Example flow for an IoT platform:
device -> ingest-svc -> Kafka topic readings -> metrics-svc -> Cassandra (TWCS, TTL 90 d)
-> alerts-svc -> PostgreSQL (alerts, B-tree)
1 ingest-svc validates and produces to Kafka (Kafka itself is an append-only log on disk)
2 metrics-svc batches 500 readings per partition, writes with consistency LOCAL_QUORUM
3 alerts-svc reads the same events and inserts only threshold breaches into PostgreSQL
4 dashboards query metrics-svc by (device_id, day); old days expire by window, no deletes
5 a replay from Kafka rebuilds either store, because each write is idempotent by (device, ts)The storage lesson: idempotent keys (device_id, ts) make LSM upserts natural (a rewrite is just a newer version), and expiry by TTL keeps tombstones out of the read path.
Distributed data: replicas, caches and distributed SQL
Replication copies the engine's work: a PostgreSQL physical replica replays the same WAL and does the same page writes; a Cassandra replica runs its own compaction, so compaction debt can differ per node and a lagging node serves slower reads. In TiKV and CockroachDB, Raft log entries are themselves written to an LSM (raftdb in TiKV), so each write passes through two logs before it lands in the data LSM; range deletes make dropping a table or moving a range cheap. A cache tier (Redis) in front of an LSM hides its read amplification for hot keys but not for scans. Cross-region, space amplification is multiplied by the replication factor: 3 replicas × 2× STCS headroom is 6× the live data in raw disk.
Scaling path: 1×, 10×, 100×
| Load | Typical shape | Storage-engine move |
|---|---|---|
| 1× (hundreds of writes/s) | One PostgreSQL/MySQL | Monotonic keys, right indexes, nothing else |
| 10× (thousands/s, hot tables) | Same DB, a few hot tables | Batch writes, partitions for retention, fillfactor, maybe MyRocks or an append-and-fold table |
| 100× (tens of thousands/s, TB-scale) | Separate stores per access pattern | LSM where writes dominate (Cassandra/ScyllaDB TWCS, RocksDB-based TiKV, CockroachDB); B-tree stays for read-heavy OLTP; compaction and stall monitoring become on-call items |
Lab
Four experiments: watch a teaching LSM create and merge files, measure heap vs clustered table sizes under two key patterns, and inspect a real RocksDB with ldb and sst_dump.
Experiment 1: the teaching LSM. From the snippet's module root:
cd docs/snippets/database/storage-engines/go
go run ./after -dir /tmp/lsm-lab
# after flushes: 14 files <- 13 SSTables of ~73 KB + wal.log (empty right after a flush)
# after 5,000 deletes: 15 files <- deletes are writes: a new 70 KB file of tombstones
# after compaction: 2 files <- one SSTable left; tombstones and old versions gone
# bytes put: 838890, WAL bytes: 1058910, SSTable bytes written: ~3300000 (write amp ~5.2x)
# tombstones dropped at the bottom: 5000
# get user:000042 -> "latest" found=true
# get user:010001 -> "" found=false <- deleted
# get session:1 -> "unflushed" found=true <- recovered from wal.log after the simulated crash
ls -l /tmp/lsm-lab # 000026.sst and wal.logThings to try: change 64<<10 (the memtable size) to 16<<10 and watch the file count and write amplification rise; comment out the compaction loops and see Get consult more files; delete wal.log between the crash and the reopen and see session:1 disappear.
Experiment 2: heap vs clustered under two key patterns. Start both servers:
docker run -d --name pg -e POSTGRES_PASSWORD=pg -p 5432:5432 postgres:17
docker run -d --name my -e MYSQL_ROOT_PASSWORD=my -e MYSQL_DATABASE=lab -p 3306:3306 mysql:8.4PostgreSQL (docker exec -it pg psql -U postgres):
CREATE TABLE seq_t (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, pad text);
CREATE TABLE rand_t (id uuid PRIMARY KEY, pad text);
INSERT INTO seq_t (pad) SELECT repeat('x', 100) FROM generate_series(1, 1000000);
INSERT INTO rand_t (id, pad) SELECT gen_random_uuid(), repeat('x', 100) FROM generate_series(1, 1000000);
SELECT relname,
pg_size_pretty(pg_relation_size(oid)) AS heap,
pg_size_pretty(pg_indexes_size(oid)) AS indexes
FROM pg_class WHERE relname IN ('seq_t', 'rand_t');
-- Expect: heaps of similar size (rows are appended in both cases).
-- The uuid PK index is noticeably larger than the bigint one: wider keys and
-- random-insert splits leave its leaves about 70% full instead of ~90%.MySQL (docker exec -it my mysql -uroot -pmy lab):
SET SESSION cte_max_recursion_depth = 1000000;
CREATE TABLE seq_t (id BIGINT AUTO_INCREMENT PRIMARY KEY, pad VARCHAR(100)) ENGINE=InnoDB;
CREATE TABLE rand_t (id BINARY(16) PRIMARY KEY, pad VARCHAR(100)) ENGINE=InnoDB;
INSERT INTO seq_t (pad)
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 1000000)
SELECT REPEAT('x', 100) FROM n;
INSERT INTO rand_t (id, pad)
WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 1000000)
SELECT UUID_TO_BIN(UUID()), REPEAT('x', 100) FROM n; -- UUIDv1 bytes, unswapped: scattered order
ANALYZE TABLE seq_t, rand_t;
SELECT table_name, data_length, index_length
FROM information_schema.tables WHERE table_schema = 'lab';
-- Expect: rand_t's data_length clearly larger than seq_t's: in InnoDB the ROWS
-- live in the PK tree, so random keys fragment the table itself, not just an index.
-- Then compare: INSERT ... SELECT UUID_TO_BIN(UUID(), 1) (swap flag = time-ordered).Note the difference: in PostgreSQL the random key hurts one index; in InnoDB it hurts the table. Record your numbers; they depend on version and page fill, the direction does not.
Experiment 3: watch page splits in PostgreSQL (needs CREATE EXTENSION pageinspect;):
CREATE EXTENSION IF NOT EXISTS pageinspect;
SELECT * FROM bt_metap('rand_t_pkey'); -- root block, levels
SELECT avg(avg_item_size), avg(free_size) FROM (
SELECT (bt_page_stats('rand_t_pkey', b)).* FROM generate_series(1, 200) b) s;
-- Repeat for seq_t_pkey: much less free space per leaf.Experiment 4: a real RocksDB with ldb and sst_dump. If you have RocksDB tools (brew install rocksdb installs rocksdb_ldb and rocksdb_sst_dump; source builds produce ldb and sst_dump), the wiki's commands are:
ldb --db=/tmp/test_db --create_if_missing put a1 b1
ldb --db=/tmp/test_db get a1
ldb --db=/tmp/test_db batchput a3 b3 a4 b4
ldb --db=/tmp/test_db scan
ldb --db=/tmp/test_db dump --hex > /tmp/dbdump
ldb --db=/tmp/test_db compact # manual full compaction
sst_dump --file=/tmp/test_db --command=scan --read_num=5
sst_dump --file=/tmp/test_db/000829.sst --show_properties # entries, deletions, index/filter sizes
ls -l /tmp/test_db # *.sst, *.log (WAL), MANIFEST-*, CURRENT, OPTIONS-*, LOG
grep -i stall /tmp/test_db/LOGldb opens the DB offline by default ("By default, ldb can only used against a DB that is offline"); use --secondary_path=<dir> to look at a running one. --show_properties prints the table properties block: number of entries and deletions (tombstones), data, index and filter block sizes.
Common misconceptions
| Belief | Reality |
|---|---|
| LSM writes fewer bytes than a B-tree | It writes sequentially; leveled compaction can rewrite each value many times. The gain is I/O shape and no page-sized rewrites |
| LSM reads are always slow | Point reads with bloom filters and cache touch about one block; scans and compaction debt are the slow cases |
| Deleting data frees space immediately | LSM deletes add tombstones; PostgreSQL leaves dead tuples; space returns after compaction / VACUUM |
| Compaction is optional maintenance | It is the write path's second half; stop it and writes stall |
| Write stalls mean the disk is failing | They are deliberate throttling when flush or compaction falls behind |
| SSDs make random writes free | They make random reads cheap; random small writes cost FTL garbage collection and wear |
| PostgreSQL and InnoDB store tables the same way | PostgreSQL: heap + indexes pointing to ctid; InnoDB: rows inside the PK B+tree |
| A bloom filter tells you where a key is | It only says "definitely not" or "maybe" |
| TWCS fits any timestamped table | Only time-ordered, TTL-expiring data without updates to old rows |
| Size-tiered is the safe default | It needs up to 2× free space and lets read amplification grow |
| An append-only MySQL table is an LSM | It is still a B+tree; you copied the pattern and own the compaction job |
| WiredTiger is an LSM engine | MongoDB uses its B-tree; its LSM is documented as experimental |
| A short benchmark settles B-tree vs LSM | Steady state takes hours; most short benchmarks measure an empty LSM |
Cheat sheet
| Topic | Remember |
|---|---|
| Storage engine | The layer under SQL that owns pages/files, caching, logging; MySQL handler API, PostgreSQL table AM |
| B+tree | One home per key; in-place page updates; splits; best reads |
| LSM write path | WAL → memtable → immutable memtable → flush to L0 SST → compaction down the levels |
| LSM read path | Memtables → L0 newest first → one file per level; bloom → index block → data block (block cache) |
| Amplifications | Write (bytes written / bytes put), read (places checked), space (disk / live); RUM: pick two |
| Leveled | Low read/space amp, high write amp; RocksDB default, Cassandra LCS |
| Size-tiered / universal | Low write amp, high read/space amp; Cassandra STCS default, RocksDB Universal |
| TWCS / FIFO | Time-series with TTL / logs; expire whole files |
| Tombstones | Deletes are writes; purged at the bottom level after gc_grace_seconds (Cassandra) |
| Write stalls | Too many memtables, L0 files (20/36), pending compaction bytes (64/256 GB) |
| First RocksDB knobs | write_buffer_size 64 MB, max_write_buffer_number 2, level0_file_num_compaction_trigger 4, target_file_size_base 64 MB, max_bytes_for_level_base 256 MB |
| SSD | LSM's sequential files and whole-file deletes fit flash; random small writes cost wear |
| Copy-on-write B-tree | LMDB/bbolt: no WAL, one writer, lock-free readers |
| PostgreSQL vs InnoDB | Heap + ctid indexes vs clustered PK; random PKs hurt InnoDB tables, PostgreSQL indexes |
| Products | TiKV = RocksDB, CockroachDB = Pebble, MongoDB = WiredTiger B-tree, Redis = RAM + RDB/AOF |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why does a 100-byte update in InnoDB cost more than 100 bytes of I/O? Important
Answer
Answer: The redo record is written at commit, and later the whole 16 KB page is written back (twice with the doublewrite buffer); a split writes more pages.
2 — What two places does every RocksDB write go to, and why both? Important
Answer
Answer: The WAL on disk and the memtable in memory. The memtable makes it readable and sortable; the WAL makes it survive a crash until the memtable is flushed.
3 — Name the three blocks a point lookup touches inside one SSTable in the best case and what each does. Good to know
Answer
Answer: Filter block (bloom: maybe/definitely not), index block (which data block), one data block (the key). Filter and index are usually cached.
4 — Which compaction style would you pick for a 90-day-TTL sensor table in Cassandra, and with what window? Good to know
Answer
Answer: TWCS with about 20-30 windows: a 3-day window (compaction_window_unit: DAYS, compaction_window_size: 3).
5 — Why can't an LSM drop a tombstone as soon as it is compacted once? Important
Answer
Answer: Older versions may still exist in lower levels; dropping the tombstone would resurrect them. It can be dropped only at the bottom level (and, in Cassandra, after gc_grace_seconds so all replicas saw it).
6 — RocksDB logs "Stalling writes because we have 20 level-0 files". What are two fixes? Important
Answer
Answer: Increase compaction throughput (max_background_jobs, subcompactions), make L0→L1 balanced (max_bytes_for_level_base ≈ L0 size), use bigger memtables to reduce write amp, or temporarily raise the triggers.
7 — What does the RUM conjecture say, and where do bloom filters sit in it? Good to know
Answer
Answer: Bounding two of read, update and memory overhead forces a lower bound on the third. Bloom filters spend memory to reduce read overhead.
8 — Why does a random UUID primary key hurt InnoDB more than PostgreSQL? Important
Answer
Answer: InnoDB stores rows in the PK B+tree, so random keys fragment the table itself; PostgreSQL appends rows to the heap and only the PK index fragments.
9 — How does LMDB recover after a crash without a WAL? Good to know
Answer
Answer: Copy-on-write: no active page is ever overwritten; a commit switches the root in the meta page atomically, so the last committed root is always consistent.
10 — A benchmark shows an LSM beating a B-tree by 5× on inserts after 3 minutes. What do you ask? Important
Answer
Answer: Did it reach steady-state compaction? Does the data exceed cache? Same durability and compression? What are p99 latency, bytes written and disk used over hours?
11 — What do Redis RDB and AOF correspond to in disk-engine terms? Important
Answer
Answer: RDB is a periodic snapshot (like a checkpoint); AOF is a write-ahead log replayed on restart and compacted by a rewrite. There are no data pages: the data lives in RAM.
Glossary
| Term | Meaning |
|---|---|
| Storage engine | Layer that stores and retrieves data on disk below the query layer |
| Handler API | MySQL's C++ interface between the SQL layer and a pluggable engine |
| Table access method | PostgreSQL's interface (pg_am, TableAmRoutine) for table storage; heap is built in |
| Page / block | Fixed-size unit of I/O and caching (8 kB PostgreSQL, 16 KB InnoDB, 4 KB RocksDB data block) |
| Buffer pool | In-memory page cache (shared_buffers, InnoDB buffer pool) |
| Dirty page | Page changed in memory and not yet written to disk |
| Checkpoint | Point where dirty pages are written so recovery can start there |
| B+tree | Balanced tree with all keys in linked leaves; internal nodes route |
| Fan-out | Children per internal node; sets tree height |
| Page split | Moving part of a full page to a new page and adding a parent downlink |
| Fill factor | Percentage of a page filled at build/insert time (fillfactor, innodb_fill_factor) |
| Clustered index | Index whose leaves store the rows (InnoDB PK, SQL Server clustered, Oracle IOT) |
| Heap | Unordered row storage addressed by physical location (ctid) |
| HOT update | PostgreSQL heap-only tuple: new version on the same page, no index writes |
| Doublewrite buffer | InnoDB copy of pages written before in-place write, for torn-page safety |
| LSM-tree | Log-structured merge tree: buffer in memory, write sorted immutable files, merge later |
| Memtable | Sorted in-memory write buffer of an LSM (skip list in RocksDB) |
| Immutable memtable | Frozen memtable waiting to be flushed |
| Flush | Writing an immutable memtable to a new L0 SSTable |
| WAL | Write-ahead log; makes the memtable (or dirty pages) durable |
| SSTable / SST | Sorted string table: immutable sorted file of key-value pairs |
| Data block | Chunk of sorted entries inside an SST (default 4 KB in RocksDB) |
| Index block | Map from last key of each data block to its offset |
| Filter block | Bloom filter for the keys of an SST |
| Footer / metaindex | Fixed tail of an SST pointing to index and meta blocks |
| Sorted run | Set of files holding each key at most once in order |
| Level (L0, L1…) | Tier of SSTs; L0 overlapping, L1+ one sorted run each, ~10× growth |
| Compaction | Background merge of sorted runs that removes obsolete versions and tombstones |
| Leveled compaction | Merge a file into overlapping files of the next level (LCS, RocksDB Level) |
| Size-tiered compaction | Merge several similar-size runs (STCS) |
| Universal compaction | RocksDB's tiered style |
| UCS | Cassandra 5.0 Unified Compaction Strategy, tiered-to-leveled by scaling_parameters |
| TWCS | Time-window compaction strategy for TTL time series |
| FIFO compaction | Delete oldest files over a size or age limit; never merge |
| MANIFEST | RocksDB/LevelDB log of which files form the current version |
| Sequence number | Monotonic number on each write; newest version wins |
| Merge iterator | Iterator that merges sorted inputs from all levels |
| Bloom filter | Bit array answering "definitely not" or "maybe" for set membership |
| False positive | Bloom "maybe" for a key that is absent; costs one wasted read |
| Block cache | RocksDB cache of uncompressed blocks |
| Tombstone | Delete marker that shadows older values until compacted away |
| Range tombstone | One marker deleting a key range (DeleteRange) |
gc_grace_seconds | Cassandra minimum tombstone age before purge (default 10 days) |
| Zombie data | Deleted data resurrected because a replica missed the tombstone |
| Compaction debt | Work compaction is behind on (L0 files, pending bytes) |
| Write stall | Throttling or stopping writes when flush/compaction cannot keep up |
| Write amplification | Bytes written to storage per byte written by the application |
| Read amplification | Places (pages, files) checked per lookup |
| Space amplification | Disk bytes per byte of live data |
| RUM conjecture | Read, update, memory: bounding two bounds the third from below |
| FTL | Flash translation layer: SSD firmware mapping logical to physical pages |
| Erase block | Smallest unit a flash chip can erase (many pages) |
| Wear / endurance | Limited program/erase cycles of flash; TBW rating |
| TRIM / discard | Telling the SSD which blocks are free |
| Copy-on-write B-tree | B-tree that writes new copies of changed pages up to a new root (LMDB, bbolt) |
| Bε-tree / fractal tree | B-tree with buffers in internal nodes that batch writes (TokuDB, PerconaFT) |
| WiscKey / key-value separation | Keys in the LSM, values in a separate log (Badger, RocksDB BlobDB, TiKV Titan) |
| MyRocks | RocksDB as a MySQL storage engine |
| WiredTiger | MongoDB's default engine: B-tree, MVCC, checkpoints + journal |
| Pebble | Go LSM engine used by CockroachDB |
| TiKV | Distributed KV store of TiDB, built on RocksDB |
| RDB / AOF | Redis snapshot file / append-only command log |
appendfsync | Redis AOF fsync policy: always, everysec, no |
ldb / sst_dump | RocksDB admin tools for a DB directory / a single SST file |
db_bench, YCSB, sysbench | Benchmark tools for RocksDB, any KV store, MySQL/PostgreSQL |
References
- P. O'Neil, E. Cheng, D. Gawlick, E. O'Neil, "The Log-Structured Merge-Tree (LSM-Tree)", Acta Informatica 33(4):351–385, 1996. PDF
- D. Comer, "The Ubiquitous B-Tree", ACM Computing Surveys 11(2), June 1979. PDF
- M. Athanassoulis et al., "Designing Access Methods: The RUM Conjecture", EDBT 2016. PDF
- M. A. Bender et al., "An Introduction to Bε-trees and Write-Optimization", ;login: 40(5), October 2015. PDF
- RocksDB Wiki: RocksDB Overview, Compaction, Leveled Compaction, Universal Compaction, FIFO compaction style, RocksDB Bloom Filter, Write Ahead Log (WAL), Write Stalls, DeleteRange, BlockBasedTable Format, Block Cache, Setup Options and Basic Tuning, Administration and Data Access Tool
- RocksDB source: options.h, advanced_options.h, table.h
- LevelDB: Implementation notes
- PostgreSQL documentation: Database Page Layout, B-Tree Indexes, Table Access Method Interface Definition
- MySQL 8.4 Reference Manual: Alternative Storage Engines, Clustered and Secondary Indexes, InnoDB Startup Options and System Variables
- MyRocks: facebook/mysql-5.6 wiki, myrocks.io
- MongoDB: WiredTiger Storage Engine; WiredTiger: Architecture guide, Checkpoint, Log-Structured Merge Trees
- Apache Cassandra: Compaction overview, STCS, LCS, TWCS, UCS; ScyllaDB: Compaction strategies; Apache HBase Reference Guide
- TiKV: RocksDB; PingCAP: RocksDB Overview
- Redis: Persistence
- Pebble, LMDB, bbolt, Badger
- laravel/framework FileStore.php, MySqlGrammar; laravel/laravel config/cache.php, config/database.php
- Laravel 13 documentation: Migrations, Queries, Task Scheduling, Cache, Rate Limiting