Stage 2 · Building blocks · Medium · 16 min

Indexes and storage engines

How databases find data quickly: B-tree and LSM-tree storage engines, secondary indexes and their write cost, and Bloom filters that skip unnecessary disk reads.

What each interview level is expected to know

Learn first: Choosing a database and modelling data

After this lesson you can:

  • Explain how a B-tree speeds up reads and an LSM tree speeds up writes.
  • Say why every extra index slows down writes.
  • Explain how a Bloom filter skips reads for keys that are not there.

Start here

See it in 60 seconds

Finding one row fast

Without an index the database reads every row to find one; an index is a sorted tree that finds it in a few reads.

Scene 1 of 6 · Find one user

The app asks for user 42 in a users table of 1,000,000 rows, with no index yet.

AppAppUsers tableUsers table1,000,000 rows
  • App — healthy
  • Users table — healthy — 1,000,000 rows
Rows or pages read to find user 42
not shown yet
  1. Find one user. The app asks for user 42 in a users table of 1,000,000 rows, with no index yet.
  2. Read every row. With no index, the database must read every row to be sure it found the right one: a full scan.
  3. An index is a tree. An index is a sorted tree of pages; say each splits its ids into 100 ranges (real pages hold hundreds).
  4. Follow the ranges. The top page sends 42 to the 1–10,000 page, that page to 1–100, and the bottom page finds 42.
  5. A few reads, not all. 3 index pages plus the row itself make 4 reads, instead of 1,000,000.
  6. Writes pay for it. Every new user must also be added to the index, so each index makes writes a little slower.
  7. Now you try. Pick how many rows the table holds, then find user 42. For example: 1,000,000,000 rows: a full scan reads all 1,000,000,000; the index reads 5 pages plus the row, 6 reads. Each level covers 100 times more rows, so a much bigger table needs only one or two more reads.

Scene 1 of 6: Find one user. The app asks for user 42 in a users table of 1,000,000 rows, with no index yet.

Key points

  1. With no index, finding one row means checking every row in the table, page by page: a full scan.
  2. An index is a sorted tree of pages; each page points to a smaller range of ids.
  3. Each level down covers far fewer rows, so even a billion rows need only a few reads.
  4. Every index must be updated on each write, so extra indexes make writes slower.

Go deeper in the Storage engines: B+ tree vs LSM tree lab →

In plain words

A users table holds 1,000,000 rows, and the app wants the row for user 42. With no , the database checks all 1,000,000 rows, one page after another. An index is a sorted structure, kept beside the table, that points to where each row is. With it, the database finds user 42 in a few reads. The storage engine is the part of the database that keeps tables and indexes on disk.

Each index has a price. Every insert or delete, and every update to an indexed column, must change the index as well, so writes get slower and use more disk. So you index the columns your common queries search by, such as user_id, not every column. Storage engines differ too. A B-tree keeps sorted pages and changes them in place. An writes changes in arrival order first and sorts them later, which helps heavy writes.

The problem it solves

A table keeps its rows in one order, but queries ask in many ways: by id, by email, by date. Without help, a query that does not match that order reads the whole table. That work grows with the table, so a query that was fine at 10,000 rows is slow at 100 million.

Why it matters

Most slow queries are slow because the database reads far more rows than it returns. An index lets it go almost straight to the rows it needs. The same index adds work to every write, so knowing both sides tells you which indexes to add and which to drop.

A worked example

Searching a 100-million-row table without an index can mean checking rows one by one, taking about 30 seconds. The right index narrows that same search to about 3 disk reads, roughly 5 milliseconds, which is about 30,000 ÷ 5 = 6,000 times faster.

Think of it like…

Think of a phone book. It is sorted by surname, so you find one name in a few flips. Finding who owns one phone number means reading every page.

Where this analogy stops working

Sorted order that suits one kind of question is the useful part. But a printed book never changes. A database index is updated on every insert and delete, which slows writes. A second kind of question needs a second index, with its own cost.

Try it

See it working

Guided walkthroughOpen the full lab →

Storage engines: B+ tree vs LSM tree

Write and read the same keys in two engines. A B+ tree changes pages in place. An LSM tree adds writes to memory, saves sorted files, and merges them later.

Step through the same work in each engine

Both engines start with the same six keys, user:01 to user:50. Pick an engine and the work, then press Next step. Back takes you to the step before.

The engine
The work

