Indexes, B-trees and LSM trees

Topic 4 of 10 in Week 3: Databases11 min readIntermediateFree course

Overview

Without an index, finding one row means reading every row: a full table scan. On a table with 100 million rows that takes seconds or minutes. An index is a separate, sorted structure that points to rows, turning that scan into a few reads. This lesson explains how indexes work, what they cost, and the two storage engine designs behind almost every database.

What an index is

Think of the index at the back of a book: sorted terms with page numbers. A database index is a sorted list of values of one or more columns, each pointing to its row. Because it’s sorted, the database can:

  • find an exact value quickly (WHERE email = ...),
  • scan a range (WHERE created_at > ...),
  • return rows already in order (ORDER BY created_at), avoiding a sort.

Composite indexes

An index on (city, signup_date) is sorted by city, then by date within each city. It helps:

  • WHERE city = 'Pune'
  • WHERE city = 'Pune' AND signup_date > '2026-01-01'
  • WHERE city = 'Pune' ORDER BY signup_date

It doesn’t help WHERE signup_date > ... alone, just as a phone book sorted by surname can’t find everyone named “Priya” quickly. Put the column you filter on with equality first.

The cost

Every index must be updated on every insert, update and delete of the indexed columns, and it takes storage and memory. Ten indexes on a busy table can make writes several times slower. Index for the queries you actually run, and remove unused indexes.

Two storage engine designs

Two ways to build an index. A B-tree, used by PostgreSQL and MySQL, has a root node with keys 40 and 80 pointing to leaf nodes 10 to 25, 50 to 65 and 90 to 99, which point to rows. It has few levels, so a lookup is about 3 to 4 page reads; writes update a page in place plus a write-ahead log, and it is great for reads and range scans. An LSM tree, used by Cassandra and RocksDB, writes first to an in-memory memtable alongside a crash-safe log. When full, the memtable is flushed to sorted files (SSTables) at level 0, and compaction merges them into bigger sorted SSTables. Writes are sequential appends and very fast; reads may check several files, helped by bloom filters, so it is great for write-heavy workloads. Both keep data sorted by key and support range queries, and every index speeds up reads and slows down writes.

B-trees

A B-tree stores keys in fixed-size pages (often 8–16 KB) arranged as a wide, shallow tree. Each page holds hundreds of keys, so even billions of rows need only three or four levels. A lookup reads one page per level, and the top levels are usually cached in memory.

Writes find the right leaf page and modify it in place; if a page fills up, it splits. Used by PostgreSQL, MySQL (InnoDB), SQL Server, Oracle and SQLite.

  • Strengths: predictable, fast reads; efficient range scans; mature.
  • Weaknesses: random writes to pages all over the disk; page splits; random keys (like UUID v4) scatter inserts and bloat the index.

LSM trees

A log-structured merge tree never updates data in place:

  1. Writes go to an append-only write-ahead log (for durability) and to a sorted in-memory table, the memtable.
  2. When the memtable is full, it’s written to disk as an immutable sorted file, an SSTable.
  3. In the background, compaction merges SSTables, discarding overwritten and deleted values.

Reads check the memtable, then SSTables from newest to oldest. Bloom filters (small probabilistic structures) let the engine skip files that certainly don’t contain the key. Used by Cassandra, ScyllaDB, RocksDB, LevelDB, HBase and Bigtable.

  • Strengths: very high write throughput (sequential I/O), good compression.
  • Weaknesses: reads may touch several files; compaction uses CPU and disk in the background and can cause latency spikes.

Which when?

Workload Prefer
Read-heavy transactional apps (users, orders) B-tree
Very write-heavy (logs, metrics, messages, IoT) LSM
Lots of range scans with updates B-tree
Huge datasets with mostly appends LSM

You usually choose the engine by choosing the database, so this is mostly a “why” you can explain in an interview: “Cassandra suits the chat message store because its LSM engine handles very high write rates.”

Durability: the write-ahead log

Both designs use a write-ahead log (WAL): every change is appended to a log on disk before it’s applied to the main data structures. After a crash, the database replays the log to recover. The same log is often used to feed replicas (the replication lesson).

Other kinds of index

  • Hash indexes: exact lookups only, no ranges.
  • Full-text (inverted) indexes: map words to documents (week 6, search).
  • Geospatial indexes: R-trees or geohashes for “near me” queries (the ride-sharing case study).
  • Partial and covering indexes: index only some rows, or include extra columns so the table isn’t read.

Recap

Indexes are sorted structures that make reads fast and writes slower. Composite indexes work left to right. B-trees update pages in place and offer fast, predictable reads; LSM trees append, flush and compact, offering very fast writes at some read cost. Both rely on a write-ahead log for durability. Index for your real queries and pick the engine that matches your read/write balance.

Exercise

Pick the indexes and the engine

(a) A users table has 50 million rows. The app runs these queries often: find a user by email; list users in a city sorted by signup date; count users who signed up today. Which indexes would you create? (b) A separate service ingests 200,000 sensor readings per second and mostly reads the last hour of data for one sensor. Would you prefer a B-tree-based or an LSM-based store, and why?

Text
(a) Indexes:
-

(b) Engine:

Summary

  • An index is a sorted structure that finds rows without scanning the whole table; it speeds up reads and slows down writes.
  • Composite indexes work left to right: (a, b) helps queries on a, or on a and b, but not on b alone.
  • B-trees keep sorted pages updated in place; a lookup takes a few page reads, which suits read-heavy workloads.
  • LSM trees buffer writes in memory, flush sorted files and merge them later; writes are fast and sequential, reads may check several files.
  • Write-ahead logs make both engines durable: a change is logged before it is applied.