FullStack AI Hub
Studio
System Design · 03. Data & Storage
12 min
10 steps
Intermediate

Indexing & B-Trees

Turn 10-million-row full table scans into three B+ Tree page reads without drowning writes in index updates.

System Design03. Data & StorageLesson 2 of 11
12 minIntermediate10 steps

Indexing & B-Trees

Turn 10-million-row full table scans into three B+ Tree page reads without drowning writes in index updates.

PAGES READ
120,000
QUERY P95
1,850 ms
DISK IOPS
96% full
COMPLEXITY
O(N) scan
UNINDEXED HEAP TABLE (120k PAGES) · O(N) Full Disk ScanscanscanscanOrders API54%customer_id=84921Seq ScanPlan76%120k pagesHeap Pages 1–40k94%Heap Pages 40–80k96%Heap Pages 80–120k94%
index traversal
3-hop page hit
full table scan
row + index write
disk I/O saturation
In This LessonStep 1 of 10
What You Will Master
  • ✓Trace how high-fanout B+ Trees locate any row among 100M records in 3–4 disk page reads
  • ✓Order composite index columns cleanly using the leftmost-prefix and equality-before-range rules
  • ✓Eliminate random heap table lookups entirely using covering (index-only) scans
  • ✓Balance read speedup against write amplification, low-cardinality traps, and partial indexes

Architectural Trade-Off Comparison Matrix

PatternBest ForKey Trade-Off
B+ Tree Secondary IndexPoint lookups (`=`) and range scans (`BETWEEN`, `ORDER BY`) across millions of rows in O(log N)Every INSERT/UPDATE/DELETE must update the tree and handle occasional 8 KB page splits
Composite Index (Equality → Range)Multi-column filters like `WHERE tenant_id = ? AND created_at > ?` using leftmost-prefix orderQuerying only the second column (`created_at`) skips the index unless it has its own index
Covering Index (`INCLUDE`)Hot read queries answered 100% from index leaf pages without touching the main heap tableWider leaf entries reduce tree fan-out and increase RAM/SSD footprint
Partial Index (`WHERE status = ...`)Indexing only the tiny active slice (e.g., 2% pending orders) instead of 98% archived rowsPlanner only uses the partial index when the query’s `WHERE` predicate matches the index filter

Step-by-Step Architectural Breakdown (10 Steps)

Full architectural walkthrough transcript and state transitions for Indexing & B-Trees.

STEP 01 · PROBLEMJump to step →

The unindexed wall: scanning 10,000,000 rows on disk

Your `orders` table just crossed **10 million rows** (~120,000 8 KB heap pages on SSD). A simple query—`SELECT * FROM orders WHERE customer_id = 84921`—has no index.

The database performs a **Sequential Full Table Scan**, reading all **120,000 disk pages** into memory just to find 4 matching rows—taking **1,850 ms** and pegging disk IOPS at 96%.

watch:A missing index looks invisible at 1,000 rows in local dev, then turns into a production outage overnight at 10 million rows.

Sequential ScanHeap Pages (8 KB)O(N) Read Cost
STEP 02 · SOLUTIONJump to step →

Add a B+ Tree Index: 120,000 pages → 3 page hops

Run `CREATE INDEX idx_orders_customer ON orders(customer_id)`. A **B+ Tree** packs **~500 sorted keys per 8 KB page**—meaning a tree just **3 levels tall** indexes `500³ = 125,000,000` rows!

The engine walks **Root (RAM) → Branch (RAM) → Leaf Page** to grab the exact row pointer, then fetches only the 1 matching heap page—slashing latency from **1,850 ms down to 4 ms**.

idea:Because B+ Tree root and branch pages stay hot in the buffer pool (RAM), finding a key among 100 million rows usually requires only 1–2 actual SSD reads.

B+ Tree Fan-Out (~500)Root → Branch → LeafO(log N) Lookup
STEP 03 · TECHNIQUEJump to step →

Why B+ Trees beat Hash Indexes: linked leaf range scans

Why don’t SQL databases use Hash Tables as their default index? A Hash Index can only answer exact `=` equality—it is completely useless for `created_at BETWEEN Jan 1 AND Jan 7` or `ORDER BY price LIMIT 20`.

In a **B+ Tree**, every leaf page links directly to its right neighbor (`Leaf 1 → Leaf 2 → Leaf 3`), so range queries seek once to the start key and **walk sideways sequentially** at full SSD speed.

idea:Doubly-linked B+ Tree leaves give you O(log N) seek PLUS sequential O(K) range scans and pre-sorted `ORDER BY` with zero in-memory sorting.

Linked Leaf PagesRange ScansIndex-Ordered Sort
STEP 04 · TECHNIQUEJump to step →

Composite Indexes: the Leftmost-Prefix & Equality-First rule

Your multi-tenant query runs `WHERE tenant_id = 7 AND created_at > "2026-01-01" ORDER BY created_at DESC`. Should you create `(created_at, tenant_id)` or **`(tenant_id, created_at)`**?

