Indexing: B-Trees, LSM Trees and Secondary Indexes
Overview
An index is an extra data structure that lets a database find rows without reading the whole table, like the index at the back of a book. Without one, every query is a full scan; with the right one, the same query is thousands of times faster. The cost is extra storage and slower writes, because every index must be updated too.
Interviews go beyond "add an index". You are expected to know the two main index designs (the B-tree used by most relational databases and the LSM tree used by many write-heavy NoSQL stores), what a secondary index is, and why a column order in a composite index matters. This lesson explains each with numbers.
Detailed Notes
What is it?
Imagine a table of 10 million users and the query SELECT * FROM users WHERE email = 'ana@x.com'. With no index the database does a full table scan: it reads every row and checks the email. An index is a separate, sorted structure that maps email to the location of the row, so the database jumps straight to it.
Some vocabulary:
- Primary index. The index on the primary key. In many databases the rows are stored in this order.
- Secondary index. An index on any other column (
email,created_at), so you can search by something other than the primary key. A table can have many. - Composite index. An index on several columns together, such as
(user_id, created_at). - Disk page. Databases read and write in fixed blocks, commonly 8-16 KB. The cost of a query is mostly "how many pages did I touch".
Why do we need it?
Look at the numbers.
Request load
Without index
about 4 s
Reads all 2 GB, one query at a time per core.
With index
about 0.3 ms
Three page reads; top levels are usually cached.
Index cost
about 200 MB
10M entries x about 20 bytes, and one extra write per insert.
10 million rows, 200 bytes per row, SSD storage.
A full scan is proportional to table size, so as the table grows the query gets slower and slower. An index lookup grows only logarithmically: a 100x bigger table adds about one more page read. That is the difference between a query that works at launch and one that melts the database at 10x traffic.
Reads are not free of cost elsewhere, though. Every insert, update or delete must also update each index. A table with 5 indexes does roughly 6 writes per row change (the table plus 5 indexes). So indexes help reads and tax writes and storage. The skill is picking the few that your real queries need.
How does it work?
B-tree: the default
A B-tree (databases actually use the B+ tree variant) keeps keys sorted in a tree of pages. The root page lists ranges and points to child pages; the lowest level (the leaves) holds the keys and pointers to the rows.
- Fan-out. One 8 KB page can hold roughly 500 keys. So a tree with 3 levels holds about 500 x 500 x 500 = 125 million keys, and a lookup reads about 3 pages. The top levels stay in memory, so in practice it is 1 disk read.
- Point lookup:
WHERE id = 42walks root to leaf: 3 steps. - Range query:
WHERE created_at BETWEEN a AND bfinds the start leaf and walks the linked leaves in order. Sorted storage is why ranges andORDER BYare cheap. - Writes find the right leaf page and update it in place. If the page is full it splits into two. Random writes mean random disk I/O, and a write-ahead log protects against a crash mid-split.
B-trees are read-optimised and predictable. They are the right default for relational databases.
LSM tree: built for writes
Random disk writes are slow. A log-structured merge tree (LSM tree) turns them into sequential writes.
- A write is appended to a commit log (for durability) and inserted into an in-memory sorted structure, the memtable. This is very fast.
- When the memtable is full (say 64 MB) it is written to disk as an immutable sorted file called an SSTable (sorted string table). Files are never modified.
- Over time many SSTables pile up. A background process called compaction merges them into bigger sorted files and drops overwritten or deleted values.
- A read checks the memtable, then SSTables from newest to oldest. To avoid opening every file, each SSTable has a bloom filter, a tiny in-memory structure that says "this key is definitely not here" or "might be here".
B-tree
update pages in place
- 1
Walk root to leaf
about 3 page reads
- 2
Update the leaf page
random disk write
- 3
Split the page if full
log protects crashes
- Fast, predictable reads
- Efficient range scans
- Mature in SQL databases
- Random write I/O
- Page splits and fragmentation
Default for read-heavy relational workloads
LSM tree
append, then merge
- 1
Append to log + memtable
memory speed
- 2
Flush a sorted SSTable
sequential write
- 3
Compact files in background
bloom filters help reads
- Very high write throughput
- Sequential disk writes
- Compresses well
- Reads may check several files
- Compaction write amplification
Write-heavy, append-style data
Same goal, opposite choices about when to do the sorting work.
Trade-off in plain words: LSM trees accept slower, more complicated reads and background compaction work in return for very high write throughput. Cassandra, HBase and RocksDB use them. The extra disk writing caused by compaction is called write amplification: one logical write may be physically rewritten several times.
Secondary indexes in practice
A secondary index on email is a second sorted structure: email -> primary key. A query by email does two lookups: find the primary key in the secondary index, then fetch the row by primary key.
- Covering index. If the index also stores the columns the query needs, the second lookup is skipped. The index "covers" the query.
- Composite index order matters. An index on
(user_id, created_at)is sorted byuser_idfirst, then bycreated_atinside each user. It serves "orders of user 7 in date order", and "orders of user 7", but not "orders on 3 March for all users" (the date is not the leading column). Rule: equality columns first, range column last. - Low-selectivity columns. An index on
is_active(two values) is nearly useless: it narrows 10 million rows only to 5 million. - Write cost. 2,000 inserts per second into a table with 4 secondary indexes means about 10,000 index and table writes per second. Measure before adding.
Secondary indexes in a partitioned database
When data is partitioned across machines (partitioning lesson), a secondary index has a hard choice:
- Local index (per partition). Each partition indexes only its own rows. Writes are cheap, but a query by email must ask every partition and merge ("scatter-gather"), so latency is set by the slowest partition.
- Global index. One index covering all partitions, itself partitioned by the indexed value. A read goes to exactly one index partition, but each write may update an index on a different machine, usually asynchronously, so the index can briefly lag behind the data.
For a URL shortener's "links of user 42", a global index on user_id is fine because it is a rare dashboard query.
Interview tip. A frequent mistake is proposing a secondary index on a sharded store and ignoring the scatter-gather cost. Another is adding indexes on every column "just in case". State the exact query each index serves.
Reading a query plan
Databases tell you whether they used an index. In PostgreSQL, EXPLAIN shows either a Seq Scan (full scan) or an Index Scan. Seeing Seq Scan on a huge table in a hot query is your cue to add an index or fix the query (for example a function wrapped around the column, like WHERE lower(email) = ..., defeats a plain index on email).
Real-world example
An online store's order page was slow: SELECT * FROM orders WHERE user_id = 7 ORDER BY created_at DESC LIMIT 20 on a table of 200 million orders took 8 seconds, because the database scanned the table and then sorted the matches. Adding a composite index on (user_id, created_at DESC) let the database jump to user 7's entries and read the first 20 in order, finishing in about 2 ms. The team also dropped two unused indexes, which cut insert time by a third.
System design example
Design the message history for a chat app with 10,000 writes per second.
- Access pattern: newest messages in a conversation, read by
(conversation_id, message_id). This is a primary-key range read, so no secondary index is needed at all. - Storage engine: with 10,000 writes per second and mostly append-only data, an LSM-based store (Cassandra-style) fits. Sequential writes keep ingest cheap; compaction runs in the background.
- Search ("find messages containing 'invoice'") is a different access pattern. A B-tree cannot do it efficiently. Send messages asynchronously to a separate search system built on an inverted index (a map from each word to the list of messages containing it, introduced in the typeahead and search designs).
Interview discussion. Say: "I'll start from the queries. Message history is a range read on the primary key, so no extra index. Because writes dominate, I'd pick an LSM-based store. For full-text search I'd use a separate index fed asynchronously, accepting that it lags by a second or two."
Trade-off thinking. B-trees give fast, predictable reads and in-place updates at the cost of random write I/O. LSM trees give high write throughput at the cost of read complexity and compaction overhead. Every extra index speeds one read pattern and slows every write.
Key interview takeaway
Index to match queries, not columns. Know the cost on both sides: faster reads, slower writes, more storage. Use B-tree for read-heavy relational workloads and LSM for write-heavy workloads, and remember that in a partitioned database a secondary index is either scatter-gather (local) or lagging (global).
Real World Example
A 200-million-row orders table answered "latest 20 orders of a user" in 8 seconds until a composite index on (user_id, created_at DESC) cut it to about 2 ms.
Common Interview Questions
Finished this lesson?
0 of 44 lessons done · 0% of the course

