Skip to content

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 forGo to
The tables to memoriseEverything in one minute
Why two designs exist and the trade-offWhy storage engines differ
Bayer & McCreight, Comer, O'Neil, LevelDB, RocksDBWhere it comes from
Handler API, pages, buffer pool, B+tree update pathB-tree side
Write, read and space amplification, RUMThe three amplifications
Memtable, WAL, SSTable, bloom filter, block cacheLSM side
Leveled, size-tiered, universal, TWCS, FIFOCompaction
Tombstones, range deletes, write stallsDeletes and debt
SSD, copy-on-write B-trees, Bε-trees, heap vs clusteredOther designs and hardware
PostgreSQL, InnoDB, MyRocks, WiredTiger, Cassandra, TiKV, CockroachDB, RedisWhat each product really does
RocksDB and Cassandra knobs, stall messagesMechanics and knobs
Picking an engine, write bursts, tombstone stormsSolving the classic problems
Benchmarks that lieBenchmarking pitfalls
Workload → engine tableChoosing an engine
Monolith to distributed SQLIn architecture
Teaching LSM, heap vs clustered sizes, ldbLab
Wrong beliefs, summary, termsMisconceptions, 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 doesFind the leaf page, change it, write the whole page back laterAppend to WAL, insert into memtable; flush a sorted file later
A point read doesRoot-to-leaf walk: 3-4 pages, upper levels cachedMemtable, then files newest first; bloom filters skip most files
A range scan doesWalk linked leaves in orderMerge an iterator over every level
A delete doesRemoves the entry (PostgreSQL marks the tuple dead for VACUUM)Writes a tombstone; space returns only after compaction
Background workCheckpoints, page splits, VACUUM / purgeFlushes and compaction, forever
Wins atRead-heavy OLTP, predictable latencyWrite-heavy ingest, compression, flash endurance
ProductsPostgreSQL, InnoDB, SQL Server, Oracle, SQLite, WiredTiger, LMDB, bboltRocksDB, LevelDB, Pebble, MyRocks, Cassandra, ScyllaDB, HBase, TiKV, Badger

The three costs.

CostPlain wordsB+treeLeveled LSMSize-tiered LSM
Write amplificationBytes the device writes per byte you wroteHigh for small random updates (a whole page per change)Medium to high (rewrite at every level)Lowest
Read amplificationPages or files touched per lookupLowestLow with bloom filtersHigher (more runs)
Space amplificationDisk bytes per live byteFragmentation, half-empty pagesLowest (~1.1×)Up to ~2× during merges

The knobs that matter first.

ProductKnobDefaultWhat it moves
RocksDBwrite_buffer_size64 MBMemtable size: bigger = fewer, larger L0 files
RocksDBmax_write_buffer_number2Memtables allowed before writes stop
RocksDBlevel0_file_num_compaction_trigger4L0 files that start L0→L1 compaction
RocksDBtarget_file_size_base64 MBSST size at L1
RocksDBcompaction_stylekCompactionStyleLevelLeveled vs universal vs FIFO
Cassandracompaction classSTCS (UCS recommended for new tables)Compaction strategy per table
Cassandragc_grace_secondstable propertyHow long tombstones must live
PostgreSQLfillfactor100 heap, 90 B-treeFree space left in pages for updates
InnoDBinnodb_page_size / innodb_fill_factor16384 / 100Page size, free space at index build
MongoDB WiredTigercheckpoint interval60 sHow much journal recovery replays
UPDATE / INSERTkey = 4711Buffer pool (shared_buffers / InnoDB buffer pool)rootinternalinternalleafleaf (dirty)changed in placenew leafpage splitleaf1 log the change first · 2 descend root to leaf (3-4 pages, upper levels cached) · 3 modify the leaf in place, mark it dirty4 a full leaf splits: half its keys move to a new page, the parent gets a new downlink · 5 checkpoint writes whole pages backWAL / redo log1 append record,fsync at COMMITData file: fixed-size pages (8 kB PostgreSQL, 16 KB InnoDB)at fixed offsets; a page is rewritten where it lives5 checkpoint /writeback: wholepage, random I/O

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 thereA key may exist in several files; the newest wins
Random writes; each dirty page is written wholeSequential 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 splitsBackground cost: compaction, which never ends
Latency predictable; write throughput bounded by random I/OWrite 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 ​

  1. "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.
  2. "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.
  3. "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 with ENGINE= per table.
  • PostgreSQL: the table access method interface, which "manage[s] the storage for tables". Each method is a row in pg_am whose handler returns a TableAmRoutine; heap is 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.