With these settings: The B+ tree changed 2 pages in place, at 2 places on disk. Each is saved whole later: 16 KB for a few bytes of record.

App, writes and readsAppwrites and readsLog on disk, grows at its endLog on diskgrows at its endRoot page, user:20 splits it, NOWRoot pageuser:20 splits ituser:15 → leftNOWLeft leaf page, keys before user:20Left leaf pagekeys before user:20Right leaf page, user:20 and afterRight leaf pageuser:20 and after
  • App — writes and reads — healthy
  • Log on disk — grows at its end — healthy
  • Root page — user:20 splits it — healthy — NOW — user:15 → left
  • Left leaf page — keys before user:20 — healthy
  • Right leaf page — user:20 and after — healthy
  • Write
Step 1 of 7

Step 1 of 7 · Root page

Done: user:15 starts at the root page

What happens
The root says keys before user:20 go left, so user:15 goes left.
Why
A B+ tree keeps each key in one fixed place, and the root tells the write where.
What changes
The write goes to the left leaf page.
Next
The left leaf page changes in memory

Event log

6 more to go. Press a line to go back to that step.

Pages changed in memory
0
Log entries
0
Page writes to disk
0
not yet

Step 1 of 7: Root page. user:15 starts at the root page. The root says keys before user:20 go left, so user:15 goes left.

What this simplifies. Real trees have thousands of pages and engines have many files per level, but the steps are the same. Page size differs: 16 KB in MySQL's InnoDB, 8 KB in PostgreSQL. Both kinds of engine keep a log on disk.

Try it yourself

The same six keys in both engines. Write, flush, compact and read in any order.

LSM tree: writes
New files, never edited
New data reaches disk as whole sorted files, written in one go. This suits heavy write traffic.
B+ tree: writes
Pages changed in place
Each write changes the page where its key lives, and those pages sit at scattered places on disk.
Reading one key
B+ tree is usually quicker
It walks one path from the root to one page. An LSM tree may check memory and several files.

LSM tree (used by RocksDB and Cassandra)

Built for writes
1. Memtable: the newest writes, in memory2 / 4 keys
user:10: "Alice"
user:25: "Bob"
2. Level 0: saved files (SSTables) on disk, not merged yet1 files
SST-L0-1: user:05, user:30
3. Level 1: merged files on disk, one version of each key
SST-L1-1: user:01, user:50

B+ tree (used by PostgreSQL and MySQL)

Built for reads
Root page: keys before the split key go left, the rest go right
user:20
Left leaf page: keys before user:20
user:01user:05user:10
Right leaf page: user:20 and after
user:25user:30user:50
A leaf page holds the records themselves. A page has a fixed size: 16 KB in MySQL's InnoDB, 8 KB in PostgreSQL. A write changes its page in memory, and the database writes the whole page back to disk later.

Write a key

Read one key

Log of what happened

[5:35:57 AM]Both engines start with the same six keys. Write or read a key to compare them.

Mechanics

How it works

