Skip to content
Visual explainer 2h to learn 3 steps

Indexes & storage engines: B-trees vs LSM trees

Explain why some databases favour writes and others favour reads.

By Invicly Tech, , in System Design Deep Dive. About 12 minutes to read.

Topic 15 of 33

In short

Storage engines decide how data sits on disk. B-trees update pages in place and favour reads; LSM trees buffer writes in memory and flush sorted files, favouring heavy write workloads.

Explained simply

A storage engine is the part of a database that decides how data is laid out on disk and how it is found again. Two designs power most databases today: B-trees and LSM trees. They make opposite trade-offs, which is why some databases are great at reads and others at heavy writes.

An index is like the index at the back of a book. Instead of reading every page to find a word, you look it up in a sorted list that tells you the page number. A database index does the same: it keeps a sorted structure of some column's values pointing to the rows.

A B-tree keeps the data sorted in fixed-size blocks called pages and changes them in place, like editing a filing cabinet. An LSM tree never edits old files. It collects new writes in memory, writes them out as new sorted files, and merges files later in the background, like a pile of notes you tidy up once in a while.

Nothing is free. Every index makes reads faster and writes slower, because each insert must also update the index. B-trees give steady, fast reads. LSM trees take writes faster but may check several files on a read and spend background work merging.

Press Play on a diagram to walk through it one step at a time.

FlowLSM tree write path
  1. Step 1
    Write-ahead log

    Append for durability

  2. Step 2
    Memtable

    Sorted in-memory buffer

  3. Step 3
    Flush to SSTable

    Immutable sorted file on disk

  4. Step 4
    Compaction

    Merge files, drop overwritten and deleted keys

CompareB-tree vs LSM tree
B-tree
  • Fixed-size pages updated in place
  • Fast, predictable reads
  • Random writes cost more
  • PostgreSQL, MySQL InnoDB
LSM tree
  • Sequential appends and merges
  • Very high write throughput
  • Reads may check several files
  • Cassandra, RocksDB
CompareWhere each engine pays its cost
B-tree
  • Write: rewrite whole page in place
  • Read: one path root to leaf
  • Space: partly empty pages
  • Background work: vacuum or page merges
LSM tree
  • Write: append and flush, cheap
  • Read: may check several files
  • Space: old versions until compaction
  • Background work: compaction I/O

In depth

Inside a B-tree