text
     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 row

Real 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.

ProductBoundaryHow you choose
MySQL / MariaDBhandler API, pluggable enginesENGINE=InnoDB / ENGINE=ROCKSDB per table
PostgreSQLtable access method (pg_am), index AMCREATE TABLE ... USING heap (default)
MongoDBstorage engine API--storageEngine wiredTiger (default)
CockroachDB, TiKV, etcdembedded KV libraryBuilt in: Pebble, RocksDB, bbolt
SQL Server, Oracle, SQLitesingle built-in engineTable options (clustered index, IOT, WITHOUT ROWID)

Fix / how to use it: check the engine before tuning anything.

sql
-- 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.

text
     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).

text
     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 place

Real 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.

ProductPageSplit / space knob
PostgreSQL B-tree8 kBfillfactor (index default 90, heap 100); deduplication and bottom-up deletion delay splits
InnoDB16 KB (innodb_page_size)innodb_fill_factor (default 100) at index build; MERGE_THRESHOLD for merges
SQL Server8 KBFILLFACTOR, PAD_INDEX
OracleDB_BLOCK_SIZE (8 KB typical)PCTFREE
SQLitepage_size (4096 default)VACUUM to repack
WiredTigervariable in-memory pages, reconciled on writeleaf_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".

text
     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 checkpoint

Real 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

DesignOptimisesPays with
B+treeReadsUpdates (random page writes), some space
Leveled LSMSpace, reads (vs tiered)Writes (compaction)
Size-tiered / universal LSMWritesReads and space
FIFO / TWCSWrites and space for TTL dataReads across files; only works for time-ordered data
Hash index (Bitcask, Redis dict)Point reads and updatesMemory (all keys in RAM), no range scans
Bloom filtersReadsMemory (~10 bits per key for ~1% false positives)

The LSM side: memtable, WAL, SSTables, filters and cache ​

Put / Deleteclient writeMemoryactive memtableskip list, sortedimmutable memtablefrozen, waiting to flush21bWAL1a sequential appenddeleted afterits memtable flushesDiskL0overlappingnew SST3 flush: one sequential writeL11 sorted runa..fg..pq..z4 compaction L0→L1 when L0 files ≥level0_file_num_compaction_trigger (4)5 compaction L1→L2 when L1 > target sizeL2~10× L1files range-partitioned by key; each level one sorted run… Ln: the last level holds ~90% of the dataCompaction: merge-sort inputs, keep the newest version of each key, drop shadowed values andtombstones that reached the bottom; write new files, then delete the inputs (old files are never edited).

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.

text
     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 resume

Real 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.

text
     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 deleted

Fix: 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).

text
     <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.

text
     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 memory

Fix: 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.

Get(key)memtableimmutablememtable(s)L0 fileseach, newest firstL1 … Lnone file per levelfirst value ortombstone winsbloom filterin memoryindex blockkey → data blockblock cacheuncompressed blocksmiss: 1 disk readof one data block (4-16 KB)"maybe" → look further"definitely not here" → skip the file, 0 I/OOne SSTable (RocksDB BlockBasedTable)data block 1data block 2…data block Nfilter block (bloom)index blockmetaindex + footersorted keys, prefix-compressed, ~4 KBeach; filter and indexare usually cachedRange scans cannot use the bloom filter: they merge an iterator over every level.

Compaction: leveled, size-tiered, universal, TWCS, FIFO ​

LeveledRocksDB default, Cassandra LCSSize-tiered / UniversalSTCS, RocksDB UniversalTime-window (TWCS)Cassandra, ScyllaDBFIFORocksDB FIFOL0L1: one sorted runL2 ≈ 10× L14 similar runs mergeexpiredwindoww1w2w3 (current)oldest file deletedwhen total > limitWrite amp: highRead amp: lowSpace amp: low (~1.1×)Best: reads, updates,deletes, tight disksWrite amp: lowRead amp: higherSpace amp: up to ~2×Best: write-heavy,bulk ingestWrite amp: lowReads: few windowsSpace: freed per windowBest: time series withTTL, append-onlyWrite amp: 1 (+ WAL)Reads: every fileSpace: cappedBest: logs, caches;drops data silently

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)".

