Database indexes: B-tree vs LSM

In one sentence

A B-tree keeps keys sorted in pages updated in place: great for reads and ranges. An LSM tree buffers writes in memory and merges sorted files later: great for ingest. Every index taxes writes.

Analogy: A B-tree is a dictionary kept in order: finding a word is fast, but adding one means making room on the right page. An LSM tree is a notebook you only append to, recopied neatly every night.

B-trees pay at write time to keep one sorted copy; LSM trees write sequentially and pay later in compaction and multi-file reads.

How it works

  • A B-tree stays 3–4 levels deep with its top levels in RAM, so a lookup costs ~1 disk read.
  • An LSM flushes its memtable as immutable sorted SSTables; background compaction merges them and drops deleted keys.
  • LSM reads may check several files, so per-file Bloom filters skip those that can't hold the key.
  • RUM conjecture: you can minimize two of read, write and space amplification, never all three.
  • In composite indexes column order matters: equality columns first, then the range or sort column.

Check yourself

Answer to mark it learned; your answers aren't scored.

A dashboard runs WHERE tenant_id = 42 AND created_at > now() - interval '24 hours' on a 20M-row Postgres table. A teammate added an index on (created_at, tenant_id), yet the query is still slow. Best fix?

Go deeper

Full explanation

An index is a second, sorted structure that lets the database find rows without scanning the table. Two designs dominate:

  • B-tree (Postgres, MySQL InnoDB): a shallow balanced tree of fixed-size pages (8 KB in Postgres, 16 KB in InnoDB). With hundreds of keys per page, 3–4 levels cover billions of rows and the top levels stay in RAM, so a lookup costs ~1 disk read. Keys stay sorted, so range scans and ORDER BY … LIMIT are cheap. Writes modify pages in place (plus the WAL).
  • LSM tree (RocksDB, Cassandra, ScyllaDB, Bigtable): writes go to a WAL and an in-memory memtable; when it fills, it is flushed as an immutable sorted SSTable. Background compaction merges SSTables and drops overwritten and deleted (tombstoned) keys. Writes are sequential and fast; a read may check several files, so per-file Bloom filters skip the ones that can't hold the key.

The trade-off is the RUM conjecture: you can minimize two of read, write (update) and space amplification, never all three. B-trees favor reads; LSMs favor writes and pay with compaction I/O and read amplification.

Two rules hold for any index: column order matters (equality columns first, then the range or sort column), and every index slows writes, because each insert must update it.

Code From seq scan to index-only scan (Postgres)
sqlFrom seq scan to index-only scan (Postgres)
-- Hot query: one tenant's LLM token usage in the last 24h
EXPLAIN (ANALYZE, BUFFERS)
SELECT created_at, total_tokens
FROM llm_calls
WHERE tenant_id = 42
  AND created_at > now() - interval '24 hours';

-- Before (no index), 20M rows:
--   Seq Scan on llm_calls (actual time=0.021..1843.512 rows=3100 loops=1)
--     Filter: ((tenant_id = 42) AND (created_at > ...))
--     Rows Removed by Filter: 19996900

-- Equality column first, range column second; INCLUDE makes it covering.
-- CONCURRENTLY: build without blocking writes on a live table.
CREATE INDEX CONCURRENTLY llm_calls_tenant_time_idx
  ON llm_calls (tenant_id, created_at)
  INCLUDE (total_tokens);

-- After (table recently vacuumed):
--   Index Only Scan using llm_calls_tenant_time_idx on llm_calls
--     (actual time=0.034..1.912 rows=3100 loops=1)
--     Index Cond: ((tenant_id = 42) AND (created_at > ...))
--     Heap Fetches: 0

-- Reversed order (created_at, tenant_id) would walk every tenant's
-- last 24h and filter: a range on the leading column ends the prefix.

-- Every index is a write tax: find the ones nobody uses.
SELECT indexrelname, idx_scan FROM pg_stat_user_indexes
WHERE relname = 'llm_calls' ORDER BY idx_scan;
Real example