A B-tree splits data into pages, 8 KB in PostgreSQL and 16 KB by default in MySQL's InnoDB. The root page holds keys that divide the key space, and each points to a child page covering that range. Leaf pages at the bottom hold the actual keys with either the row (InnoDB stores rows in the primary key's leaves) or a pointer to the row in the table (PostgreSQL's heap).

Because each page holds hundreds of keys, the tree is very shallow. With 500 keys per page, three levels cover 125 million keys and four cover 62.5 billion. The top levels stay cached in memory, so a lookup usually costs one or two disk reads. Leaves are linked, so a range scan walks along them.

When a page is full, it splits in two and the parent gets a new key. Changes are first written to a write-ahead log so a crash mid-split cannot corrupt the tree.

LayersLooking up id = 7421 in a B-tree
  1. 1
    Root page

    Keys 1 to 10M split into ranges; go to 5,000-9,999

  2. 2
    Internal page

    Narrows to 7,000-7,499

  3. 3
    Leaf page

    Finds key 7421 and its row pointer

  4. 4
    Table row

    Heap tuple (PostgreSQL) or the leaf itself (InnoDB)

Inside an LSM tree: the read path

Writes in an LSM tree (log-structured merge tree) are cheap: append to a log, insert into the sorted in-memory memtable, done. When the memtable fills (64 MB by default in RocksDB), it becomes read-only and is flushed to disk as an SSTable, a sorted, immutable file.

Reads are where the cost hides. The newest version of a key could be in the memtable, in a recent SSTable, or in an old one. So a read checks the memtable first, then SSTables from newest to oldest, stopping at the first hit. To avoid opening every file, each SSTable has a Bloom filter, a small bit array that answers definitely not here or maybe here, and a sparse index of block offsets. With about 10 bits per key a Bloom filter gives roughly a 1% false positive rate.

Deletes are written as tombstones, markers that hide older values until compaction removes both.

FlowLSM tree read path for one key
  1. 1
    Memtable

    Newest writes, in memory

  2. 2
    Immutable memtables

    Waiting to be flushed

  3. 3
    Bloom filter check

    Skip SSTables that cannot hold the key

  4. 4
    SSTable block index

    Jump to the right block

  5. 5
    Return newest version

    A tombstone means not found

Compaction strategies

Without compaction, SSTables pile up, reads check more and more files, and deleted or overwritten data wastes space. Compaction merges sorted files, keeping only the newest version of each key, like a merge step in merge sort.

Size-tiered compaction (Cassandra's long-standing default) merges several files of similar size into one bigger file. It writes data fewer times, which suits write-heavy loads, but needs spare disk space during big merges and leaves more files for reads to check.

Leveled compaction (the default in RocksDB and LevelDB) keeps data in levels, each about 10 times larger than the one above, with non-overlapping files inside a level. A read checks at most one file per level, and space overhead is low, but data is rewritten more often, which raises write amplification.

Time-window compaction groups data by time, ideal for time series that expire with a TTL, because whole old files can simply be dropped.

  • Size-tiered: fewer rewrites, more space, more files to read
  • Leveled: predictable reads, more rewriting
  • Time-window: best for TTL time series

Read, write and space amplification

Engineers compare engines with three numbers. Write amplification: bytes physically written per byte the app writes. A B-tree changing a 100-byte row writes at least a full 8 KB page plus a WAL record. An LSM tree writes each byte to the log, then again at each compaction, often 10 or more times overall with leveled compaction. Read amplification: how many pages or files a read touches. B-trees are low and predictable; LSM trees vary with the number of files. Space amplification: disk used per byte of live data. LSM trees hold stale versions until compaction; B-trees waste space in half-empty pages.

You cannot minimise all three at once. This is why write-heavy stores (Cassandra, RocksDB, ScyllaDB) choose LSM trees and general-purpose relational databases choose B-trees. Write amplification also matters on SSDs, because it wears them out.

Making indexes work for you

A composite index on (a, b) is sorted by a, then by b. It serves filters on a, or on a and b, but not on b alone: the leftmost-prefix rule. Put equality columns first and range columns last: (customer_id, created_at) serves WHERE customer_id = 42 AND created_at > last week.

A covering index includes every column a query needs, so the database never visits the table. PostgreSQL supports this with INCLUDE (since version 11) and index-only scans. Wrapping a column in a function, like WHERE lower(email) = ..., skips a plain index; create an expression index on lower(email) instead.

Always check with EXPLAIN ANALYZE, which runs the query and shows whether an index was used and how long each step took. Remove unused indexes: PostgreSQL's pg_stat_user_indexes shows idx_scan counts, and each idle index still slows every write.

  • Leftmost prefix: (a, b) helps a, and a + b, not b alone
  • Equality columns first, range column last
  • Low-selectivity columns (like a boolean) rarely benefit alone

Learn it in 3 short steps

About 40m each. Track them with a timer in your plan.

  1. 1
    Explain how B-trees store data~40m
  2. 2
    Explain LSM trees and compaction~40m
  3. 3
    Compare read and write amplification~40m

Key points

  • Indexes speed reads but slow every write that must update them.
  • B-trees keep keys sorted in a shallow tree of pages.
  • LSM trees use Bloom filters to skip files that lack a key.
  • Compaction reclaims space but costs background I/O.

Key terms

Tap a card to flip it. 0/6 known

Examples

Fixing a slow query with a composite index

The orders page runs: latest 20 orders for one customer. With 50 million rows and no suitable index, EXPLAIN ANALYZE shows a sequential scan reading the whole table. Step 1: add an index on (customer_id, created_at DESC), equality column first. Step 2: run EXPLAIN ANALYZE again: it now shows an Index Scan that stops after 20 rows, typically under a millisecond. Step 3: CONCURRENTLY builds the index without blocking writes, which matters on a live table.

sql
EXPLAIN ANALYZE
SELECT id, total_cents, created_at FROM orders
 WHERE customer_id = 42
 ORDER BY created_at DESC LIMIT 20;
-- before: Seq Scan on orders ... rows removed by filter

CREATE INDEX CONCURRENTLY idx_orders_cust_created
    ON orders (customer_id, created_at DESC);

-- after: Index Scan using idx_orders_cust_created

How deep is a B-tree over 1 billion rows?

Assume 8 KB pages and index entries of about 16 bytes (an 8-byte key plus pointer and overhead), so roughly 500 entries per page. Step 1: 1 billion keys / 500 per page = 2 million leaf pages. Step 2: the level above needs 2,000,000 / 500 = 4,000 pages, the next 8 pages, and then one root. So the tree has 4 levels. Step 3: the upper three levels are only about 4,000 pages, roughly 32 MB, which stays in memory, so a point lookup needs about one disk read for the leaf. This is why B-tree lookups stay fast even on huge tables.

Quick reference

  • Page size: PostgreSQL 8 KB, InnoDB 16 KB by default
  • B-tree depth is about log base fanout of N: 1 billion keys fit in about 4 levels
  • LSM write path: WAL, memtable, flush to SSTable, compaction
  • Bloom filter at about 10 bits per key gives about a 1% false positive rate
  • Leveled compaction: predictable reads, higher write amplification
  • Composite index (a, b): helps a and a + b, not b alone
  • CREATE INDEX CONCURRENTLY avoids blocking writes in PostgreSQL
  • EXPLAIN ANALYZE shows the real plan and timing; pg_stat_user_indexes finds unused indexes

Common mistakes

  • Adding indexes on every column and slowing writes.
  • Ignoring compaction load spikes in LSM-based databases.
  • Expecting an index to help a query that wraps the column in a function.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1What does a Bloom filter tell an LSM tree during a read?

Question 2

2A table has an index on (country, city). Which query cannot use it efficiently?

Question 3

3Why do LSM trees usually have higher write amplification than the app's write volume suggests?

Question 4

4How does a delete work in an LSM tree?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Name the best storage engine family for: (a) an app logging 200,000 metric points per second, (b) an accounts database with many point reads and occasional updates.

  2. Exercise 2medium

    A query runs WHERE status = 'open' AND created_at > now() - interval '1 day' ORDER BY created_at. Design a PostgreSQL index for it and explain the column order. Bonus: make it smaller if only 2% of rows are open.

  3. Exercise 3hard

    Write a tiny LSM-style key-value store in Python with a memtable, flush to immutable sorted runs, reads newest-first, and tombstone deletes.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Should I add an index on every column?
No. Each index takes disk space and slows every insert, update and delete. Index the columns your frequent queries filter, join or sort on, and check with EXPLAIN ANALYZE.
Which databases use LSM trees?
Cassandra, ScyllaDB, HBase, Google Bigtable, and anything built on RocksDB or LevelDB, which includes CockroachDB (via Pebble, a RocksDB-inspired engine) and MyRocks for MySQL.
What is the difference between a clustered and a non-clustered index?
A clustered index stores the table rows themselves in index order, as InnoDB does with the primary key. A non-clustered index stores keys with pointers to rows kept elsewhere, as all PostgreSQL indexes do.

Go deeper

ShareXLinkedInWhatsApp