text
     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 4

Leveled 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.

StrategyProductsWrite ampRead ampSpace ampTrigger knobs
LeveledRocksDB kCompactionStyleLevel (default), LevelDB, Pebble, Cassandra/ScyllaDB LCSHighLow~1.1×level0_file_num_compaction_trigger, max_bytes_for_level_base, sstable_size_in_mb (LCS, 160 MB)
Size-tiered / universalCassandra/ScyllaDB STCS, RocksDB kCompactionStyleUniversal, HBase (exploring)LowHigherUp to ~2×min_threshold (4), size_ratio, max_size_amplification_percent
Unified (UCS)Cassandra 5.0TunableTunableTunablescaling_parameters
Incremental (ICS)ScyllaDB EnterpriseLowMediumLower than STCSsstable_size_in_mb
Time-windowCassandra/ScyllaDB TWCSLowFew windowsFreed per windowcompaction_window_unit, compaction_window_size
FIFORocksDB kCompactionStyleFIFO1 (+WAL)Every fileCappedmax_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.

text
     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.

ProductDelete writesPurged whenKnobs
RocksDB / PebblePoint tombstone (Delete, SingleDelete)Bottommost compaction, no snapshot needs itCompactOnDeletionCollector, bottommost_level_compaction
Cassandra / ScyllaDBCell, row, range or partition tombstone; TTL expiryCompaction after gc_grace_secondstombstone_threshold, gc_grace_seconds, tombstone_*_threshold
HBaseDelete markerMajor compactionhbase.hregion.majorcompaction
PostgreSQL (for contrast)Sets xmax; tuple is deadVACUUMautovacuum settings (MVCC & VACUUM)
InnoDB (for contrast)Delete-mark in placePurge threadinnodb_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:

CauseSlowdown atStop atLOG message
Too many memtablesmax_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 fileslevel0_slowdown_writes_trigger (20)level0_stop_writes_trigger (36)Stalling writes because we have 4 level-0 files
Pending compaction bytessoft_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.

text
     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.

PatternHDDSSD
Random 4-16 KB readsSlow (seek ~5-10 ms)Fast (~0.1 ms)
Random small writesSlowFast at first; FTL GC and wear add cost under sustained load
Large sequential writesFastFast, least wear
Whole-file delete + TRIMFreeLets 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).

text
     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 finish

Bε-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.

text
     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
AspectPostgreSQL heap + B-treeInnoDB clusteredSQL ServerOracle
Row locationHeap, ctidLeaf of PK B+treeClustered index if defined, else heapHeap by default; IOT optional
Secondary index points toctidPrimary key valueClustering key or RIDROWID
Random PK insertsHeap fine, PK index fragmentsWhole table fragmentsLike InnoDB when clusteredHeap fine
Range scan by PKIndex + scattered heap pages (unless CLUSTERed)Sequential leavesSequentialIOT: sequential
Update of non-key columnNew tuple; HOT avoids index writesIn place + undoIn placeIn place + undo

What each product really does ​

