Skip to content

Storage Engines: B-Trees vs LSM Trees

Advanced 42 min read Part 5 of 18

How databases store data on disk: page-based B-trees vs log-structured LSM trees, WAL, compaction, bloom filters, amplification, and which databases use which.

Summary#

A storage engine is the part of a database that lays data out on disk and finds it again. There are two dominant designs. B-trees keep data in fixed-size pages sorted by key and update them in place, protected by a write-ahead log; they give fast, predictable reads and power PostgreSQL, MySQL InnoDB and most relational databases. LSM trees (log-structured merge trees) buffer writes in memory (memtable), flush them as immutable sorted files (SSTables) and merge files in the background (compaction); they turn random writes into sequential ones and power Cassandra, RocksDB, HBase and many write-heavy stores. LSM reads may check several files, so they use bloom filters. The choice is a balance of read, write and space amplification.

Why It Exists#

Disks, including SSDs, are much better at sequential I/O than at small random writes, and every write must survive a crash. A database that inserts 100,000 rows per second into random positions of a large file would spend all its time seeking and rewriting pages. Storage engines are clever answers to "how do we make writes durable and fast, and still find any key quickly?". Knowing how they work explains why Cassandra writes so fast, why Postgres needs VACUUM, and why some databases suffer latency spikes during compaction. This page builds on Database Indexing.

How It Works#

Page-oriented B-tree storage#

