Skip to content

Part 1 · Blueprint 05

Indexes & Storage Engines: B-Trees vs. LSM Trees

16 min reading · Sources · Editorial review pending

An index speeds selected reads by adding write and maintenance work.

More
20px
Reading list
Page details

Published date · Last edited:

Draft edition. Editorial review and supplementary reading recommendations are still being completed.

Format: Architecture walkthrough. Prerequisites: the beginner bootcamp. Chapter prerequisites: SQL vs. NoSQL vs. NewSQL Storage Engines.

Sixty-second mental model

Problem: An index speeds selected reads by adding write and maintenance work.

Use: Account for read, write and space amplification together.

Design boundary: Explain why an index reduces query work and increases write work. Compare B-tree point/range access with log-structured write paths, including compaction, tombstones and read amplification. A physical engine decision depends on the actual workload.

Layer 1 · Intuition

Hypothetical scenario: Northwind is designing storage engines. Maya represents product requirements, Dev implementation and Priya reliability. The team must agree what one update means and which component owns the recovery log and index.

Think of a sorted filing cabinet compared with a journal of batches. Separate the requester from recovery log and index, then identify the retained evidence needed after failure.

Authority
The entitled state owner.
Invariant
A rule preserved across concurrency and failures.
B-tree
A balanced multiway search-tree family suited to page-oriented access. Analogy: A directory tree that narrows the search at each level.
Bloom filter
A probabilistic membership structure with possible false positives but no false negatives under its normal insertion-only model. Analogy: A quick door list that may send you to check inside unnecessarily.
Compaction
Rewriting storage runs to consolidate versions and reclaim eligible space. Analogy: Merging filing boxes and discarding obsolete copies.
Full table scan
Examining the table's records to evaluate a query. Analogy: Reading every page to find a name.
Index
An auxiliary structure used to locate records without scanning every record. Analogy: A book index pointing to relevant pages.

Architecture and worked reasoning

Design boundary: Explain why an index reduces query work and increases write work. Compare B-tree point/range access with log-structured write paths, including compaction, tombstones and read amplification. A physical engine decision depends on the actual workload.

Responsibilities on the request path

Storage engines: responsibilities and request directionExplain why an index reduces query work and increases write work. Compare B-tree point/range access with log-structured write paths, including compaction, tombstones and read amplification. A physical engine decision depends on the actual workload.Write logMemory tableSorted filesRead merge
Explain why an index reduces query work and increases write work. Compare B-tree point/range access with log-structured write paths, including compaction, tombstones and read amplification. A physical engine decision depends on the actual workload.

Workload and limiting resource

In a hypothetical query, a table has 10,000,000 rows and a selective ordered index visits 100 entries plus matching records. That is a different work unit from scanning 10,000,000 rows. If a mutation touches three secondary indexes, 1,000 row updates/s produce at least 3,000 logical secondary-index updates/s before physical amplification.

Keep the units attached to each intermediate result. The assumptions above describe a hypothetical exercise, not observed vendor capacity. A real capacity decision also needs a measured service curve, skew, recovery traffic and an explicit admission policy for overload.

Mutation or publication path

Storage engines: mutation boundaryAcknowledge only after the selected durability boundary. Then: Flush immutable sorted data without losing intervening writes. Then: Compact overlapping ranges and retain deletions until safe to collect.Step 1
Acknowledge only after the selected durability boundary.
Step 2
Flush immutable sorted data without losing intervening writes.
Step 3
Compact overlapping ranges and retain deletions until safe to collect.
Acknowledge only after the selected durability boundary. Then: Flush immutable sorted data without losing intervening writes. Then: Compact overlapping ranges and retain deletions until safe to collect.
  1. Acknowledge only after the selected durability boundary.
  2. Flush immutable sorted data without losing intervening writes.
  3. Compact overlapping ranges and retain deletions until safe to collect.

Observation and recovery path

Storage engines: observation boundaryCheck memory and candidate sorted files. Then: Use filters to avoid provably absent keys. Then: Merge versions according to the engine visibility rule.Step 1
Check memory and candidate sorted files.
Step 2
Use filters to avoid provably absent keys.
Step 3
Merge versions according to the engine visibility rule.
Check memory and candidate sorted files. Then: Use filters to avoid provably absent keys. Then: Merge versions according to the engine visibility rule.
  1. Check memory and candidate sorted files.
  2. Use filters to avoid provably absent keys.
  3. Merge versions according to the engine visibility rule.

Failure that changes the decision

Hypothetical scenario: Compaction falls behind sustained writes, increasing sorted-file count and read work. Adding an index can worsen both the write budget and recovery time.