ProductEngine familyWhat to knowDefaults worth naming
PostgreSQLHeap + B-tree indexes, WALOut-of-place row versions in the heap; indexes point to ctid; VACUUM reclaims; B-tree has deduplication and "bottom-up index deletion" against version churn8 kB pages, fillfactor 100 heap / 90 B-tree
MySQL InnoDBClustered B+tree, redo + undo, doublewriteRows live in the PK tree; secondary indexes carry the PK; purge reclaims16 KB pages, innodb_doublewrite=ON
MyRocks (MySQL/MariaDB/Percona)RocksDB under the MySQL handlerFacebook'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
SQLiteB-tree file; rollback journal or WALEvery table is a B-tree keyed by rowid (or PK with WITHOUT ROWID); one writer4096-byte pages; see SQLite
SQL ServerB+tree (clustered or heap)Clustered index = InnoDB-like; heap + RID otherwise; FILLFACTOR8 KB pages, 64 KB extents
OracleHeap (default) or index-organised tableIOT = clustered; PCTFREE reserves update spaceDB_BLOCK_SIZE usually 8 KB
MongoDB WiredTigerB-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)
RocksDBLeveled LSM (hybrid), column familiesLibrary; the reference for most tunables on this pageSee knobs
LevelDBLeveled LSMThe original Google library; single process, no column families4 MB memtable, 2 MB files
PebbleLeveled LSM in Go"a LevelDB/RocksDB inspired key-value store focused on performance and internal usage by CockroachDB"; RocksDB-compatible formats, range deletionsCockroachDB's only engine
BadgerLSM with key-value separation (WiscKey)Keys in the LSM, values in a value log; lower write amplification for large values; value-log GCGo, Dgraph
CassandraLSM per table (memtable, commit log, SSTables)Compaction per table: STCS default, UCS recommended for new tables, LCS for reads, TWCS for TTL time seriesgc_grace_seconds 864000
ScyllaDBLSM, shard-per-core C++Same SSTable family as Cassandra; STCS, LCS, TWCS, ICSSee Cassandra & ScyllaDB
HBaseLSM on HDFS (memstore, HFile, WAL)Minor and major compactions; region servers block when memstores are fullhbase.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, raftTitan optional for large values
CockroachDBPebbleMVCC keys in one LSM per store; range deletes for dropsSee Distributed SQL
LMDB, bbolt (etcd)Copy-on-write B+tree, mmapNo WAL, single writer, lock-free readersbbolt default page = OS page size
RedisIn-memory hash table + RDB snapshots / AOF logNot 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.

OptionDefaultMeaningRaise it whenCost of raising
write_buffer_size64 MBSize of one memtableWrite bursts, too many small L0 filesMemory; longer WAL replay
max_write_buffer_number2Memtables (active + immutable) before writes stopFlush cannot keep up with burstsMemory
min_write_buffer_number_to_merge1Immutable memtables merged in one flushMany overwrites of hot keysRead path checks more memtables
level0_file_num_compaction_trigger4L0 files that start L0→L1 compactionFewer, larger compactionsMore L0 files to read
level0_slowdown_writes_trigger20L0 files that start throttlingShort bursts you want to absorbRead amp during burst
level0_stop_writes_trigger36L0 files that stop writesSameSame
target_file_size_base64 MBSST size at L1 (× target_file_size_multiplier per level)Fewer files, fewer open handlesCoarser compactions
max_bytes_for_level_base256 MBTarget size of L1Match to L0 size (≈ write_buffer_size × trigger)Bigger L0→L1 merges
max_bytes_for_level_multiplier10Fan-out between levelsLower write amp needs lower (more levels)Read/space amp
level_compaction_dynamic_level_bytestrueCompute level targets from the last levelKeep true–
max_background_jobs2Flush + compaction threads (DB option, SetDBOptions)Compaction debt on a multi-core boxCPU, I/O
soft_ / hard_pending_compaction_bytes_limit64 GB / 256 GBDebt that slows / stops writesBulk loadsDisk usage
compaction_stylekCompactionStyleLevelLeveled / Universal / FIFO–Changing it needs a full compaction
block_size (table option)4 KBData block sizeScan-heavy, compression ratioPoint-read cost
filter_policy (table option)nonee.g. NewBloomFilterPolicy(10)Always for point reads~10 bits/key memory

Cassandra, ScyllaDB and HBase knobs ​

ProductKnobDefaultPurpose
Cassandra STCSmin_threshold / max_threshold4 / 32SSTables per minor compaction
Cassandra STCSbucket_low / bucket_high, min_sstable_size0.5 / 1.5, 50MBWhat counts as "similar size"
Cassandra LCSsstable_size_in_mb160Target SSTable size
Cassandra TWCScompaction_window_unit, compaction_window_sizeDAYS, 1Window per SSTable
Cassandra (all)tombstone_threshold0.2Ratio that triggers single-SSTable tombstone compaction
Cassandra (all)unchecked_tombstone_compactionfalseSkip the eligibility pre-check
Cassandra tablegc_grace_seconds864000 (10 days)Minimum tombstone age before purge
Cassandra UCSscaling_parametersT4T = tiered, L = leveled; "Using scaling_parameters:T8 will result in more SSTables per read."
HBasehbase.hregion.memstore.flush.size128 MBMemstore flush size
HBasehbase.hregion.majorcompaction7 daysMajor compaction period (purges deletes)

B-tree engine knobs (for contrast) ​