An index trades extra writes for much faster reads. The pictures show both sides on one users table of 1,000,000 rows, stored 100 rows to a page.

  1. B-tree index (fast reads)

    Pick a case to follow below

    With this case: With no index, finding one user meant reading all 10,000 pages, 1,000,000 rows.

    App, asks the databaseAppasks the databaseIndex on email, a B-treeIndex on emaila B-treeUsers table, 1,000,000 rows, NOWUsers table1,000,000 rowsreading page 1NOW
    • App — asks the database — healthy
    • Index on email — a B-tree — healthy
    • Users table — 1,000,000 rows — healthy — NOW — reading page 1
    • Page read
    Step 1 of 2

    Step 1 of 2 · Users table

    Done: The database reads page 1

    What happens
    There is no index on email, so the database starts at the first page and checks its 100 rows.
    Why
    Rows are kept in the order they were added, not by email. Any page could hold the match.
    What changes
    No match on page 1. It goes on to page 2.
    Next
    It reads all 10,000 pages
    Pages read
    1
    of 10,000 in the table
    Rows in the table
    1,000,000
    100 to a page

    Step 1 of 2: Users table. The database reads page 1. There is no index on email, so the database starts at the first page and checks its 100 rows.

    An index is a sorted lookup structure, like the index at the back of a book. In the picture, the app looks for one email in the table. Compare no index with a B-tree index.

    With no index, the database reads every page of the table, here 10,000 pages, because any page could hold a match. The work grows with the table.

    A B-tree keeps the keys sorted in a wide, shallow tree. Each page holds many keys, so each level narrows the search a lot. Here, with 100 keys to a page, 3 levels cover 1,000,000 rows, and the lookup takes 4 page reads in all.

    Real index pages hold hundreds of keys, so finding one row among a billion takes about four steps down the tree. Because the keys are sorted, a range such as "orders from May" is also fast.

  2. LSM-tree (fast writes)

    A log-structured merge tree (LSM-tree) makes writes cheap. Each write goes to a sorted table in memory. It is also appended to a write-ahead log (WAL) on disk, so it can be replayed after a crash. When the memory table fills, it is saved to disk as a sorted file. A background job called compaction merges those files.

  3. Every index slows writes

    Pick a case to follow below

    With this case: With 1 index, adding one user took 2 writes: the row and one for each index.

    App, asks the databaseAppasks the databaseIndex on email, a B-treeIndex on emaila B-treeUsers table, 1,000,000 rows, NOWUsers table1,000,000 rowsrow writtenNOW
    • App — asks the database — healthy
    • Index on email — a B-tree — healthy
    • Users table — 1,000,000 rows — healthy — NOW — row written
    • Write
    Step 1 of 2

    Step 1 of 2 · Users table

    Done: The new row is written to the table

    What happens
    The app adds a new user. The database writes the row to a page of the table.
    Why
    This write happens whatever indexes the table has.
    What changes
    The table has the row. The indexes do not know about it yet.
    Next
    The index on email is updated
    Writes for one new user
    1
    the row and 1 index
    Indexes on the table
    1

    Step 1 of 2: Users table. The new row is written to the table. The app adds a new user. The database writes the row to a page of the table.

    What these pictures simplify. These pictures use round sizes: 1,000,000 rows, 100 rows to a page and 100 keys to an index page, so the counts come out exact. Real pages hold more or fewer, and a database keeps busy pages in memory. The storage engine lab above writes and reads keys in two engines.

    An index speeds up reads, but every index must also change when a row is added. In the picture, the app adds one new user. Compare one index with five.

    Each insert or delete must change every index on the table. An update changes the indexes on the columns it touches, and in some databases all of them. With five indexes, one new user costs 6 writes: the row and one for each index.

    So add an index for a query the app runs often, and drop indexes that nothing uses.

  4. Bloom filters skip wasted reads

    A small bit array answers "definitely not here" or "maybe here". LSM engines keep one per data file, so a lookup skips files that cannot contain the key. are possible; false negatives are not.

In code: a Bloom filter

// hashes: a few functions, each turning a key into a numberfunction makeBloom(size, hashes) {  const bits = new Uint8Array(size) // one byte per bit here, to keep it short  return {    add(key) { for (const h of hashes) bits[h(key) % size] = 1 },    mightHave(key) { return hashes.every(h => bits[h(key) % size] === 1) }  }}
  • Adding a key sets a few bits. Checking a key looks at the same bits.
  • If any of them is 0, the key was never added, and the database can skip that file.
  • If all of them are 1, the key might be there, because other keys can set the same bits.
  • A real filter packs 8 bits into each byte and picks its size from the number of keys.

Use it when

  • A column you often filter, join or sort on: these are the WHERE, JOIN and ORDER BY parts of a query.
  • A query that filters on one column and sorts on another: one composite index, such as (user_id, created_at), serves "a user's latest posts".
  • A write-heavy workload, such as logs or metrics: an LSM-tree engine usually takes writes faster than a B-tree.

Skip it when

  • A column with only a few distinct values, such as a true-or-false flag: the index still matches a large part of the table. It saves little.
  • A table that is written far more often than it is read: each index you add slows every write.

Check yourself

A query filters on email, but the only index is on user_id. What does the database do?

Also

More in 60 seconds

Surviving a crash with a log

A write-ahead log records each write before memory changes, so after a crash the database replays it and loses no flushed write.

Scene 1 of 6 · Log it first

Each write, such as x = 5, is first appended to the end of a log file: the write-ahead log.

AppAppLog on diskLog on diskx = 5 appendedTable in memoryTable in memoryData filesData files
  • App — healthy
  • Log on disk — healthy — x = 5 appended
  • Table in memory — healthy
  • Data files — healthy
