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):
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:
- 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!
- When the MemTable fills up, it flushes sequentially to disk as an immutable SSTable (Sorted String Table, Level
L0). - Background compaction merges and deduplicates SSTables across levels (
L0 → L1 → L2), reclaiming space from overwritten or deleted keys (tombstones). - 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 ontenant_idalone OR(tenant_id, created_at), but not queries filtering only oncreated_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 likeWHERE email = ...), but cannot support range queries (<,>,BETWEEN) orORDER 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
GINindexes 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 downINSERT, 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.