ProductKnobDefaultEffect on the storage structure
PostgreSQLfillfactor (table / index)100 / 90Free space for HOT updates and fewer splits
PostgreSQLshared_buffers128 MBPage cache inside PostgreSQL
PostgreSQLcheckpoint_timeout, max_wal_size5 min, 1 GBHow often dirty pages are written; full-page writes after each checkpoint
PostgreSQLfull_page_writesonTorn-page protection (first change after checkpoint logs the whole page)
InnoDBinnodb_buffer_pool_size128 MBPage cache
InnoDBinnodb_fill_factor100Space left on pages during sorted index build
InnoDBinnodb_doublewriteONTorn-page protection: pages written twice
InnoDBinnodb_flush_neighbors0 (8.0+)Flush adjacent dirty pages together (HDD-era)
InnoDBinnodb_redo_log_capacity100 MBRedo space; checkpoint pressure
WiredTigerstorage.wiredTiger.engineConfig.cacheSizeGB50% of (RAM − 1 GB)Cache size

Error and log messages you will see ​

MessageProductMeaningAction
Stalling writes because we have 4 level-0 filesRocksDB LOGL0 debt, throttlingCompaction threads, bigger memtables, check disk
Stopping writes because we have 5 immutable memtables (waiting for flush)RocksDB LOGFlush behindMore write buffers / background jobs
Stalling writes because of estimated pending compaction bytesRocksDB LOGDeep compaction debtFix compaction throughput; check max_bytes_for_level_base
Status::Incomplete() with no_slowdownRocksDB APIWrite refused during a stallRetry later or shed load
Read 10 live rows and 1001 tombstone cells for query ... (warning)Cassandra logOver tombstone_warn_threshold (1000)Model change; see tombstone storms
Scanned over 100001 tombstones during query ...; query aborted / TombstoneOverwhelmingExceptionCassandraOver tombstone_failure_threshold (100000)Same
Region server stops accepting updates ("new updates are blocked and flushes are forced")HBaseGlobal memstore limitFaster flush/compaction, more region servers
could not extend file ... No space left on devicePostgreSQLDisk full (bloat, WAL)VACUUM, free space, archive WAL

Solving the classic problems ​

Picking an engine ​

OptionHowAdvantageCost / limitation
Stay on B-tree (PostgreSQL / InnoDB)Default; tune keys, fillfactor, partitionsOne system, mature tooling, predictable readsWrite ceiling at random-I/O rate; bloat management
B-tree + application-level batchingAppend-only event table + periodic fold (the Laravel snippet below)LSM write pattern without a new engineYou own the "compaction" job
MyRocks inside MySQLENGINE=ROCKSDB per tableLess space and write amp, same SQLFewer features (no FK, gap-lock differences), fewer experts
RocksDB / Pebble embeddedLibrary in your serviceFull control of the LSMYou build replication, backup, ops
Cassandra / ScyllaDBWide-column LSM clusterLinear write scaling, TWCS for TTLQuery-first data modelling, tombstones, eventual consistency
TiDB / CockroachDBDistributed SQL on RocksDB / PebbleSQL + horizontal write scalingLatency of consensus, operational complexity
RedisIn-memoryMicrosecond latencyRAM cost, persistence is secondary
sql
-- 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
// 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)
	}
}
php
// 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 ​

OptionHowAdvantageCost / limitation
More background jobsmax_background_jobs = cores/2..coresCompaction keeps upCPU and I/O taken from foreground
Bigger memtableswrite_buffer_size 128-256 MB, max_write_buffer_number 4-6Absorbs bursts, fewer L0 filesMemory, longer recovery replay
Match L1 to L0max_bytes_for_level_base ≈ write_buffer_size × min_write_buffer_number_to_merge × level0_file_num_compaction_triggerL0→L1 compactions stay balancedNeeds recalculation when memtable changes
Raise stall triggers temporarilylevel0_slowdown_writes_trigger, pending-bytes limits via SetOptionsNo stalls during a known burstRead amp and disk usage during the burst
Universal compaction for the hot CFcompaction_style = kCompactionStyleUniversalLower write ampSpace amp up to 2×
Bulk load via SST ingestionBuild sorted SSTs with SstFileWriter, IngestExternalFileBypasses memtable and most compactionData must be pre-sorted, non-overlapping ideally
Subcompactionsmax_subcompactions > 1Parallel L0→L1CPU
Rate-limit the writersQueue upstream; WriteOptions.no_slowdown and retryPredictable latencyWriters wait somewhere else
text
     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