Safe with 100 ms flushes
not shown yet
Lost with 100 ms flushes
not shown yet
  1. Log it first. Each write, such as x = 5, is first appended to the end of a log file: the write-ahead log.
  2. Then change memory. Only then does it change the table in memory, where reads find the new value quickly.
  3. Save in big batches. Later, the changes in memory are saved to the data files in large, efficient writes.
  4. A crash wipes memory. If the server crashes, everything in memory is gone, including writes not yet saved to the data files.
  5. Replay the log. On restart, it reads the log from the last save and replays each write, rebuilding memory.
  6. Only flushed writes count. A write is safe once a flush forces it onto the disk; confirming before the flush risks the latest writes.
  7. Now you try. Say writes arrive every 10 ms, and the log is flushed every 100 ms. After how many writes does the server crash? For example: Flushing every write loses none; with 100 ms flushes, 20 of 27 were flushed, so the last 7 are lost. Those were confirmed before their flush. Waiting for the flush before confirming, even in groups, loses none but makes each write wait.

Scene 1 of 6: Log it first. Each write, such as x = 5, is first appended to the end of a log file: the write-ahead log.

Key points

  1. Each write is appended to a log on disk first, then applied to the table in memory.
  2. Appending to the end of one file is fast, so the log costs little.
  3. After a crash, the database replays the log from its last save and rebuilds memory.
  4. Confirming before the flush is faster, but a crash can lose the latest confirmed writes.

Go deeper in the Storage engines: B+ tree vs LSM tree lab →

Judgement

Trade-offs and how it fails

What you give up

Reads vs writes
An index makes the reads that use it much faster. It also takes disk space and adds work to every write.
Storage engine
A B-tree updates pages in place, which suits reads and range queries. An LSM-tree appends and merges later, which suits heavy writes. Its reads may have to check several files, and compaction uses disk and CPU in the background.

Failure modes

  • Too many indexes: a table with 15 indexes does 16 writes for each new row, so inserts slow down.
  • An index the query cannot use: a composite index on (user_id, created_at) does little for a query that filters only on created_at.
  • A full scan that hides until the table grows: the query is fast in testing with 1,000 rows and slow in with 100 million.

In the real world

  • Meta built MyRocks, a MySQL engine on RocksDB, and reported that it used about half the storage of compressed InnoDB.
  • PostgreSQL's documentation says its default index type is the B-tree, which handles equality and range queries.

Trade-offs to be ready to discuss: Btree vs lsm · More indexes vs write speed

Check yourself

Why do LSM-tree databases, such as Cassandra, handle heavy writes well?

Interview

What interviewers look for

  • Name the index for your main query: "An index on (user_id, created_at) finds a user's latest 20 posts without a scan."
  • When you pick an LSM-tree store such as Cassandra or RocksDB, say how reads stay fast. A for each file skips the files that cannot hold the key.
  • Say the cost out loud: "Each index speeds up one query and slows every write."

Say it out loud: Why does every extra index slow down writes?

A table has 6 indexes, and inserts have become slow. Reads are fine. What is the most likely cause?

Expected depth by interview level

Levels describe the depth interviewers probe, not years of experience. Choose a level on the learning path to highlight it.

JuniorUseful
Indexes make reads fast and writes slower.
MidExpected
Which indexes a query needs.
SeniorExpected
B-tree vs LSM trade-offs, Bloom filters, write amplification.
StaffUseful
Choosing a storage engine for a workload.

Practice

Apply it

Three harder questions

The first two use the idea on a new case. The last asks you to judge a design.

Apply it

A table has a composite index on (user_id, created_at). Which query can use it best?

Apply it

An LSM engine has 8 data files, each with a Bloom filter. For one key, 7 filters say "definitely not here" and one says "maybe". How many files does the lookup read?

Judge a design

A sensor service writes 200,000 small readings a second and reads them rarely. Which storage engine fits better?

Next: transactions, which group several changes so they succeed or fail together.

Go deeper

Sources and further reading

First-hand sources to check this page against and to go further. They are standards, official docs, original papers, and guides from engineering and security teams. Each link was opened on 8 November 2026.

  • Official docsIndexesPostgreSQL documentationB-tree and other index types, multicolumn indexes, and when the planner uses them.
  • Engineering guideUse The Index, LukeMarkus WinandHow a B-tree index is laid out and why column order in an index matters.
  • Official docsRocksDB OverviewRocksDB wiki (Meta)A real LSM-tree engine: the memtable, sorted files on disk and compaction.