Always put **Equality columns first, Range/Sort columns last**: `(tenant_id, created_at)` jumps straight to tenant 7’s contiguous slice, already sorted by time. Reversing the order forces scanning every tenant’s January rows!

idea:Think of a phone book sorted by `(LastName, FirstName)`: finding `"Smith, Alice"` is instant, but finding every `"Alice"` across all last names requires scanning the entire book.

Composite Index OrderLeftmost PrefixEquality Before Range
STEP 05 · SOLUTIONJump to step →

Covering Indexes: skip the main table completely

Even with a B+ Tree index, fetching 200 matching orders still performs **200 random disk hops** into the heap table to grab `total_cents` and `status`.

Attach those extra payload columns directly onto the leaf with **`CREATE INDEX ... ON orders(customer_id, created_at) INCLUDE (total_cents, status)`**. The planner runs an **Index-Only Scan**—zero heap table lookups!

idea:Covering indexes eliminate random heap-fetch I/O completely for hot list endpoints, often cutting p99 latency in half again.

Covering IndexIndex-Only ScanINCLUDE Columns
STEP 06 · TRADE-OFFJump to step →

Why indexing a boolean column backfires (Selectivity)

Should you index `is_active` (true/false) or `gender`? Usually **no**! If 50% of 10 million rows have `is_active = true`, following 5 million random B-Tree pointers into the heap is **slower than just sequentially scanning the table**.

The query planner knows this via table statistics (histograms)—so it **ignores** your low-cardinality index on reads while still forcing every write to maintain it!

watch:B-Tree indexes shine on high selectivity (fetching <5–10% of rows). Indexing a 50/50 boolean wastes RAM and slows writes for zero read gain.

Index SelectivityCardinalityCost-Based Planner
STEP 07 · PROBLEMJump to step →

Over-indexing: how 12 indexes crush INSERT throughput

Over two years, engineers add **12 different B+ Tree indexes** onto `orders` to optimize every dashboard report. Now a single `INSERT INTO orders` must update the heap page **plus 12 separate B+ Trees**.

Random UUID keys make it even worse: inserts scatter across every leaf page, triggering constant **8 KB page splits**, dirtying buffer-pool RAM, and slashing write throughput by **6×**.

watch:Every index makes reads faster and writes slower. Periodically audit `pg_stat_user_indexes` and drop unused indexes—and prefer monotonic UUIDv7 over random UUIDv4 primary keys.

Write AmplificationB-Tree Page SplitsUUIDv4 vs UUIDv7
STEP 08 · SOLUTIONJump to step →

Partial Indexes: index only the 2% that actually matters

98% of your 10 million orders are `status = "completed"` and rarely touched by workers; only **2% (`200k rows`)** are `status = "pending"`.

Create a **Partial Index**: `CREATE INDEX idx_pending ON orders(created_at) WHERE status = "pending"`. It shrinks index size by **50×** (fits permanently in RAM) and skips index updates for completed rows completely.

idea:Partial indexes are one of the highest-leverage SQL tricks: 50× smaller RAM footprint, faster worker polling, and near-zero write amplification on historical data.

Partial IndexWorking Set in RAMPredicate Matching
STEP 09 · TECHNIQUEJump to step →

Clustered PKs & UUIDv7: sequential inserts without splits

In MySQL InnoDB (and SQL Server), the table itself IS a **Clustered B+ Tree** ordered by Primary Key. Inserting random **UUIDv4** keys jumps randomly across disk pages, splitting full pages constantly.

Switching to time-ordered **UUIDv7** (or Snowflake IDs) appends every new row cleanly to the **rightmost leaf page**—keeping leaf pages 98% packed and tripling sustained INSERT speed.

idea:If you need globally unique client-generated IDs without sacrificing B-Tree write locality, use time-sortable UUIDv7 instead of random UUIDv4.

Clustered IndexUUIDv7 LocalityRightmost Leaf Append
STEP 10 · RECAPJump to step →

Recap: the disciplined indexing playbook

Great indexing is surgical, not maximal: a **3-level B+ Tree** turns 10-million-row scans into 4 ms lookups, while bloated unused indexes quietly wreck write throughput.

Order composite indexes **Equality → Range/Sort**, use **Covering (`INCLUDE`)** for hot list queries, use **Partial Indexes** for tiny active slices, and always verify plans with **`EXPLAIN ANALYZE`**.

idea:Never guess whether an index helps—run `EXPLAIN (ANALYZE, BUFFERS)` and check actual shared page hits vs reads.

B+ TreesEquality → RangeCovering & PartialEXPLAIN ANALYZE

Related Production Deep-Dives & Simulators

Related Systems Course
Free · Verifiable Credential

FS-401RAG Engineer

Build evidence-carrying retrieval systems from ingestion and provenance through search reranking grounded generation and evaluation.

21 concepts~25h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.