The B-tree (B+ tree) divides the file into fixed-size pages (8 KB in PostgreSQL, 16 KB in InnoDB). Internal pages hold sorted keys and child pointers; leaf pages hold the keys and either the rows (InnoDB's clustered index) or pointers to rows in a heap (PostgreSQL). A lookup walks from the root to a leaf, reading 3-4 pages, most of which are already cached in the buffer pool in RAM.

Writes modify pages in place: find the leaf, change it in memory, mark it dirty, and write it back later. If a leaf is full, it splits into two and the parent gets a new key. Changing a 100-byte row therefore eventually costs writing a whole 8-16 KB page.

Page-oriented B-tree storage in depth#

Inside one page. Most B-tree engines use a slotted page layout. A small header at the start holds metadata: free-space pointers, a checksum, and the log position of the last change. After it comes an array of line pointers, also called slots, each giving the offset and length of one record. The records themselves are packed from the end of the page backwards. Free space sits in the middle and shrinks from both sides. Index entries and other pages refer to a record by (page number, slot number), so the engine can move a record within its page, for example to compact free space, by updating only the slot. In PostgreSQL this pair is the ctid you can select from any table.

The buffer pool. Pages are only useful in memory, so every engine keeps a buffer pool: a large area of RAM holding copies of recently used pages. PostgreSQL's is shared_buffers, often set to about 25% of RAM, with the operating system's page cache acting as a second layer. InnoDB's is innodb_buffer_pool_size, often 60 to 75% of RAM on a dedicated server. When the pool is full, a replacement policy chooses a page to evict. PostgreSQL uses a clock-sweep approximation of least-recently-used. InnoDB uses an LRU list split into "young" and "old" parts, so a single large scan cannot flush out the hot working set. A page that has been changed in memory but not yet written back is dirty. A background writer flushes dirty pages gradually, and a checkpoint periodically guarantees that every page dirtied before a certain log position is on disk.

The write path, step by step. Updating one row in a B-tree engine works like this:

  1. Find the leaf page through the tree, using cached internal pages.
  2. Load the leaf into the buffer pool if it is not there, which is one random read.
  3. Change the record in memory and mark the page dirty.
  4. Append a log record describing the change to the WAL buffer.
  5. At commit, flush the WAL up to this transaction's record to durable storage.
  6. Later, at a background flush or checkpoint, write the whole dirty page to its place in the data file.

Only step 5 is on the commit's critical path, and it is a sequential append. Step 6 is a random write, but it happens in the background, and several changes to the same page between checkpoints share one page write. The cost appears when changes are spread thinly. If each of 10,000 updates per second hits a different page, each page write carries just one 100-byte change inside 8 KB, an 80-fold amplification of the bytes changed.

Why reads are predictable. A lookup always follows exactly one root-to-leaf path. The number of pages touched depends only on tree height, which grows with the logarithm of the row count. There is no background merge that changes the cost from one minute to the next. This steadiness is a big reason relational OLTP systems stay on B-trees: p99 latency tracks p50 closely unless the working set stops fitting in memory.

Copy-on-write B-trees. A variant never overwrites a page. A change writes a new copy of the leaf, then new copies of each parent up to a new root, and atomically switches a root pointer. LMDB, the embedded store used by OpenLDAP and others, works this way, as do the Btrfs file system and CouchDB's storage. Readers keep using the old root, so they never block, and crash recovery is trivial because the old tree is intact until the switch. The cost is rewriting a whole path per transaction, and old pages must be garbage-collected.

When a big index is fine. A web crawler that wants to skip duplicate pages can hash each page's content and store the hash in its URL metadata table, with an index on the hash column. Every new page then needs one indexed lookup ("have we seen this hash?") before it is processed. At billions of pages, that index is large, and it is tempting to worry that it will slow writes. In practice the worry is overstated. A B-tree insert is a few cached page touches plus a WAL append, and modern engines handle large indexes well, so the design is sound. The hash column is random, though, so its index has no locality, and its inserts behave like the random-key case in Database Indexing. Size the buffer pool or the number of shards so that the upper levels of the index stay in memory.

Write-ahead log#

Because dirty pages are written back lazily, a crash would lose changes still in memory, or leave a page half written. So before a commit is acknowledged, every change is appended to a sequential write-ahead log (WAL; InnoDB's redo log) and fsynced. After a crash, the engine replays the WAL from the last checkpoint to rebuild every committed change. The WAL turns the durability cost of a commit into one sequential append, and the same log feeds replication. LSM engines use a WAL too, to protect the memtable. See ACID and Isolation Levels.

Write-ahead log in depth#

The rule that gives the log its name. Before a changed page may be written to the data file, the log records describing that change must already be on durable storage. If this rule holds, every state on disk can be explained and repaired from the log. Each log record carries a log sequence number (LSN), a position in the log. Each page records the LSN of the last change applied to it. During recovery, the engine compares the two. If the page's LSN is older than the record's, the change is replayed. If not, it is already on the page and is skipped.

Redo and undo. A redo record says how to re-apply a change: "set bytes 120 to 220 of page 9001 to ...". An undo record says how to reverse it. Engines that may write uncommitted changes to the data file (a "steal" policy, which lets the buffer pool evict dirty pages freely) also need undo, so they can roll back transactions that were running at the crash. The best-known design is ARIES, from Mohan, Haderle, Lindsay, Pirahesh and Schwarz: "ARIES: A Transaction Recovery Method Supporting Fine-Granularity Locking and Partial Rollbacks Using Write-Ahead Logging" (ACM Transactions on Database Systems, 1992). Its recovery runs in three passes: analysis (what was in flight), redo (repeat history to the crash point) and undo (roll back the losers). InnoDB keeps a redo log plus separate undo logs, which also serve MVCC. PostgreSQL's WAL is mostly redo. Instead of undo, it keeps old row versions in the heap, and transaction status decides what is visible.

What fsync costs, and group commit. A commit is not durable until the WAL bytes are flushed with fsync, or written with an equivalent flag. The cost depends heavily on hardware:

StorageTypical durable flush latency
Enterprise NVMe with power-loss protectionTens of microseconds
Consumer SSD without power-loss protectionHundreds of microseconds to milliseconds, and it may not truly persist
Network block storage (cloud volumes)About 0.5 to 2 ms
Spinning diskSeveral ms

With a 1 ms flush and one flush per commit, a single session tops out near 1,000 commits a second. Engines get past this with group commit. While one flush is in progress, other transactions' log records pile up in the buffer, and the next flush makes all of them durable together. Under concurrency, one fsync can cover dozens of commits.

Relaxing durability on purpose. Engines let you trade a little durability for speed:

  • PostgreSQL synchronous_commit = off acknowledges commits before the flush. A crash can lose the last fraction of a second of commits, but it never corrupts data. It can be set per transaction, so analytics or click logging can use it while payments do not.
  • MySQL's innodb_flush_log_at_trx_commit = 1 flushes at every commit, the safe default. A value of 2 writes to the OS at commit and flushes about once a second, which survives a MySQL crash but not an OS crash or power loss. A value of 0 writes and flushes about once a second.
  • Redis's append-only file offers appendfsync always, everysec (the common default) or no.

Checkpoints and recovery time. Recovery replays the log from the last checkpoint, so the checkpoint interval sets the worst-case recovery time. Frequent checkpoints mean fast recovery but more page writes. In PostgreSQL they also mean more full-page images in the WAL, because the first change to each page after a checkpoint logs the whole page (see the Deep Dive). Typical settings are a checkpoint every 5 to 15 minutes or every few gigabytes of WAL, which gives recovery times of seconds to a few minutes.

One log, many jobs. The WAL is more than a crash-recovery tool:

  • Physical replication ships it to replicas, which replay it.
  • Point-in-time recovery replays archived WAL on top of a base backup, up to any chosen moment.
  • Logical decoding and CDC turn it into a stream of row changes for Debezium and Kafka. See Change Data Capture.

The same idea, a durable ordered log as the source of truth, reappears in Kafka and in event sourcing.

When fsync lies or fails. Durability depends on every layer honouring flushes: drive caches, RAID controllers and virtual disks. In 2018, PostgreSQL developers found that on Linux, a failed fsync could clear the error state. A retry would then "succeed" without the data ever being written. PostgreSQL responded by treating an fsync failure as fatal and recovering from the WAL instead of retrying. The lesson for system design: test durability claims by pulling power, and prefer hardware with power-loss protection for databases.

LSM trees: memtable, SSTables and compaction#

  1. Write goes to the WAL and into the memtable, an in-memory sorted structure. That is the whole write path: no disk seeks, so writes are very fast.
  2. When the memtable reaches a size limit, it becomes immutable and is flushed to disk as an SSTable (sorted string table): a file of key-value pairs sorted by key, with a small index of key offsets. The WAL segment can then be discarded.
  3. Updates and deletes do not modify old files. An update writes a newer version; a delete writes a tombstone marker. Old versions remain on disk until compaction.
  4. Compaction runs in the background, merging several SSTables (like the merge step of merge sort), keeping only the newest version of each key and dropping tombstoned data once it is safe.

Compaction strategies decide which files are merged and when:

StrategyHowStrengthWeaknessUsed by
Size-tieredMerge several SSTables of similar size into one bigger fileLow write amplification; good for write-heavy loadsHigh space amplification (needs free space up to the size of the data being merged); reads may check many filesCassandra default (STCS); RocksDB "universal" is similar
LeveledEach level is about 10x larger than the previous; each level is one sorted run of non-overlapping filesFew files per read, low space amplificationHigher write amplification (data rewritten at each level)LevelDB, RocksDB default, Cassandra LCS
Time-windowGroup SSTables by time window; never merge across windows; drop whole windows on expiryVery cheap for time-series with TTLsOnly fits data written once and expired by timeCassandra TWCS

LSM trees in depth#

Where the design came from. Patrick O'Neil, Edward Cheng, Dieter Gawlick and Elizabeth O'Neil described the log-structured merge tree in "The Log-Structured Merge-Tree (LSM-Tree)" (Acta Informatica, 1996). They aimed at workloads such as transaction history, where inserts vastly outnumber lookups. Google's "Bigtable: A Distributed Storage System for Structured Data" (Chang et al., OSDI 2006) turned the idea into the memtable, SSTable and compaction design used today. LevelDB, released by Jeff Dean and Sanjay Ghemawat in 2011, made it an embeddable library. Facebook forked LevelDB into RocksDB, adding multi-threaded compaction, column families and many tuning options. RocksDB is now the engine inside many other systems.

A motivating workload. Picture a monitoring service ingesting 2 million data points a second from 50,000 servers, each about 50 bytes after encoding, or 100 MB/s of new data. In a B-tree keyed by (series, timestamp), each point lands in the leaf for its series. With 50,000 servers × 100 metrics = 5 million series, the active leaves alone run to many gigabytes. Writes become random page updates, and the engine spends its I/O rewriting 8 KB pages to add 50 bytes each time. In an LSM tree, the same points go into the memtable, and every 64 MB the engine writes one sorted file sequentially. The disk sees large sequential writes, which every storage device handles best.

The memtable. The memtable must stay sorted, take concurrent inserts, and allow ordered iteration for the flush. RocksDB and LevelDB use a skip list by default. Cassandra uses a concurrent skip-list-based structure, and some engines use balanced trees or hash-plus-vector variants for special workloads. When the active memtable is full, it becomes immutable, a fresh one takes new writes, and a background thread flushes the immutable one. If flushing falls behind and too many immutable memtables pile up (max_write_buffer_number), the engine stalls writes. This is deliberate back-pressure that stops memory from running out.

Inside an SSTable. An SSTable is more than a sorted dump. A typical layout:

  • Data blocks of about 4 to 64 KB, each holding sorted key-value pairs. Keys are prefix-compressed: each key stores only the bytes that differ from the previous key, with periodic "restart points" where a full key is written so that search can start there. Blocks are often compressed with LZ4, Snappy or Zstandard.
  • An index block holding the last key of each data block and its offset. A lookup binary-searches the index, then reads exactly one data block.
  • A filter block holding the bloom filter for the file's keys (next section).
  • A footer with the offsets of the index and filter blocks, so the file can be opened by reading its end.

Index and filter blocks are small and are usually cached in memory. So a point lookup in one SSTable costs at most one data-block read, and zero if the filter says the key is absent.

Versions, sequence numbers and tombstones. Every write gets an increasing sequence number. Internally the key is (user key, sequence number), sorted so that the newest version comes first. That gives MVCC almost for free: a snapshot is just "ignore sequence numbers above S". A delete writes a tombstone, a marker that hides older versions. A range delete writes one range tombstone covering a key interval, instead of millions of point tombstones. Data is only physically removed when compaction merges a tombstone with every older version it hides, and, in the lowest level, the tombstone itself can then be dropped.

Leveled compaction, with numbers. Take RocksDB's defaults: Level 1 is about 256 MB, and each level is 10 times bigger, so Level 2 is 2.5 GB, Level 3 is 25 GB, Level 4 is 250 GB and Level 5 is 2.5 TB. Within each level from L1 down, files do not overlap in key range, so a point lookup checks at most one file per level. Compaction picks a file in level N and merges it with the overlapping files in level N+1, about 10 files' worth because of the size ratio. So moving a byte one level down rewrites about 10 bytes in the worst case, and data passes through every level. Counting the WAL, the L0 flush and about 10 rewrites per level over 4 to 5 levels, write amplification can reach 20 to 40 in theory. In practice, measured values are often 10 to 30, depending on key distribution. Space amplification stays low, about 1.1, because about 90% of the data sits in the last level, and at most the levels above it can hold stale versions.

Size-tiered compaction, with numbers. Size-tiered compaction waits until there are several files (Cassandra's default is 4) of similar size, then merges them into one larger file. Each byte is rewritten about once per tier. With tiers growing by 4 times, reaching a 1 TB tier from 64 MB flushes takes about 7 tiers, so write amplification is often well under 10. The cost is in reads and space. Files in the same tier overlap, so a lookup may check one file per sstable in several tiers. And merging the largest tier temporarily needs free space equal to the input, so a node should keep up to 50% of its disk free in the worst case.

Time-window compaction for time-series. When data arrives in time order and expires with a TTL, time-window compaction groups files by write time, for example one window per day. It compacts within each window, using size-tiered rules, and never across windows. Once every row in a window is past its TTL, the whole window's files are deleted outright: no tombstones to merge, no rewrites. This makes it very cheap for metrics and logs. It breaks down if old windows receive late writes or updates, because those mix new data into old windows.

Write stalls and slowdowns. Compaction must, on average, keep up with ingest. If Level 0 collects too many files (RocksDB's level0_slowdown_writes_trigger, then level0_stop_writes_trigger), or the bytes awaiting compaction exceed a limit, the engine first slows and then stops writes. In production, this appears as sudden p99 write latency spikes during ingest bursts. The fixes are more compaction threads, faster disks, larger memtables, or a compaction style with lower write amplification. Rate-limiting compaction smooths foreground latency but raises the risk of stalls, so it is a dial, not a free win.

Separating keys from values. Large values make compaction expensive, because every rewrite copies the value too. The WiscKey paper (Lu et al., "WiscKey: Separating Keys from Values in SSD-conscious Storage", USENIX FAST 2016) proposed storing values in a separate append-only log, so the LSM tree holds only keys and value pointers. Compaction then moves small entries, and write amplification drops sharply for large values. The price is an extra read per lookup and garbage collection for the value log. RocksDB's BlobDB and other engines adopt the idea for values above a size threshold.

Bloom filters in LSM reads#

A read checks the memtable, then SSTables from newest to oldest, until it finds the key. Opening every file would be slow, so each SSTable carries a bloom filter: a compact bit array that answers "is this key possibly in this file?". It never gives a false "no", and gives a false "maybe" at a tunable rate. About 10 bits per key gives roughly a 1% false-positive rate. So most files that do not contain the key are skipped without any disk read. Bloom filters do not help range scans, which must merge all overlapping files; leveled compaction keeps that number small. See Probabilistic Data Structures.

Bloom filters in depth#

The problem they solve. In a time-series database, a query such as "all data for host=server-42 over the last 30 days" may span many SSTables, while only one or two of them actually contain that series. Without help, the engine would read a block from every file to find out. Each SSTable therefore carries a bloom filter for its keys. The engine checks each filter in memory, skips every file whose filter says "not here", and reads only the files whose filter says "maybe". Across dozens of files, that turns dozens of disk reads into one or two.

How a bloom filter works. Burton Bloom described it in "Space/Time Trade-offs in Hash Coding with Allowable Errors" (Communications of the ACM, 1970). The filter is an array of m bits, all zero at first, plus k independent hash functions.

  • Add a key: compute its k hashes and set those k bits to 1.
  • Check a key: compute the same k bits. If any of them is 0, the key was never added: a certain "no". If all are 1, the key is probably there, but other keys may have set those bits by chance: a "maybe".

Bits are only ever set, never cleared, so a key that was added can never test as absent. There are no false negatives. That is what makes skipping files safe.

The math, briefly. After inserting n keys, the chance that a given bit is still 0 is about e^(−kn/m). A false positive needs all k bits to be 1, so the rate is about (1 − e^(−kn/m))^k. The best number of hash functions is k = (m/n) × ln 2. Plugging in:

Bits per key (m/n)Best kFalse-positive rate
53about 9%
107about 0.8%
1510about 0.07%
2014about 0.007%

Each extra 5 bits per key cuts the false-positive rate roughly tenfold. The common choice of 10 bits per key gives about 1%.

What it costs in memory. One billion keys at 10 bits each is 10 billion bits, about 1.25 GB of RAM. That is affordable for a large node, but not negligible. Engines therefore offer partitioned filters, which split a file's filter into pieces that can be cached separately so cold files do not pin memory. Newer designs reduce the size. RocksDB added Ribbon filters, which reach the same false-positive rate with roughly 30% less memory, at some extra CPU cost to build them. Some deployments skip filters for the last level, which holds most of the data. Most lookups for keys that exist end there anyway, so skipping its filter saves most of the memory at a small read cost.

Expected wasted reads. If a point lookup for a key that does not exist checks filters for 20 files at a 1% false-positive rate, the expected number of wasted block reads is 20 × 0.01 = 0.2. Without filters it would be 20. For keys that do exist, the engine reads the file that has them, plus about 0.01 wasted reads for each newer file checked before it.

What bloom filters cannot do. They answer "is this exact key here?". A range query such as "keys from A to C" cannot use a standard filter, because the filter has no notion of order. Engines offer prefix bloom filters, which index a fixed-length key prefix such as the series ID, so "all points for series X in a time range" can still skip files. Otherwise, range reads rely on each file's min and max key and on leveled compaction keeping overlaps few. Bloom filters also cannot delete. Variants such as counting filters and cuckoo filters support removal, but SSTables never need it, because the files are immutable. See Probabilistic Data Structures.

Read, write and space amplification#

Every engine pays somewhere. Amplification measures how much extra work the engine does per unit of useful work:

  • Write amplification: bytes written to disk per byte the application wrote. B-trees rewrite whole pages (and the WAL); LSM trees rewrite data during each compaction.
  • Read amplification: disk reads per lookup. B-trees read one path; LSM trees may check several files.
  • Space amplification: disk space used divided by live data size. B-trees waste space in partly empty pages; LSM trees keep old versions and tombstones until compaction.
B-treeLSM, leveledLSM, size-tiered
Write amplificationMedium-high (page rewrites + WAL)High (rewrite per level, often 10x+)Lower
Read amplificationLow, predictable (one root-to-leaf path)Low-medium (bloom filters help)Higher (more overlapping files)
Space amplificationMedium (page fragmentation)Low (~10% overhead)High (temporary 2x during big merges)
Write patternRandom page writesSequentialSequential
Latency profileSteadyBackground compaction can cause spikesBigger compaction spikes

The RUM conjecture sums this up: you can optimise for two of Read, Update (write) and Memory (space) overhead, but not all three.

Amplification in depth#

Worked example: one small update in each engine. An application updates one 100-byte row.

  • B-tree (PostgreSQL). The engine appends a WAL record of about 150 bytes. If this is the page's first change since the last checkpoint, the WAL also gets a full 8 KB page image. Later, the 8 KB data page is written, and possibly an index page too if an indexed column changed. With changes spread thinly across pages, that is roughly 8 to 16 KB written for 100 bytes of change. If many updates hit the same hot pages between checkpoints, the per-update cost drops toward the WAL record alone.
  • LSM (leveled RocksDB). The engine appends about 100 bytes to its WAL and inserts into the memtable. The flush writes it once to L0. Then compaction rewrites it on the way down: about 10 times per level in the worst case across 4 or 5 levels. The total is roughly 1 to 4 KB written for 100 bytes, all in large sequential chunks.

So, counted in bytes, leveled LSM write amplification can be similar to a B-tree's on small rows, or better. The real difference is the pattern. LSM writes are large and sequential, while B-tree page writes are random. That matters on hard disks, and on SSDs it shapes the drive's own internal write amplification and wear.

Why amplification matters for SSD life. Flash drives are rated for a total amount of data written, such as a few petabytes for a data-centre NVMe drive. An application writing 50 MB/s with an engine write amplification of 20 sends 1 GB/s to the device, or about 86 TB a day. A drive rated for 3.5 PB of writes would last only about 40 days at that rate. Keeping amplification down is therefore not only about speed. Facebook built MyRocks to replace InnoDB for its user database partly because the LSM engine wrote less and compressed better on flash.

Read amplification in practice. With all filters, indexes and upper levels cached, a leveled LSM point lookup typically costs about one disk read, the same as a B-tree whose internal pages are cached. The difference shows up in range scans, which must merge iterators from every level, and in lookups during compaction backlogs, when L0 has many overlapping files. Size-tiered layouts pay more on reads, because more overlapping files must be checked.

Space amplification in practice. B-tree pages are rarely full. After random inserts and splits they average about 70% full, and PostgreSQL also holds dead row versions until VACUUM runs. LSM space amplification depends on compaction style. Leveled stays around 10% overhead. Size-tiered may briefly need twice the data size during a large merge. And any LSM keeps deleted data on disk until compaction reaches it, which is why disk usage can keep rising after a mass delete.

The RUM conjecture. Athanassoulis and co-authors set out the "RUM conjecture" in "Designing Access Methods: The RUM Conjecture" (EDBT 2016). It says an access method can minimise at most two of three overheads at once: Read, Update and Memory (space). B-trees favour reads. LSM trees favour updates. A plain append-only log is optimal for updates and terrible for reads. Every engine knob, such as fanout, filter bits, compaction style or fill factor, slides a design along this triangle. When someone claims a new engine is better at everything, ask which corner of the triangle it gave up.

Measuring it. RocksDB reports per-level compaction statistics, including bytes read and written, so you can divide device writes by user writes. On Linux, iostat and drive SMART counters show device-level writes. Comparing them with the application's ingest rate gives the end-to-end write amplification, including file system and drive effects.

Data structures that power databases#

StructureWhat it isWhere it is used
B+ treeBalanced tree of sorted pagesRelational tables and indexes (Postgres, InnoDB, SQLite), MongoDB's WiredTiger
Skip listSorted linked lists with random "express lanes"; O(log n) search, easy concurrent insertsLSM memtables (LevelDB, RocksDB), Redis sorted sets
Hash indexIn-memory hash map from key to file offsetBitcask (Riak's engine): one disk seek per read, but all keys must fit in RAM
SSTableImmutable sorted file with a block index and bloom filterCassandra, HBase, RocksDB, Bigtable
Inverted indexTerm to list of documents containing itLucene (Elasticsearch, OpenSearch, Solr), PostgreSQL GIN
R-treeNested bounding boxes for spatial dataPostGIS (via GiST), SQLite R*Tree module
Bloom filterProbabilistic set membershipLSM SSTables, caches, distributed joins

Lucene, the library behind Elasticsearch, is itself log-structured: it writes immutable segments and merges them in the background, the same idea as SSTables and compaction.

Data structures in depth#

Skip lists. William Pugh introduced skip lists in "Skip Lists: A Probabilistic Alternative to Balanced Trees" (Communications of the ACM, 1990). The bottom level is a sorted linked list of every element. Each element is also promoted to the level above with some probability, often 1/2 or 1/4, and so on upward. A search starts at the top level, moves right while the next key is smaller, and drops down a level when it would overshoot, much like taking express trains and then switching to locals. The expected search cost is O(log n), like a balanced tree, but an insert only links a node into a few lists. There are no rotations or rebalancing, which makes lock-free concurrent inserts practical. That is why LSM memtables favour skip lists. Ordered iteration is just a walk along the bottom list, exactly what a flush needs. Redis uses a skip list, together with a hash table, for sorted sets, so it can answer rank and range queries in O(log n).

Log-structured hash tables (Bitcask). Bitcask, the engine Basho built for Riak, is the simplest durable design that is still fast. Every write appends a record to the active data file. An in-memory hash table, the keydir, maps each key to the file, offset and size of its latest value. A read is one hash lookup plus one disk read. Old files are periodically merged, keeping only live values, and the merge writes hint files that let a restart rebuild the keydir without scanning the data. The limits are clear. Every key must fit in RAM, at a few dozen bytes of overhead per key, and range queries are impossible, because a hash has no order. It suits large numbers of point lookups on a key set of known, bounded size.

SSTables beyond LSM trees. Immutable sorted files are useful even without a memtable in front of them. Bulk-loaded read-only datasets, such as a nightly-built lookup table shipped to every server, can be served as SSTables with an index and a bloom filter. Immutable files are easy to copy, cache and checksum, because they never change after being written.

Inverted indexes. Search engines map each term to a sorted posting list of document IDs, compressed by storing gaps. Lucene writes these as immutable segments and merges them in the background, the same shape as an LSM tree. This is why newly indexed documents become searchable after a refresh rather than instantly, and why a heavy update rate costs a search cluster a lot. Every update is a delete plus a re-insert of the whole document.

R-trees. The R-tree was the first spatial index designed from the start for disk-based databases. It solved two problems that the earlier in-memory structures did not:

  • Shapes, not only points. Drivers and pins are points, but highways are lines, counties are polygons, and a shop's delivery zone is a polygon. An R-tree wraps every object in its minimum bounding rectangle, the smallest axis-aligned box that contains it. A point is a box of zero size, and a road is a long thin box.
  • Disk friendliness. Boxes that are close together are grouped under a parent box that encloses them, up to the root. Like a B-tree, it stays balanced, all leaves are at the same depth, each node fills one page, and inserts and deletes split or merge pages.

Unlike quadtree cells, R-tree boxes may overlap. A query point inside two overlapping boxes forces the search down both branches, so poor insert choices that create lots of overlap slow every query. The R*-tree (Beckmann, Kriegel, Schneider and Seeger, SIGMOD 1990) uses better insert and split rules, and sometimes reinserts entries to cut overlap. Most production R-trees follow it. PostGIS builds its spatial indexes on PostgreSQL's GiST framework, which provides R-tree-style bounding-box search, and SQLite and Oracle Spatial ship their own R-tree variants. If the question involves real geometry, such as "does this delivery zone contain this address?" or "does this road cross this county?", an R-tree is the right tool.

Radix trees and tries. In-memory databases often index keys with radix trees, where each level consumes a few bits or one byte of the key. The Adaptive Radix Tree (Leis, Kemper and Neumann, ICDE 2013) varies node size with the number of children. That keeps it compact while giving lookups whose cost depends on key length, not on the number of keys, and it supports ordered range scans that hash tables cannot.

Choosing the structure for the query, in one example. A dating app must show each user a feed of nearby people who match age and preference filters, with low latency. Filtering a transactional database at read time does not scale. One good approach indexes exactly the fields used to build the feed, including a geospatial index on location, in a search-optimised store such as Elasticsearch or OpenSearch. Then the feed query combines a geo filter, range filters and preference terms in one indexed request. The difficulty is keeping that index in step with the transactional database. Use change data capture so that profile and location updates flow into the search store. Batch those updates when they are frequent, because search engines are built for heavy reads and pay a real cost per update. Each structure, B-tree, inverted index and R-tree-like geo index, earns its place by matching one shape of query.

Which databases use which#

Engine typeDatabases
B-tree, update in placePostgreSQL, MySQL InnoDB, Oracle, SQL Server, SQLite, MongoDB (WiredTiger, default)
LSM treeCassandra, ScyllaDB, HBase, Google Bigtable, LevelDB, RocksDB, CockroachDB (Pebble), TiKV (RocksDB), MySQL MyRocks
Log-structured hashBitcask (Riak)
Log-structured segmentsLucene-based search engines

Many systems let you choose: RocksDB is embedded as the engine inside many databases, and MySQL can run InnoDB (B-tree) or MyRocks (LSM).

Which databases use which, in depth#

SystemEngineNotes
PostgreSQLHeap files + B-tree (and GIN, GiST, BRIN, hash) indexesMVCC versions live in the heap and need VACUUM. WAL for durability and replication.
MySQL InnoDBClustered B+ tree on the primary keySecondary indexes store the primary key. Redo and undo logs. Doublewrite buffer.
MySQL MyRocksRocksDB (LSM)Built at Facebook to save space and flash writes.
SQLiteB-tree fileOne file. Rollback journal or WAL mode.
MongoDBWiredTiger (B-tree, compressed, MVCC)WiredTiger can do LSM, but MongoDB uses its B-tree mode.
CassandraIts own LSM implementationSize-tiered, leveled, time-window, and newer unified compaction options.
ScyllaDBLSM in C++ on the Seastar frameworkCassandra-compatible, with one shard per CPU core.
HBaseLSM on HDFSBigtable's open-source descendant.
Google BigtableLSM on Colossus, Google's file systemThe original memtable and SSTable design.
RocksDBEmbedded LSM libraryUsed inside CockroachDB (before Pebble), TiKV, Kafka Streams state stores, and more.
CockroachDBPebble (LSM, written in Go)Replaced RocksDB with Pebble as its default engine.
RedisIn-memory hash table plus skip listsDurability through RDB snapshots and/or an append-only file.
Elasticsearch / OpenSearchLucene segments (log-structured inverted index)Refresh makes segments searchable, and merges compact them.

Reading the pattern. Systems built for general transactional work and rich queries chose B-trees. Systems built for huge write volumes spread across many nodes chose LSM trees. Systems built for one kind of query (text, time-series, vectors) chose a log-structured layout of a specialised index. A single product may also mix engines. PostgreSQL's heap is not an LSM, but its WAL is a log. Cassandra's commit log is a WAL in front of its LSM.

A decision walk-through. Three workloads:

  1. Order management: 3,000 writes and 30,000 reads a second, multi-row transactions, ad-hoc queries by support staff. A B-tree engine (PostgreSQL or InnoDB) fits: steady reads, transactions and secondary indexes are what matter.
  2. IoT readings: 500,000 small writes a second from 2 million devices, reads by device over a time range, data kept for 90 days. An LSM store with time-window compaction (Cassandra or ScyllaDB), or a time-series database, fits. Writes are sequential, and expiry drops whole files.
  3. User profile cache warmed from a database: a few thousand writes and a million reads a second, exact key lookups. An in-memory hash store (Redis) in front of the database fits. The storage engine question becomes a memory sizing question.

See Time-Series Databases and Cassandra in Practice for engine-specific tuning.

Row stores vs column stores#

Everything above stores a row's fields together, which suits OLTP: fetch or update one order with all its columns. Analytics flips the pattern. A query such as "total revenue by country for 2026" touches billions of rows but only two or three columns. A column store keeps each column in its own files, so that query reads only country, amount and created_at and skips the other 40 columns entirely.

Why column stores are fast for analytics.

  • Less I/O: reading 3 of 40 columns reads less than a tenth of the bytes.
  • Compression: values in one column are similar, so run-length, dictionary and delta encoding often shrink data 5 to 10 times. Sorting by a low-cardinality column first (country, then date) makes runs longer still.
  • Vectorised execution: the CPU processes tight arrays of one type at a time with SIMD instructions, instead of interpreting row after row.
  • Skipping: each block stores min and max values (zone maps), so a filter on dates skips whole blocks, the same idea as PostgreSQL's BRIN.

Why they are slow for OLTP. Inserting or updating one row means touching every column's file. So column stores buffer recent writes in a row-oriented or in-memory delta store and merge it into compressed column files in the background, which is an LSM-like move. ClickHouse's MergeTree engine writes sorted immutable parts and merges them, which is LSM in spirit. Apache Parquet and ORC are columnar file formats used by Spark, Trino and data lakes. Snowflake, BigQuery and Redshift are columnar warehouses. The usual architecture keeps a row-store OLTP database as the source of truth and streams changes into a column store for analytics, rather than forcing one engine to do both. Hybrid "HTAP" systems, such as TiDB with its TiFlash columnar replicas, keep a columnar copy in sync automatically.

In-memory engines and durability#

When the whole dataset fits in RAM, the engine's job changes. There are no pages to cache, and data structures can be pointer-based hash tables, skip lists and radix trees rather than disk-shaped B-trees. Reads and writes take microseconds. The open question is durability, and in-memory systems answer it with the same tools described earlier:

  • Snapshots: periodically write the full state to disk. Redis RDB files are made by a forked child process using copy-on-write memory. A crash loses everything since the last snapshot.
  • Append-only logs: log every write, as in Redis AOF or a WAL, and fsync it per write, per second or never. Logs grow, so they are periodically rewritten into a compact form, which is a tiny compaction step.
  • Replication: keep copies in the RAM of other machines, often in other availability zones. Some systems treat this as their main durability, accepting that a correlated failure of every replica loses recent data.

Memory costs roughly 10 to 50 times more per gigabyte than SSD, so in-memory engines suit hot, bounded data: sessions, counters, leaderboards, rate limits and caches. They also suit cases where a disk-based source of truth can rebuild the data. See Redis in Practice.

When to Use It#

You rarely build a storage engine, but you use this knowledge when choosing and tuning databases:

  • B-tree engines for read-heavy or mixed OLTP, range queries, and steady latency.
  • LSM engines for write-heavy workloads: event logs, messaging, metrics, IoT, high ingest rates (tens of thousands of writes per second per node).
  • Time-window compaction for time-series with TTLs.
  • Explaining latency spikes (compaction), disk usage growth (tombstones, bloat) and SSD wear (write amplification).

When NOT to Use It#

  • Do not pick an LSM store for heavy random-read workloads with tight p99 targets unless you have tested compaction impact.
  • Do not use delete-heavy patterns (queues) on LSM stores without care: tombstones pile up and slow reads.
  • Do not choose by engine alone; data model, replication and operations matter more for most systems.

How to Implement It#

  1. Characterise the workload: read/write ratio, update vs append, range scans, deletes, TTLs.
  2. Pick the engine family: B-tree for mixed OLTP; LSM for heavy writes and appends.
  3. Tune memory: buffer pool (B-tree) or block cache and memtable size (LSM) to hold the hot set.
  4. Choose a compaction strategy to match: leveled for read-heavy LSM, size-tiered for write-heavy, time-window for time-series.
  5. Monitor compaction backlog, pending tombstones, write stalls and disk headroom (size-tiered needs free space).
  6. For B-trees, monitor page splits, bloat and VACUUM progress (Postgres).
# Illustrative RocksDB options (LSM tuning knobs)
write_buffer_size = 64MB             # memtable size before flush
max_write_buffer_number = 4          # memtables in memory before writes stall
level0_file_num_compaction_trigger = 4
max_bytes_for_level_base = 256MB     # size of level 1
max_bytes_for_level_multiplier = 10  # each level about 10x larger
bloom_filter_bits_per_key = 10       # ~1% false-positive rate
compaction_style = level
TechnologyFits when
PostgreSQL / InnoDB (B-tree)General OLTP, mixed reads and writes
RocksDBEmbedded LSM engine for building databases and stateful services
Cassandra / ScyllaDBDistributed LSM for heavy writes
PebbleGo LSM engine (CockroachDB)
WiredTigerDocument store engine (MongoDB)

Trade-offs#

ChoiceGainCostPick when
B-treeFast predictable reads, in-place updatesRandom writes, page splits, fragmentationRead-heavy and mixed OLTP
LSM leveledGood reads and space, fast writesHigh write amplificationWrite-heavy with frequent reads
LSM size-tieredLowest write costSpace spikes, slower readsWrite-mostly, append workloads
LSM time-windowCheap expiry of whole windowsOnly for time-ordered TTL dataMetrics, time-series
Copy-on-write B-tree (LMDB)Lock-free readers, trivial recoveryRewrites a root path per commit, needs page reclamationRead-heavy embedded stores
Log-structured hash (Bitcask)One seek per read, append-only writesAll keys in RAM, no range queriesBounded key sets, point lookups
Key-value separation (WiscKey, BlobDB)Much lower compaction cost for large valuesExtra read per lookup, value-log garbage collectionValues of several KB and up
Relaxed commit durabilityHigher commit throughputLose the last moments of commits on crashLogs, clicks, analytics events

Common Pitfalls#

  • Running out of disk during a size-tiered compaction because there was no free headroom.
  • Using an LSM store as a queue, creating millions of tombstones that slow reads.
  • Ignoring compaction backlog until writes stall.
  • Expecting B-tree insert speed to hold with random keys (UUIDv4) on huge tables; page splits and cache misses grow.
  • Benchmarking on consumer SSDs without power-loss protection and trusting fsync numbers that do not reflect real durability.
  • Sizing LSM disks for the live data only, ignoring compaction headroom and tombstones.
  • Turning off bloom filters or caching too little of the index and filter blocks, so every read hits disk.
  • Setting checkpoints very far apart and being surprised by long crash-recovery times.
  • Deleting row by row in an LSM store instead of using TTLs, partition deletes or range tombstones.

Real-World Examples#

Google's Bigtable paper (2006) described memtables, SSTables and compaction, the design many LSM-based databases follow; RocksDB, developed at Facebook from LevelDB, is now embedded in many systems.

MySQL's MyRocks engine, developed at Facebook, replaced InnoDB for some workloads to reduce storage space and write amplification on flash.

CockroachDB replaced RocksDB with Pebble, its own Go LSM engine, as its default storage engine. TiKV, the storage layer of TiDB, runs on RocksDB.

The WiscKey paper (USENIX FAST 2016) showed large gains from separating keys and values on SSDs, and RocksDB's BlobDB applies the same idea for large values.

In the Interview#

Handling storage-engine questions in an interview#

Use the engine to justify the database. The engine is the "why" behind a database choice. "Cassandra for messages because it scales" is weak. "Messages are append-only at about 200,000 writes a second. An LSM engine turns each write into a WAL append plus a memtable insert, and partitions by conversation keep reads to one partition" is strong. In the same way, "PostgreSQL for orders because B-tree reads are predictable and the WAL gives durable commits and replicas" shows you know what you are buying.

Expect the cost question. Whatever engine you name, the next question is about its cost. For LSM stores, it is compaction I/O, write stalls, tombstones and read amplification for range scans. For B-trees, it is random write I/O, page splits with random keys, and vacuum or bloat in PostgreSQL. Name the cost before the interviewer does.

Numbers worth knowing.

  • Bloom filters: about 10 bits per key gives about 1% false positives.
  • Leveled compaction keeps about 10% space overhead. Size-tiered can briefly need up to 2 times the space.
  • A durable fsync costs tens of microseconds on NVMe with power-loss protection, and about 1 ms on cloud block storage. Group commit amortises it across many transactions.
  • B-trees with fan-out in the hundreds reach billions of keys in 4 levels.

A good follow-up answer. "Your Cassandra cluster's reads got slow after a big cleanup job. Why?" The cleanup wrote millions of tombstones. Until compaction purges them, after gc_grace_seconds, reads must scan past them. Fix it by deleting through partition-level deletes or TTLs rather than row by row, and by modelling queue-like data differently.

Deep Dive: Torn pages, MVCC storage and compaction tuningShow

Torn pages. A crash during a page write can leave half old, half new data, which the WAL alone cannot repair if the WAL only records small changes. PostgreSQL writes a full page image to the WAL the first time a page changes after each checkpoint (full_page_writes); InnoDB uses a doublewrite buffer, writing pages to a separate area first. Both cost extra writes in exchange for safe recovery.

MVCC in the engine. PostgreSQL stores new row versions in the heap and leaves old ones for VACUUM, so update-heavy tables bloat and indexes may need updating even for unindexed column changes (heap-only tuple updates avoid this when the page has space). InnoDB updates rows in place and keeps old versions in undo logs. LSM engines get MVCC almost free: versions are just keys with sequence numbers.

Compaction tuning. Compaction competes with foreground traffic for disk bandwidth. Engines rate-limit compaction, but if writes outpace it, Level 0 files pile up and the engine slows or stalls writes on purpose. Capacity planning for LSM stores must include compaction I/O (often several times the raw write rate) and free disk space.

Tombstones and repair. In distributed LSM stores like Cassandra, a tombstone must survive long enough (gc_grace_seconds) for all replicas to see it; otherwise a replica that missed the delete can bring the data back ("zombie" data) during repair.

Deep Dive: Building a minimal LSM key-value store, step by stepShow

Walking through a tiny design shows why each part of an LSM engine exists.

Version 1: append-only log. Every put(k, v) appends k, v to a file. A get(k) scans the file backwards for the newest k. Writes are as fast as the disk allows. Reads are O(n), and the file grows forever.

Version 2: add a hash index (Bitcask). Keep an in-memory map from key to file offset. Reads become one seek. But every key must fit in memory, and range queries are impossible.

Version 3: sort the data (memtable + SSTables). Buffer writes in a sorted in-memory structure and flush it as a sorted file. Now each file needs only a sparse index (one entry per block), so memory no longer scales with the key count, and range scans work by merging sorted files. A WAL protects the memtable until its flush.

Version 4: bound the number of files (compaction). Without merging, reads check ever more files. A background merge combines files, keeps the newest version of each key and drops deleted ones. Choosing which files to merge is the compaction strategy, and it decides write, read and space amplification.

Version 5: skip files cheaply (bloom filters). Add a filter per file so that point reads skip files that cannot hold the key. Cache the index and filter blocks.

Version 6: production concerns. Add checksums per block to detect corruption. Throttle compaction so it does not starve foreground I/O. Add back-pressure (write stalls) when compaction falls behind. Provide snapshots via sequence numbers, and column families for different tuning per data type. Separate large values (WiscKey-style) so compaction moves less data. Each step answers a failure of the one before, and real engines such as LevelDB and RocksDB grew in roughly this order.

Crash-safety checklist for such a store. Each step needs its own rule:

  • The WAL is fsynced before acknowledging a write.
  • A flushed SSTable is written to a temporary name, fsynced, then renamed atomically, and the directory is fsynced.
  • A manifest log records which files make up the current version of the tree, so recovery knows which files to trust.
  • WAL segments are deleted only after the manifest records the flush that made them redundant.

Getting any one of these wrong loses data on power failure, which is why engines use extensive fault-injection testing.

Key Takeaways#

  • B-trees update fixed-size pages in place, with a WAL for durability; reads are fast and predictable.
  • LSM trees write to a WAL and memtable, flush immutable SSTables and compact in the background; writes are sequential and fast.
  • Bloom filters let LSM reads skip files that cannot contain a key.
  • Size-tiered, leveled and time-window compaction trade write, read and space amplification differently.
  • Relational databases mostly use B-trees; Cassandra, RocksDB, HBase and Bigtable use LSM trees.
  • The WAL rule means log records reach durable storage before the data page. Group commit amortises fsync across many transactions.
  • LSM engines layer memtable, SSTables (data, index and filter blocks) and compaction. Sequence numbers and tombstones give MVCC and deletes.
  • Leveled compaction trades write amplification for low read and space overhead. Size-tiered is the reverse. Time-window fits TTL data.
  • A bloom filter's false-positive rate falls about tenfold for every 5 extra bits per key, and it never gives false negatives.
  • The RUM conjecture: an engine can minimise only two of read, update and memory overhead.