// 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):
		}
	}
}
php
// 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 ​

OptionHowAdvantageCost / limitation
Expire by file, not by rowTWCS + TTL (Cassandra), FIFO/ttl (RocksDB), DROP/DETACH PARTITION (PostgreSQL)No tombstones at allData must be time-ordered
Range or partition deletesDeleteRange (RocksDB/Pebble), DELETE ... WHERE pk = ? (Cassandra partition tombstone)One marker instead of millionsRange tombstones still cost reads until compacted
Time-bucketed partitionsPartition key includes a day/hour bucketOld buckets are never read againQueries span buckets
Don't model queues on an LSMUse a broker or a B-tree table with SKIP LOCKEDDeletes are cheap in a B-treeAnother system
Lower gc_grace_seconds with regular repaire.g. 1-3 days if repair runs more often than thatTombstones purged soonerZombie data if repair misses the window
Deletion-triggered compactionRocksDB NewCompactOnDeletionCollectorFactory; Cassandra tombstone_threshold, unchecked_tombstone_compactionPurges dense-tombstone files earlyExtra compaction I/O
Avoid null writesCassandra: unset values instead of null in prepared statementsEach null is a cell tombstoneDriver discipline
sql
-- 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
// 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)
}
php
// 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 ​

OptionHowAdvantageCost
Monotonic keysbigint identity, UUIDv7/ULID instead of UUIDv4Right-edge inserts, full pages, small hot setKey reveals order/time
Fill factorfillfactor=80-90 on update-heavy PostgreSQL tablesHOT updates, fewer splitsMore pages
Fewer indexesDrop unused (pg_stat_user_indexes.idx_scan = 0)Every index is another random writeSome queries slower
Batch writesMulti-row INSERT, COPY, LOAD DATAAmortise WAL and page writesLatency of the batch
Rebuild bloated indexesREINDEX CONCURRENTLY, OPTIMIZE TABLE / ALTER TABLE ... FORCEDense pages againI/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:

PitfallWhy it misleadsDo instead
Run too shortAn empty LSM has no compaction debt; first minutes look greatRun until the LSM reaches steady state (levels full, compaction continuous): hours, not minutes
Data fits in RAMBoth engines become in-memory structuresDataset several times larger than cache
Empty or freshly loaded B-treeNo fragmentation, no bloatAge it with updates and deletes
Only point reads or only insertsHides 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 averagesWrite stalls and compaction show in p99/p999Report latency percentiles over time
Ignoring device effectsSSD state (fresh vs full, TRIM), cloud burst creditsPrecondition the drive; run longer than burst credits
Different durabilitysync=false vs fsync per commit; innodb_flush_log_at_trx_commit=2 vs 1Same durability on both sides
Different compressionLSM with zstd vs uncompressed InnoDBCompare equal compression or report both
Not measuring space and write bytesThe win may be in amplification, not speedReport bytes written (iostat) and disk used
Single clientNo contention, no group commitRealistic 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 ​

WorkloadRecommendedExtra techniqueReason
Read-heavy OLTP (orders, users, accounts)B-tree: PostgreSQL / InnoDBMonotonic PKs, right indexes, enough buffer poolOne home per key, predictable reads, mature tooling
Write-heavy time series / metrics with TTLLSM with TWCS (Cassandra/ScyllaDB) or FIFO/universal (RocksDB); or PostgreSQL partitionsTime-bucketed keys, drop by windowSequential writes, whole-file expiry
Event log / audit append-onlyPostgreSQL/InnoDB append table, or LSMPartition by time, BRIN index in PostgreSQLRight-edge appends are cheap even in a B-tree
Large KV store, mostly point lookupsRocksDB / Pebble / Badger (large values)Bloom filters, block cache, leveledSpace and write efficiency on flash
Write-heavy OLTP in MySQL running out of SSDMyRocks for those tablesKeep InnoDB for the restLess space and write amp
Horizontally scaled SQLTiDB (RocksDB), CockroachDB (Pebble)Range splits, follower readsLSM under consensus
Document storeMongoDB WiredTiger (B-tree)Compression, checkpointsDefault and only supported engine
Embedded, read-mostly config/statebbolt / LMDB / SQLiteOne writerCopy-on-write or B-tree, no ops
Cache, counters, sessionsRedisAOF everysec if loss mattersRAM speed
QueueNot an LSMBroker, or B-tree table with SKIP LOCKEDDelete-heavy patterns create tombstones
Analytics scansColumnar (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.

go
// 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:

go
// 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:

go
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:

go
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:

go
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.

go
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() }
go
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
<?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
<?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
<?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
<?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
<?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:

text
     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× ​

LoadTypical shapeStorage-engine move
1× (hundreds of writes/s)One PostgreSQL/MySQLMonotonic keys, right indexes, nothing else
10× (thousands/s, hot tables)Same DB, a few hot tablesBatch writes, partitions for retention, fillfactor, maybe MyRocks or an append-and-fold table
100× (tens of thousands/s, TB-scale)Separate stores per access patternLSM 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:

bash
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.log

Things 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:

bash
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.4

PostgreSQL (docker exec -it pg psql -U postgres):

sql
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):

sql
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;):

sql
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:

bash
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/LOG

ldb 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 ​

BeliefReality
LSM writes fewer bytes than a B-treeIt 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 slowPoint reads with bloom filters and cache touch about one block; scans and compaction debt are the slow cases
Deleting data frees space immediatelyLSM deletes add tombstones; PostgreSQL leaves dead tuples; space returns after compaction / VACUUM
Compaction is optional maintenanceIt is the write path's second half; stop it and writes stall
Write stalls mean the disk is failingThey are deliberate throttling when flush or compaction falls behind
SSDs make random writes freeThey make random reads cheap; random small writes cost FTL garbage collection and wear
PostgreSQL and InnoDB store tables the same wayPostgreSQL: heap + indexes pointing to ctid; InnoDB: rows inside the PK B+tree
A bloom filter tells you where a key isIt only says "definitely not" or "maybe"
TWCS fits any timestamped tableOnly time-ordered, TTL-expiring data without updates to old rows
Size-tiered is the safe defaultIt needs up to 2× free space and lets read amplification grow
An append-only MySQL table is an LSMIt is still a B+tree; you copied the pattern and own the compaction job
WiredTiger is an LSM engineMongoDB uses its B-tree; its LSM is documented as experimental
A short benchmark settles B-tree vs LSMSteady state takes hours; most short benchmarks measure an empty LSM

Cheat sheet ​

