System design concepts · Data That Doesn't Break

Database Indexes and Storage Engines: B-Tree vs LSM-Tree

An index is a promise to do a little extra work on every write so that some reads become dramatically cheaper. Choose which promises to make.

What you'll be able to explain
  • Explain how B-tree and LSM-tree engines work
  • Pick the right engine for read- vs write-heavy workloads
  • Design composite indexes using the leftmost-prefix rule
  • Use covering and partial indexes
  • Read a query plan and spot the problems

Why indexes exist

Without an index, finding WHERE email = 'a@b.in' means scanning every row: O(n). An index is a separate sorted structure that maps values to row locations, turning lookups into O(log n). The price: extra storage, and every insert/update/delete must also update every index.

Analogy

An index is the index at the back of a textbook. Looking up "replication" takes seconds instead of reading 400 pages, but every time the author adds a page, someone has to update the index too.

B-trees: the read-friendly default

Used by PostgreSQL, MySQL/InnoDB, and most relational databases. Data is kept in fixed-size pages arranged in a shallow, balanced tree; even a billion rows is only 3–4 levels deep.

DATABASERoot pagekeys 1…1MDATABASEInternal1…500kDATABASEInternal500k…1MOKLeaf… 41,207 → rowDATABASELeaf…DATABASELeaf…DATABASELeaf…search 41,207
A B-tree lookup touches one page per level: root → internal → leaf.

Updates modify pages in place (with a write-ahead log for durability). Reads are fast and predictable; random writes cause random disk I/O.

LSM trees: the write-friendly alternative

Used by Cassandra, RocksDB, ScyllaDB, HBase, and many key-value stores.

1 · WALAppend the write to a log on disk (durability)2 · MemtableInsert into a sorted in-memory tree3 · FlushWhen full, write it out as an immutable sorted file (SSTable)4 · CompactionBackground merges of SSTables, dropping old versions and tombstones5 · ReadCheck memtable, then SSTables newest→oldest, using Bloom filters to skip files
Write path of an LSM tree: writes are sequential; reads may check several places.
B-tree LSM tree
Writes Random I/O, in place Sequential, very fast
Reads One tree walk May check several files (Bloom filters help)
Space Some fragmentation Temporary duplicates until compaction
Watch out for Write amplification on hot pages Compaction storms, read amplification, tombstones
Best for Read-heavy OLTP Write-heavy ingestion, time-series, logs

Composite indexes and the leftmost-prefix rule

An index on (city, cuisine, rating) is sorted by city, then cuisine within a city, then rating. It helps queries that filter on a left prefix:

Query filters on Uses index?
city Yes
city, cuisine Yes
city, cuisine, rating > 4 Yes (range on the last column)
cuisine only No — not a left prefix
city, rating Partly: seeks on city, then filters rating

Rule of thumb for column order: equality filters first, then range, then sort columns.