Attempt this decision before reading the explanation

Does a Bloom filter replace an index for range queries?

No. It can cheaply rule out some absent point keys, with false positives. It does not identify an ordered range or return the matching values; the storage/index path still has to do that work.

Supporting mechanism analysis

Hypothetical scenario: Northwind. Maya represents product, Dev implementation and Priya reliability. The following workflow develops the underlying mechanism.

Hypothetical scenario. At Northwind, A catalogue filter scans every product while price updates wait.

In short. Trade write and storage overhead for selective reads. Inspect selectivity and the query plan together.

Hypothetical scenario. A seller opens a page listing recent active catalogue items. The database contains the right records and enforces the intended relationships, but each page request examines many unrelated items. Buying faster storage might postpone the problem without changing the work the query asks the system to perform.

The goal is to reason from a query and its result requirements to a physical access path. A useful answer includes writes and recovery, not only a faster-looking read diagram.

A new index stores additional information and must remain consistent with accepted changes. It can consume memory and storage, change write cost and increase maintenance work. An index on every field may therefore make an update-heavy workload worse while adding little value to its important reads.

Choose the operation before the structure. PostgreSQL's index-type documentation describes B-tree support for equality and ordered comparisons, hash indexing for equality, and other structures for different operators. These capabilities are concrete contracts; “indexed” does not mean that every expression or ordering can use every structure efficiently.

An index can also be a poor choice when a query needs much of a table, when selectivity changes, or when an access path requires many scattered record fetches. Inspect the actual plan and workload. A theoretical tree height alone does not predict end-to-end latency.

The seller page asks for active items belonging to one seller in a defined order. An access path that groups suitable keys can reduce the candidate range and support useful traversal. The exact key order, supported predicate, requested output and ordering semantics all matter.

Some operations can obtain the needed information from an index representation; others must fetch underlying records and verify visibility or remaining conditions. Avoid assuming that a matching key proves a request is authorized or that a record is current. Index selection is part of execution, not a replacement for the application's acceptance and permission rules.

For Northwind, an index is useful only when its organization matches a required lookup. An exact product identifier, a price range and words inside a description are different predicates. PostgreSQL documents different index types because the supported comparisons and access methods differ. An index chosen for one operator is not a general accelerator for every query on that column.

A hypothetical catalogue contains one million rows. A promotion predicate admits ten thousand candidates, and a second filter leaves two hundred. Reading only the candidate set changes the amount of inspection from one million rows to ten thousand: 1,000,000 / 10,000 = 100 times fewer candidate rows in this simplified count. It does not establish a hundredfold latency gain. Fetching payloads, sorting, visibility checks, cache state and concurrent work remain part of the execution.

Writes pay for the additional representation. If a toy insertion updates the primary representation and three secondary indexes, the accounting includes four logical structure updates before considering logging or page splits. Dropping one unused index reduces that count to three. This is a visible maintenance comparison, not a claim that all four updates cost the same amount or each creates one physical disk write.

Review the query plan and its production query shape together. A composite index that begins with tenant identity has different useful prefixes from an index that begins with price. Keeping the predicate, ordering and tenant scope explicit makes that difference discussable. Finally, index construction and replacement are changes to an operated service: budget temporary work and test the transition instead of treating the final lookup plan as the only relevant state.

Hypothetical scenario. Suppose a broad candidate scan examines 50,000 records, each with a chosen 400-byte payload. That is 50,000 × 400 = 20,000,000 bytes = 20 decimal MB of modeled record payload. A useful access path narrows the candidates to 500 records: 500 × 400 = 200,000 bytes = 0.2 MB.

The candidate payload ratio is 20 ÷ 0.2 = 100. This is not a claim that the query becomes one hundred times faster. Index pages, cache state, row representation, scattered fetches, filtering, concurrency and the returned result can all affect work and elapsed time.

For a separate tree example, choose a toy root with 100 children, each of which points to 100 leaf pages, each containing 100 record entries. The tree addresses 100 × 100 × 100 = 1,000,000 entries. A root-to-leaf descent visits three page levels in this chosen arrangement. Page occupancy, variable key size and implementation details can change the arrangement; fetching an underlying row can require additional work.

Now choose ten million record insertions per day and three secondary indexes. Under a simplified model with one logical entry added to each index per insertion, the indexes receive 10,000,000 × 3 = 30,000,000 logical entry additions per day. If each selected entry payload is 32 bytes, their raw added payload is 30,000,000 × 32 = 960,000,000 bytes = 0.96 GB/day. This excludes page overhead, splits, logs, compression, versions and background maintenance.