TopicRemember
Storage engineThe layer under SQL that owns pages/files, caching, logging; MySQL handler API, PostgreSQL table AM
B+treeOne home per key; in-place page updates; splits; best reads
LSM write pathWAL → memtable → immutable memtable → flush to L0 SST → compaction down the levels
LSM read pathMemtables → L0 newest first → one file per level; bloom → index block → data block (block cache)
AmplificationsWrite (bytes written / bytes put), read (places checked), space (disk / live); RUM: pick two
LeveledLow read/space amp, high write amp; RocksDB default, Cassandra LCS
Size-tiered / universalLow write amp, high read/space amp; Cassandra STCS default, RocksDB Universal
TWCS / FIFOTime-series with TTL / logs; expire whole files
TombstonesDeletes are writes; purged at the bottom level after gc_grace_seconds (Cassandra)
Write stallsToo many memtables, L0 files (20/36), pending compaction bytes (64/256 GB)
First RocksDB knobswrite_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
SSDLSM's sequential files and whole-file deletes fit flash; random small writes cost wear
Copy-on-write B-treeLMDB/bbolt: no WAL, one writer, lock-free readers
PostgreSQL vs InnoDBHeap + ctid indexes vs clustered PK; random PKs hurt InnoDB tables, PostgreSQL indexes
ProductsTiKV = RocksDB, CockroachDB = Pebble, MongoDB = WiredTiger B-tree, Redis = RAM + RDB/AOF

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
Storage engineLayer that stores and retrieves data on disk below the query layer
Handler APIMySQL's C++ interface between the SQL layer and a pluggable engine
Table access methodPostgreSQL's interface (pg_am, TableAmRoutine) for table storage; heap is built in
Page / blockFixed-size unit of I/O and caching (8 kB PostgreSQL, 16 KB InnoDB, 4 KB RocksDB data block)
Buffer poolIn-memory page cache (shared_buffers, InnoDB buffer pool)
Dirty pagePage changed in memory and not yet written to disk
CheckpointPoint where dirty pages are written so recovery can start there
B+treeBalanced tree with all keys in linked leaves; internal nodes route
Fan-outChildren per internal node; sets tree height
Page splitMoving part of a full page to a new page and adding a parent downlink
Fill factorPercentage of a page filled at build/insert time (fillfactor, innodb_fill_factor)
Clustered indexIndex whose leaves store the rows (InnoDB PK, SQL Server clustered, Oracle IOT)
HeapUnordered row storage addressed by physical location (ctid)
HOT updatePostgreSQL heap-only tuple: new version on the same page, no index writes
Doublewrite bufferInnoDB copy of pages written before in-place write, for torn-page safety
LSM-treeLog-structured merge tree: buffer in memory, write sorted immutable files, merge later
MemtableSorted in-memory write buffer of an LSM (skip list in RocksDB)
Immutable memtableFrozen memtable waiting to be flushed
FlushWriting an immutable memtable to a new L0 SSTable
WALWrite-ahead log; makes the memtable (or dirty pages) durable
SSTable / SSTSorted string table: immutable sorted file of key-value pairs
Data blockChunk of sorted entries inside an SST (default 4 KB in RocksDB)
Index blockMap from last key of each data block to its offset
Filter blockBloom filter for the keys of an SST
Footer / metaindexFixed tail of an SST pointing to index and meta blocks
Sorted runSet 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
CompactionBackground merge of sorted runs that removes obsolete versions and tombstones
Leveled compactionMerge a file into overlapping files of the next level (LCS, RocksDB Level)
Size-tiered compactionMerge several similar-size runs (STCS)
Universal compactionRocksDB's tiered style
UCSCassandra 5.0 Unified Compaction Strategy, tiered-to-leveled by scaling_parameters
TWCSTime-window compaction strategy for TTL time series
FIFO compactionDelete oldest files over a size or age limit; never merge
MANIFESTRocksDB/LevelDB log of which files form the current version
Sequence numberMonotonic number on each write; newest version wins
Merge iteratorIterator that merges sorted inputs from all levels
Bloom filterBit array answering "definitely not" or "maybe" for set membership
False positiveBloom "maybe" for a key that is absent; costs one wasted read
Block cacheRocksDB cache of uncompressed blocks
TombstoneDelete marker that shadows older values until compacted away
Range tombstoneOne marker deleting a key range (DeleteRange)
gc_grace_secondsCassandra minimum tombstone age before purge (default 10 days)
Zombie dataDeleted data resurrected because a replica missed the tombstone
Compaction debtWork compaction is behind on (L0 files, pending bytes)
Write stallThrottling or stopping writes when flush/compaction cannot keep up
Write amplificationBytes written to storage per byte written by the application
Read amplificationPlaces (pages, files) checked per lookup
Space amplificationDisk bytes per byte of live data
RUM conjectureRead, update, memory: bounding two bounds the third from below
FTLFlash translation layer: SSD firmware mapping logical to physical pages
Erase blockSmallest unit a flash chip can erase (many pages)
Wear / enduranceLimited program/erase cycles of flash; TBW rating
TRIM / discardTelling the SSD which blocks are free
Copy-on-write B-treeB-tree that writes new copies of changed pages up to a new root (LMDB, bbolt)
Bε-tree / fractal treeB-tree with buffers in internal nodes that batch writes (TokuDB, PerconaFT)
WiscKey / key-value separationKeys in the LSM, values in a separate log (Badger, RocksDB BlobDB, TiKV Titan)
MyRocksRocksDB as a MySQL storage engine
WiredTigerMongoDB's default engine: B-tree, MVCC, checkpoints + journal
PebbleGo LSM engine used by CockroachDB
TiKVDistributed KV store of TiDB, built on RocksDB
RDB / AOFRedis snapshot file / append-only command log
appendfsyncRedis AOF fsync policy: always, everysec, no
ldb / sst_dumpRocksDB admin tools for a DB directory / a single SST file
db_bench, YCSB, sysbenchBenchmark tools for RocksDB, any KV store, MySQL/PostgreSQL

References ​

Built by Morteza Negahi