Northwind: Indexes and storage engines: B-trees, LSMs and maintenance cost
Outcome. After this lesson, you can connect the Postgres predicate to its maintenance cost.
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.
A correct query can still do too much work
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.
An index is an additional access structure designed around operations such as equality lookup, ordered traversal or component matching. It is not a generic speed switch. The previous data-model lesson defined identities and invariants; this lesson asks how the service reaches the relevant records and what maintaining that path costs.
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.
More indexes are not a free optimization
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.
Connect the predicate to the records
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.
Connect the Postgres predicate to its maintenance cost
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.
Count candidates and maintenance separately
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.
In the wild: Connect the Postgres predicate to its maintenance cost
The primary reference establishes this concrete distinction: index types support particular operators, not arbitrary query acceleration.
Physical design is also a recovery design
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.
Follow one update to item K. In a B-tree-oriented index, search through separator pages to the leaf holding K, update the relevant page representation and maintain the tree as required. A full page can require a split and changes above it. Logging and buffered writes mean that describing this as one immediate disk overwrite is too simple. PostgreSQL's B-tree implementation chapter gives one concrete implementation.
In a log-structured merge-tree (LSM) path, append recovery information to a log and update an in-memory sorted structure. Later flush that structure as an immutable sorted run, commonly an SSTable. A read may reconcile K across memory and several runs. Background compaction merges runs and handles obsolete versions according to the engine's rules. Cassandra's storage-engine documentation connects commit log, memtables, sorted tables and reads in its implementation.
| Boundary | B-tree-oriented path | LSM-oriented path |
|---|---|---|
| Accept update K | Locate and change a relevant page | Record log entry and change memory state |
| Persist data structure | Write dirty pages under recovery rules | Flush an immutable sorted run |
| Read K | Traverse an applicable tree path | Check applicable memory and runs |
| Background cost | Splits, maintenance and version cleanup | Merge/rewrite runs through compaction |
Hypothetical scenario. Accept 100 records of 1 KiB each: 100 KiB of logical user payload. Suppose a chosen toy engine writes 100 KiB of corresponding recovery-log payload, flushes 100 KiB, then rewrites that 100 KiB twice through compaction. Under a data-file-only definition, amplification is (100 + 100 + 100) ÷ 100 = 3. Including the chosen log payload makes it (100 + 100 + 100 + 100) ÷ 100 = 4. Metadata, compression, partial pages and retries are deliberately excluded. State the accounting boundary before comparing engines.
Size-tiered compaction groups similarly sized runs. Leveled compaction organizes data into levels and controls overlap within levels, with implementation-specific exceptions and maintenance costs. Their read, write and temporary-space trade-offs are explained in Cassandra's compaction overview. More merging can reduce future read work while spending write bandwidth now; leaving many runs can postpone that work at the expense of read paths and space. Neither strategy is a universal winner.
For the search case, separate ingestion rate from the merge work needed to keep indexes usable. For the payment case, recovery and transaction behavior matter alongside raw ingestion. Choose from actual access patterns and measured background pressure rather than treating “append-only” as “each byte is written once.”
The index built during the busy hour
Hypothetical scenario. A team creates a broad new index to speed the seller page. Construction scans the dataset and consumes resources while the normal write workload continues. The page's eventual plan is better, but current requests queue and time out during the transition.
The missing question was how the structure would be introduced under load. Evaluate the chosen database's build behavior, resource needs, locking implications and recovery path. Define when to pause or abandon the operation and what evidence shows that the new structure is useful after completion.
Also inspect whether the query uses the intended predicate and key order. An index that is expensive to maintain but seldom used adds a permanent cost after the temporary build pressure has passed. Keep the access path because it earns its place under the real workload, not because it exists.
Claims an index cannot make
“Logarithmic search means negligible latency.” Complexity does not count all I/O, queueing, decoding or result work, and constants depend on the representation.
“An index makes any ordering cheap.” Ordering depends on the key structure and query contract. Verify what must still be sorted or fetched.
“A hash lookup proves uniqueness.” Collision handling and a uniqueness constraint are distinct from merely choosing a hash-based access structure.
“An index is a backup of the table.” It is an access representation with its own coverage. Recovery and backup requirements need an explicit design.
Use an access path to answer a specific question
Use indexes to support important predicates, joins and orderings when their benefit justifies maintenance and storage. State representative cardinalities and how they change over time. Test both common and skewed parameter values; a convenient example is not evidence about every seller.
Do not index a field solely because it appears on a diagram or because a rule says all searches need indexes. Small scans, bulk operations and low-selectivity queries can have different trade-offs. Likewise, denormalizing to avoid a lookup changes update obligations established in the previous lesson.
The caching lesson next asks when to reuse an already computed or retrieved result. Preserve the distinction: an index helps find authoritative or derived records; a cache reuses selected information under a separate validity and eviction policy.
Limits of this model
Candidate counts and logical structure updates are comparisons under a toy workload. Actual execution also depends on selectivity estimates, cache state, row visibility, write amplification and resource contention. Verify the complete access path and transition costs before accepting an additional index.
Check yourself: identify the cost
The candidate count falls by a factor of one hundred. Can the same factor be claimed for latency?
No. That calculation covers only selected candidate payload. Explain the remaining execution, I/O and queueing work and measure the complete operation.
A new index improves one query but adds work to every insertion. What comparison is missing?
The query's frequency and resource savings must be compared with maintenance, storage and transition costs under the workload. One faster sample does not establish an overall improvement.
The toy tree has three levels. Does every lookup require exactly three physical disk reads?
No. Cached pages can avoid physical reads, representation changes affect traversal, and underlying records may require extra fetches. Page-level structure and physical I/O are different counts.
Northwind decision log
Trade write and storage overhead for selective reads.
Inspect selectivity and the query plan together.
Drop an index only after checking its dependent queries.
Go deeper: Connect the Postgres predicate to its maintenance cost
- Video lecture: Testing Distributed Systems w/ Deterministic Simulation — Strange Loop Conference / Will Wilson. Think about storage changes under crashes as well as successful lookups.
- Book chapter: PostgreSQL Mistakes and How to Avoid Them, chapter 4: Table and index mistakes — Jimmy Angelakos. Read Table and index mistakes while considering how to connect the Postgres predicate to its maintenance cost.
- Book chapter: Just Use Postgres!, chapter 4: Indexes — Denis Magda. Read Indexes while considering how to connect the Postgres predicate to its maintenance cost.
- Primary source: PostgreSQL 17: Index Types — PostgreSQL Global Development Group. Drop an index only after checking its dependent queries.
Related blog: Debugging retrieval when the wrong candidate wins.