Database Indexing: B-Trees, LSM-Trees, and Inverted Indexes

A database index is a secondary data structure maintained alongside your table so queries can jump straight to matching rows in O(log N) (or O(1)) time instead of scanning millions of records on disk (full table scan, O(N)). Every index makes reads dramatically faster at the cost of extra storage and write overhead — because every INSERT, UPDATE, or DELETE must keep every index in sync.

Tuning indexes is almost always the highest-leverage performance fix you should apply before reaching for caching or database sharding.

B-Trees vs. LSM-Trees: The Two Core Storage Engines

Almost every modern database storage engine builds its primary index on one of two structures — a B-Tree (optimized for fast, predictable reads) or an LSM-Tree (Log-Structured Merge-Tree, optimized for high-throughput writes):

Comparison of B-Tree vs LSM-Tree storage indexes: B-Tree traverses a balanced root page [30 | 60] directly to Leaf [30..59] in O(log N) for fast reads with in-place page updates; LSM-Tree appends writes sequentially to a WAL and sorted in-memory MemTable before flushing and compacting into immutable SSTables with Bloom filters Comparison of B-Tree vs LSM-Tree storage indexes: B-Tree traverses a balanced root page [30 | 60] directly to Leaf [30..59] in O(log N) for fast reads with in-place page updates; LSM-Tree appends writes sequentially to a WAL and sorted in-memory MemTable before flushing and compacting into immutable SSTables with Bloom filters
B-Tree (read-optimized, in-place disk pages) vs. LSM-Tree (write-optimized, sequential WAL + MemTable + compacted SSTables) · Made with Akriti

How a B-Tree Works (PostgreSQL, MySQL InnoDB, SQLite)

A B-Tree (more specifically a B+Tree) breaks the database into fixed-size disk pages (typically 8 KB or 16 KB) organized as a shallow, balanced tree with huge branching factor (~500 keys per page). Even a 1-billion-row table is only 3–4 levels deep!

  • Reads: Follow pointers from root → branch → leaf in 3–4 page lookups (top levels stay pinned in RAM). Range queries (WHERE id BETWEEN 30 AND 59) simply walk linked leaf pages sequentially.
  • Writes: Updates overwrite the target leaf page in place (and split the page if it’s full), plus write to a Write-Ahead Log (WAL) for crash safety. Random key inserts cause random disk I/O and write amplification.

How an LSM-Tree Works (RocksDB, Cassandra, ScyllaDB, LevelDB)

An LSM-Tree converts random writes into blazing-fast sequential appends:

  1. Every write appends to an on-disk WAL (for durability) and inserts into a sorted in-memory tree (MemTable). That’s it — the write returns immediately!
  2. When the MemTable fills up, it flushes sequentially to disk as an immutable SSTable (Sorted String Table, Level L0).
  3. Background compaction merges and deduplicates SSTables across levels (L0 → L1 → L2), reclaiming space from overwritten or deleted keys (tombstones).
  4. Reads check the MemTable first, then recent SSTables — accelerated by Bloom filters that skip SSTables guaranteed not to contain the key.
Dimension B-Tree (B+Tree) LSM-Tree
Read latency Fast and predictable (1 exact leaf page) Slightly slower worst-case (may check multiple SSTables)
Write throughput Moderate (in-place random page updates + splits) Very high (pure sequential WAL + RAM MemTable)
Disk space / compression More fragmentation (partially filled pages) Compact immutable files compress very well
Background noise Minimal Compaction spikes can temporarily impact tail latency
Examples PostgreSQL, MySQL InnoDB, Oracle, SQL Server RocksDB, Apache Cassandra, ScyllaDB, HBase, Pebble

Essential Index Types in Practice

  • Composite (Multi-Column) Index: An index on (tenant_id, created_at) follows the leftmost-prefix rule — it accelerates queries filtering on tenant_id alone OR (tenant_id, created_at), but not queries filtering only on created_at. Put equality columns first, range columns last!
  • Covering Index (INCLUDE): Contains all columns needed by a query right inside the leaf page so the database answers the query via an Index-Only Scan without ever fetching the main table heap row.
  • Hash Index: Maps exact keys via a hash table (O(1) equality lookups like WHERE email = ...), but cannot support range queries (<, >, BETWEEN) or ORDER BY.
  • Inverted Index (Full-Text Search): Maps each normalized word/token → sorted list of document IDs containing it (posting list). Powers Elasticsearch, OpenSearch, and PostgreSQL GIN indexes for full-text search and JSONB queries.
  • Geospatial / Vector Indexes: R-Trees, Geohash, and S2 cells power “find drivers within 2 km”, while HNSW and IVF indexes power approximate nearest-neighbor (ANN) vector similarity search for embeddings.

Distributed Indexing Trade-Offs

Once a table is spread across multiple machines (see Partitioning Strategies), secondary indexes must choose between:

  • Local Secondary Index (Document-Partitioned): Each shard indexes only its own rows. Writes are fast and local, but querying by a non-shard-key column requires a scatter-gather across every shard.
  • Global Secondary Index (Term-Partitioned): The index itself is partitioned by the indexed column. Reads hit a single index shard, but writes must update multiple shards (usually updated asynchronously, making global indexes eventually consistent).

FAQs

Why shouldn’t I just index every column in my table? Every extra index slows down INSERT, UPDATE, and DELETE operations (the database must update every B-Tree on every write), consumes RAM in the buffer pool (evicting hotter pages), and eats disk space. Index only columns that actually appear in frequent WHERE, JOIN, or ORDER BY clauses — verified with EXPLAIN ANALYZE.
What is a Bloom filter and why do LSM-Trees rely on it? A Bloom filter is a tiny probabilistic bit array that tells you with 100% certainty if a key is definitely NOT in an SSTable (or possibly present). Without Bloom filters, looking up a non-existent key in an LSM-Tree would force disk reads across every single SSTable level.
Why do random UUIDv4 primary keys hurt B-Tree write performance? UUIDv4 values arrive in completely random order, forcing the B-Tree to jump randomly across distant leaf pages, causing frequent page splits and poor buffer-pool cache locality. Time-ordered IDs like UUIDv7, ULID, or Snowflake IDs append sequentially to the rightmost B-Tree leaf page while staying globally unique.
What is the difference between a clustered and non-clustered index? A clustered index stores the actual table row data directly inside the B-Tree leaf pages (so a table can have only one, e.g., MySQL InnoDB’s primary key). A non-clustered (secondary) index stores only the indexed key plus a pointer (primary key or row ID) to look up the full row separately.