Those calculations expose different dimensions: candidate reduction, search depth and maintenance demand. None can be substituted for the others. A workload with frequent updates to indexed fields may pay costs that a read-only demonstration does not reveal.

The primary reference establishes this concrete distinction: index types support particular operators, not arbitrary query acceleration.

A storage engine decides how accepted state, indexes and recovery information are represented. Tree-oriented and log-structured approaches make different trade-offs around locality, buffering, rewriting and read paths. Compare the particular implementation and workload rather than declaring either family universally better.

PostgreSQL's WAL introduction describes logging changes before the corresponding data-file changes are written, enabling replay after a crash. This is a recovery mechanism, not an assertion that every copy, backup or client acknowledgement has identical durability semantics.

Background work matters. Building or rebuilding an index, reclaiming obsolete versions and compacting storage can compete with foreground traffic. Budget the transition as well as the steady state, and examine what happens if the operation is interrupted. A new access path is not operationally free simply because the query planner can use it.

Layer 3 · Internals

Trade-offs and limits

ApproachProvidesRequires
Page-oriented treeSupports ordered access and targeted updates through an index.Random access and update maintenance consume I/O and space.
Log-structured sorted runsBuffers and batches changes into sorted storage.Compaction shifts work to read, write and space amplification.

Recovery decision

Hypothetical scenario: Compaction falls behind sustained writes, increasing sorted-file count and read work. Adding an index can worsen both the write budget and recovery time.

No. It can cheaply rule out some absent point keys, with false positives. It does not identify an ordered range or return the matching values; the storage/index path still has to do that work.

Write your design before revealing the review

Does a Bloom filter replace an index for range queries?

Evidence you can explain in your own design

Drafts and self-review are stored only in this browser. They are separate from reading completion.

Compare your decision

No. It can cheaply rule out some absent point keys, with false positives. It does not identify an ordered range or return the matching values; the storage/index path still has to do that work.

Compaction falls behind sustained writes, increasing sorted-file count and read work. Adding an index can worsen both the write budget and recovery time.

Check your understanding

Does a Bloom filter replace an index for range queries?

No. It can cheaply rule out some absent point keys, with false positives. It does not identify an ordered range or return the matching values; the storage/index path still has to do that work.

How would you recover from this failure: Compaction falls behind sustained writes, increasing sorted-file count and read work. Adding an index can worsen both the write budget and recovery time.

Start with the exact boundary that failed. Acknowledge only after the selected durability boundary. Flush immutable sorted data without losing intervening writes. Compact overlapping ranges and retain deletions until safe to collect. Then recover evidence through the observation path: Check memory and candidate sorted files. Use filters to avoid provably absent keys. Merge versions according to the engine visibility rule. Preserve the distinction between a confirmed state change and an unavailable response.

Which assumption in the worked calculation would a burst or concentrated tenant invalidate first?

In a hypothetical query, a table has 10,000,000 rows and a selective ordered index visits 100 entries plus matching records. That is a different work unit from scanning 10,000,000 rows. If a mutation touches three secondary indexes, 1,000 row updates/s produce at least 3,000 logical secondary-index updates/s before physical amplification. Recompute the affected resource rather than multiplying unrelated storage and network budgets by the same factor. Explain why an index reduces query work and increases write work. Compare B-tree point/range access with log-structured write paths, including compaction, tombstones and read amplification. A physical engine decision depends on the actual workload.

Which component in this topology could be removed from a smaller first deployment?

Write log, Memory table, Sorted files, Read merge name responsibilities, not a requirement for separate processes. Co-locate responsibilities when their transaction, trust and capacity boundaries permit it. Acknowledge only after the selected durability boundary.

What evidence must a caller have before relying on the observation path?

Check memory and candidate sorted files. Use filters to avoid provably absent keys. Merge versions according to the engine visibility rule. No. It can cheaply rule out some absent point keys, with false positives. It does not identify an ordered range or return the matching values; the storage/index path still has to do that work.

45-minute interview rubric

  1. 00–05: scope update and recovery log and index.
  2. 05–12: identify the limiting resource and derive the domain workload above, retaining units and assumptions.
  3. 12–28: draw recovery log and index, numbered writes and reads.
  4. 28–40: challenge recovery: Account for read, write and space amplification together.
  5. 40–45: defend record_key placement, observations and remaining assumptions.

Go deeper

Decision log

Account for read, write and space amplification together.

Preserve update identity and recovery log and index ownership.

Revisit changed workload, observations or recovery objectives.