An LLM call log takes ~2,000 inserts/s into Postgres. The billing dashboard's "tenant X, last 24 h" query sequentially scans 20M rows: ~1.8 s. A composite index on (tenant_id, created_at) INCLUDE (total_tokens) turns it into an index-only scan of ~3,000 entries: ~2 ms. Months later the table carries 9 indexes added "just in case"; every insert updates 9 B-trees and write latency climbs. pg_stat_user_indexes shows 5 with idx_scan = 0, so they go. When agent traces reach ~100k writes/s, they move to an LSM store (Cassandra/ScyllaDB) keyed by (tenant_id, day).

Trade-offs +3 · −3

+ You gain

  • A good index turns an O(n) scan into an O(log n) lookup: seconds become milliseconds.
  • B-tree: sorted order makes range queries, ORDER BY … LIMIT and uniqueness checks cheap.
  • LSM: sequential writes sustain far higher ingest on the same disks, and immutable files compress well.

− You pay

  • Every index adds write cost, WAL volume, disk and cache pressure.
  • LSM: reads may touch several SSTables, and compaction steals I/O and causes latency spikes.
  • B-tree: random-key inserts cause page splits and scattered writes that hurt at high ingest.

Use it when

Index the columns of your hottest WHERE, JOIN and ORDER BY clauses, proven with EXPLAIN. Pick an LSM engine for write-heavy, append-mostly data (events, traces, time series); a B-tree for read-heavy OLTP with range queries.

Avoid it when

Small tables (a seq scan wins), low-selectivity columns like a boolean, or write-heavy tables queried rarely. Never add an index you can't name the query for.

Numbers to know 4
  • Page size: 8 KB in Postgres, 16 KB in InnoDB; with hundreds of keys per page, B-trees stay ~3–4 levels deep.
  • Bloom filter: ~10 bits per key gives ~1% false positives (RocksDB's classic setting).
  • Postgres covering indexes (INCLUDE) exist since v11; index-only scans need a vacuumed visibility map.
  • Size-tiered compaction writes new SSTables while the old ones still exist, so in the worst case it needs free disk roughly equal to the data being compacted: keep ~50% headroom.
Common pitfalls 4
  • Wrong column order: (created_at, tenant_id) for tenant_id = ? AND created_at > ? scans every tenant's range.
  • Random UUIDv4 primary keys: inserts land on random B-tree pages; prefer UUIDv7 or bigint.
  • CREATE INDEX without CONCURRENTLY on a live Postgres table blocks writes for the whole build.
  • Mass deletes on an LSM store: tombstones pile up and slow reads until compaction purges them.
Interview questions 3

Answer out loud first, then reveal.

B-tree or LSM for storing agent traces at 100k events/s?Show answer

LSM. Traces are append-mostly, written far more often than read, and read by key range (tenant, session, time). An LSM turns random writes into sequential flushes, so the same disks sustain much higher ingest, and immutable SSTables compress well. I pay with read amplification and compaction I/O: leveled compaction if reads by session matter, size-tiered if it's mostly ingest, and compaction backlog as a first-class alert. Read-heavy metadata like tenants and configs stays in a B-tree store such as Postgres.

A query is slow. Walk me through fixing it with an index.Show answer

I run EXPLAIN (ANALYZE, BUFFERS) with real parameters and look for a Seq Scan with a large "Rows Removed by Filter" or an explicit Sort. Then I design the index from the query: equality columns first, then the range or ORDER BY column, and INCLUDE the selected columns if an index-only scan is cheap. I build it CONCURRENTLY, re-run EXPLAIN, and watch write latency, because every index taxes inserts. Finally I drop indexes with zero scans in pg_stat_user_indexes.

Why do extra indexes hurt UPDATE-heavy Postgres tables so much?Show answer

Postgres MVCC writes a new row version on every UPDATE. Unless it's a HOT update — no indexed column changed and the new version fits on the same page — it must insert a new entry into every index on the table. Eight indexes means nine writes plus WAL for each. So I keep indexes few, avoid indexing columns that change constantly like updated_at, and leave fillfactor headroom on hot tables so HOT updates can apply.