VIEW THIS AS

Auto mode follows the Route Engine until you choose a viewpoint.

YOU ARE HERE

ROUTE CHECK

CONNECTED TO

WHAT NEXT

Use the canonical route for this room, or HELP if you are unsure.

Why Mathematics? | B-Trees, Disk Pages, Node Fan-out and Logarithmic Search

Three secondary students review textbooks and notes together at a classroom table.

Why is mathematics important in databases and file systems? Because storage is not accessed one key at a time. Data moves in blocks or pages, and the cost of fetching a page can dominate the cost of comparing several keys already inside it. A B-tree responds by making each node wide: one page can hold many ordered separator keys and child pointers, producing a shallow balanced tree.

This mechanism is more than “a binary search tree with extra children.” Its fan-out is chosen from page capacity; its invariants keep every leaf at the same depth; insertion splits full nodes; deletion redistributes or merges underfull ones; and complexity should be interpreted in page transfers as well as comparisons.

This article develops those ideas with arithmetic, a small minimum-degree example and a realistic page-capacity calculation. It also explains B+ trees, range scans, write costs and the limits of the model. The goal is not to promise that every database uses one textbook layout. It is to show how mathematics connects storage geometry to reliable search.


Quick navigation


Why binary trees are too narrow for pages

A balanced binary search tree has height O(log₂N). That sounds efficient, but each node may contain one key and two pointers. If nodes occupy separate storage pages, a lookup could require one page read per level. For billions of records, dozens of random page accesses are costly even if the comparison count is modest.

A storage page might be 4 KiB, 8 KiB or another fixed size. Once a page is loaded, comparing many keys inside it is far cheaper than fetching many pages. A B-tree packs numerous keys and child references into one node and therefore has a much larger branching factor.

If each internal node has about F children, tree height is roughly log base F of the number of leaves. Raising the base can dramatically reduce levels.

A page-aware cost model

In the external-memory or I/O model, computation moves blocks of B data items between slower and faster memory. An operation’s important cost is the number of block transfers, not only arithmetic steps.

A B-tree node is designed to fit a block or page. Search transfers one node per level, then performs an in-page search among its keys. The tree turns page capacity into branching power.

Why “fewer levels” matters

Suppose fan-out is 200. Three branch levels can distinguish up to 200³=8,000,000 paths in a simplified full tree; four reach 1.6 billion. Real occupancy and leaf capacity modify the exact count, but the magnitude explains why wide trees are foundational.

Did You Know?

Rudolf Bayer and Edward McCreight introduced B-trees in their work on the organisation and maintenance of large ordered indexes. The “B” has inspired many informal expansions, but the safe historical practice is simply to call the structure a B-tree unless quoting a primary source about the name.


The B-tree invariants

There are several equivalent parameter conventions. To avoid ambiguity, use the minimum degree t convention, with t≥2.

Every non-root node contains at least t−1 keys and at most 2t−1 keys. An internal node with k keys has k+1 children. Therefore a non-root internal node has between t and 2t children. The root may have fewer keys and, if it is not a leaf, at least two children.

All leaves are at the same depth.

Within each node, keys are sorted. The child subtrees occupy ordered intervals separated by those keys.

Separator meaning

If a node contains keys k₁<k₂<…<kᵣ and children c₀,…,cᵣ, then:

  • every key in c₀ is less than k₁;
  • keys in cᵢ lie between kᵢ and kᵢ₊₁ for interior children;
  • every key in cᵣ is greater than kᵣ.

The exact equality and duplicate policy must be defined. A database index may store record identifiers alongside duplicate key values or use composite keys. A classroom set example can assume all keys are distinct.

Occupancy is not cosmetic

Minimum occupancy prevents a tree with one useful entry per enormous page. Maximum occupancy prevents overflow. Uniform leaf depth gives a worst-case path-length guarantee.

The root exception allows small trees. An empty tree can be one empty leaf; a one-key tree does not need t−1 keys beyond what it has.

B-tree versus binary search tree

A binary node has at most two children and one separator in its simplest form. A B-tree node has an ordered array of many separators and children. Rotations still have conceptual relatives, but insertion and deletion are organised around page-sized splits, redistribution and merges.


Search inside a wide node

At a node, find the first key greater than or equal to the target. If it equals the target, search succeeds in a set-style B-tree. Otherwise choose the child interval in which the target could occur.

The in-node search can be linear for a small node, binary for many fixed-size keys, or optimised with interpolation, SIMD comparisons or prefix compression in specialised systems. The best method depends on page layout and hardware.

A small search example

Suppose a root contains [10,20] with three children:

  • c₀ contains keys below 10;
  • c₁ contains keys between 10 and 20;
  • c₂ contains keys above 20.

Searching for 17 compares within the root and selects c₁. Searching for 20 finds the separator. Searching for 31 selects c₂.

Correctness invariant

At every descent, the chosen child’s interval is the only interval that can contain the target. The proof follows from sorted separators. Induction over levels establishes that reaching a leaf without equality means the key is absent.

Comparison cost and I/O cost

If a node has F children, binary search among its separators takes O(log F) comparisons. A root-to-leaf path of height h therefore takes O(h log F)=O(log N) comparisons in a simplified full tree. But it takes about h page visits. B-trees are especially valuable because h is small.

Frequently accessed upper levels may remain in memory, so a lookup can require even fewer physical reads. This is a workload and cache fact, not part of the pure structural guarantee.

Prefetch and locality

Contiguous key arrays make node scans cache-friendly. Child pointers or page identifiers select the next block. Layout affects performance even when two implementations satisfy identical mathematical invariants.


A complete insertion example

Use minimum degree t=2. Each non-root node can hold 1 to 3 keys. This is often called a 2–3–4 tree because internal nodes can have 2, 3 or 4 children.

Insert distinct keys in this order:

10, 20, 5, 6, 12, 30, 7, 17.

We use the top-down method: before descending into a full child, split it. This ensures insertion enters a nonfull node.

Insert 10, 20 and 5

The root is a leaf. It becomes [10], then [10,20], then [5,10,20]. Three keys are allowed, so no split is needed yet.

Insert 6

The root is full before the insertion. Split it around median 10. Promote 10 into a new root. The left leaf becomes [5], and the right leaf becomes [20].

Now descend left because 6<10 and insert 6, producing [5,6]. The tree has root [10] with leaves [5,6] and [20]. All leaves are at depth one.

Insert 12 and 30

Both exceed 10, so they enter the right leaf. It becomes [12,20] and then [12,20,30].

Insert 7

Seven is less than 10, so it enters [5,6], producing [5,6,7].

Insert 17

At root [10], the chosen right child [12,20,30] is full. Split it around median 20. Promote 20 to the root. The root becomes [10,20]; the split leaves are [12] and [30].

Seventeen lies between 10 and 20, so descend to [12] and insert it, producing [12,17].

The final tree is:

  • root keys [10,20];
  • left leaf [5,6,7];
  • middle leaf [12,17];
  • right leaf [30].

Verify every interval

The left leaf is below 10. The middle is above 10 and below 20. The right is above 20. Every leaf has between one and three keys and all leaves have equal depth.

This verification is as important as the insertion trace. A diagram that looks tidy can still violate a separator interval.

Why medians move upward

A full node has 2t−1 keys. Its median is the t-th key. Removing and promoting it leaves t−1 keys on each side, exactly the required minimum. The arithmetic is built into the capacity definition.


Why splits preserve correctness

Consider a full node containing sorted keys a₁<…<a₂ₜ₋₁. Promote aₜ. The left node keeps a₁ through aₜ₋₁; the right keeps aₜ₊₁ through a₂ₜ₋₁. Child pointers are divided consistently around the same median.

Ordering is preserved

All keys remaining on the left are less than aₜ, and all on the right are greater. Inserting aₜ into the parent places a new separator between the two child intervals.

Occupancy is preserved

Each new non-root node has t−1 keys, satisfying the minimum. Neither exceeds 2t−1. The parent gains one key and one child. The top-down algorithm ensures the parent being modified is nonfull, or handles a full root by creating a new one.

Leaf depth is preserved

Splitting a node creates two nodes at the same depth as the original. Their children, if any, remain one level lower. Splitting the root creates a new root and increases every old leaf’s depth by exactly one relative to it, so all leaves still share a depth.

Local repair yields global balance

Unlike an ordinary binary search tree, a B-tree does not allow a new leaf to appear at an arbitrary lower depth. Insertion always occurs in an existing leaf; splits propagate upward. The height changes only when the root splits.

Transactional caution

On persistent storage, a split modifies several pages and parent references. A crash between writes can corrupt the tree unless the system uses logging, copy-on-write, shadow paging or another recovery protocol. The structural proof assumes an atomic logical update; storage engines must implement that assumption safely.


Fan-out and height arithmetic

Page capacity turns bytes into branching factor. Suppose an internal page is 4,096 bytes, has a 16-byte header, uses 16-byte keys and 8-byte child page identifiers. With k keys there are k+1 child identifiers.

The byte requirement is

16 + 16k + 8(k+1) = 24 + 24k.

Require 24+24k≤4,096. Then 24k≤4,072, so k≤floor(4,072/24)=169. The page can hold at most 169 keys and 170 child pointers in this simplified fixed-width layout.

Why this is only an estimate

Real pages may include slot arrays, checksums, transaction metadata, variable-length keys, prefix compression, alignment, sibling links and free-space reserves. A pointer may be a page number rather than a memory address. The calculation is useful because assumptions are visible, not because 170 is universal.

Height with fan-out

If average fan-out is F and there are about L leaf pages, height above the leaves is approximately log_F L. With F=170 and L=1,000,000, note that 170²=28,900 and 170³=4,913,000. Roughly three internal branching steps can cover that many leaves in a dense simplified model.

Occupancy lowers effective fan-out. If nodes average 70% full, an average fan-out nearer 119 changes capacity. Even then the tree remains shallow.

Minimum occupancy gives a worst-case bound

For minimum degree t and height h≥1, the root has at least two children; each non-root internal node has at least t children; each leaf has at least t−1 keys. A standard lower-bound derivation gives at least 2t^{h−1} leaves and a number of keys growing on the order of t^h. Therefore h is O(log_t N).

The exact formula depends on whether height counts edges and how leaf records are modelled. State conventions before comparing.

Bigger pages are not automatically better

Larger nodes increase fan-out and may reduce height, but they transfer more unused bytes for small queries, take longer to search, and can increase write amplification. Storage hardware and workload determine the sweet spot.

Caching the root

The root and upper levels are tiny relative to the whole index and often remain cached. The effective number of slow reads can be height minus the cached prefix. This is one reason a four-level tree can behave like a one- or two-I/O structure in steady workloads.


Deletion, borrowing and merging

Deletion is more involved because removing a key can make a node fall below t−1 keys. Repair uses redistribution from a sibling or merging with a sibling and a parent separator.

A top-down deletion algorithm often ensures that the child entered has at least t keys, not merely the minimum t−1. Then one deletion leaves it valid, or repair happens before descent.

Borrow from a sibling

Suppose child C has t−1 keys and an adjacent sibling has at least t. Move the parent separator down into C, move the sibling’s nearest key up to replace that separator, and transfer the corresponding child pointer if the nodes are internal.

Ordering remains valid because the rotated keys cross the boundary in sorted order.

Merge

If both adjacent children have t−1 keys, merge them with the separating parent key. The merged node receives (t−1)+1+(t−1)=2t−1 keys, exactly the maximum capacity. The parent loses one key and one child.

This arithmetic mirrors the insertion split in reverse.

Delete an internal key

If target k is in an internal node, one method replaces it with its predecessor from the left child when that child has at least t keys, then deletes the predecessor below. Or use the successor from the right child. If both adjacent children are minimal, merge them with k and continue within the merged node.

Root contraction

If deletion leaves an internal root with zero keys and one child, make that child the new root. The height decreases by one, and all leaves remain equally deep.

Practical complications

Concurrent readers, variable-size entries, page latches, transactions and delayed merge policies complicate real deletion. Some storage engines leave space underused temporarily to avoid costly merges. The textbook invariants are a baseline, not a full database implementation.


B+ trees and range scans

Many database indexes use a B+ tree variant. Internal nodes primarily hold separators and child references; complete records or record pointers live in leaves. Leaves are commonly linked in key order.

Why concentrate data in leaves?

Internal separators can be smaller than full records, increasing fan-out. All record lookups end at a leaf, which gives a uniform path. Linked leaves make ordered scans efficient after the starting leaf is found.

Range query

To retrieve keys from a through b:

1. Search from the root to the first leaf position at or above a. 2. Scan forward within the leaf. 3. Follow leaf links while keys remain at most b.

The cost is the root-to-leaf search plus pages containing the output. If K records are returned and each leaf holds many records, the scan cost grows with output pages rather than repeating a root search for every key.

Separator copies

In a B+ tree, a separator in an internal node may be a copy or abbreviated boundary, while the authoritative record remains in a leaf. This differs from a textbook B-tree where records can occur in internal nodes. Terminology varies, so diagrams should state the chosen convention.

Clustered and secondary indexes

A clustered index influences physical or primary record organisation; a secondary index maps keys to row identifiers or primary keys. These are database design concepts layered on the tree. A B+ tree alone does not decide clustering semantics.

Range scans reveal the value of order

Hash tables offer excellent expected equality lookup but do not naturally provide sorted traversal. B+ trees preserve order and support predecessor, successor and range access. Workload determines which operation family matters.


Storage realities and limits

The simple model treats one node as one page and one page read as one cost. Modern systems add solid-state storage, operating-system caches, database buffer pools, compression and parallel I/O. The model remains useful, but measurements must reflect the platform.

Variable-length keys

Strings and composite keys vary in size, so key count is not a complete occupancy measure. Pages use byte occupancy, slot directories and sometimes prefix or suffix compression. A node may become full because of bytes even when it holds fewer than its nominal key count.

Write amplification

One logical insert can update a leaf, split pages and propagate separators. Journaling or copy-on-write may write additional data. A read-optimised fan-out does not eliminate write costs.

Concurrency

Multiple operations can traverse or modify overlapping paths. Systems use latches, lock coupling, optimistic validation or versioning. The balance invariant says what final states are valid; the concurrency protocol governs which intermediate states readers may observe.

Crash recovery

A correct in-memory algorithm can still fail on durable storage if writes reach media in an unfortunate order. Write-ahead logging records enough intent or before/after information to recover. Copy-on-write approaches construct new pages and atomically publish a new root or mapping.

Hot spots and skew

Monotonic inserts repeatedly touch the rightmost path. Caches may make that fast, but concurrency and page splits can concentrate there. Fill factors and append-aware designs manage the pattern.

Alternatives

Log-structured merge trees buffer and merge sorted runs, often favouring high write throughput at the cost of compaction and read complexity. Hash indexes favour equality. Tries exploit prefixes. Learned indexes model key distributions under particular assumptions. B-trees remain important, but not because alternatives disappeared.


What students are really learning

B-trees connect school mathematics to systems design in several durable ways.

Change the base of the logarithm

Binary trees emphasise log₂N. Wide nodes make log_FN operationally meaningful. Students see that asymptotic notation can hide a base that matters greatly when each level triggers expensive I/O.

Translate bytes into structure

The page calculation converts a capacity inequality into maximum keys and fan-out. Units and off-by-one pointer counts matter. This is algebra serving architecture.

Maintain interval invariants

Sorted separators partition the key space. Search, split, borrow and merge must preserve those intervals. A local update has a global ordering consequence.

Prove balance constructively

All leaves remain at equal depth because insertion splits existing nodes and root splits raise the whole tree uniformly. Balance is not hoped for statistically; it is maintained by rules.

Optimise the costly resource

The design minimises page transfers, not merely comparisons. This teaches students to choose a cost model that matches the machine and problem.

Separate abstract and physical layers

An abstract B-tree has keys and children. A storage page has headers, slots, checksums and recovery metadata. Good engineering connects the layers without confusing them.


A practical learning path

Start with a t=2 paper tree. Use cards for keys and boxes for nodes. Enforce one to three keys per non-root box. Insert the sequence from this article and physically split boxes.

Given a valid tree, search for present and absent keys. At each node, write the interval selected. This builds the separator invariant before mutation complexity.

Stage 2: insertion

Implement top-down insertion with arrays. Before every descent, split a full child. After each insert, check sorted keys, child counts, occupancy and equal leaf depth.

Stage 3: deletion

Add borrowing, merging and root contraction. Test every deletion order for small key sets against a reference ordered set.

Stage 4: page arithmetic

Design a hypothetical page format. Vary page size, key width, pointer width and header. Calculate capacity and plot approximate height for growing N. Then explain which omitted overhead would reduce capacity.

Stage 5: benchmark models

Count node visits separately from comparisons. Simulate a cache that holds the top two levels. Compare random equality lookups with long range scans.

Automated invariant checker

A checker should confirm:

  • keys within every node are strictly ordered under the chosen duplicate policy;
  • an internal node with k keys has k+1 children;
  • every non-root node respects minimum and maximum occupancy;
  • every descendant key falls within inherited lower and upper bounds;
  • all leaves have one common depth;
  • cached counts or links, if present, are consistent.

This checker makes experimentation safer and demonstrates how proof obligations become executable tests.

A bulk-loading investigation

Inserting an already sorted dataset one record at a time is not always the best way to build a new index. A bulk loader can pack sorted records into leaf pages, link those leaves, then construct upper separator levels. If it targets a chosen fill factor, it can leave room for later updates while producing a dense initial tree.

Students can compare two builds of the same sorted keys: repeated insertion and bottom-up bulk loading. Record page count, average occupancy, number of splits and final height. Both trees may satisfy the invariants, yet their construction work and free-space distribution differ.

This clarifies an important systems principle: an abstract data type can have more than one valid construction algorithm. Workload knowledge—here, that all keys are available in sorted order—can justify a specialised method.

Fill factor as a planned trade-off

A page filled to 100% uses space efficiently at build time but may split on its next insertion. Leaving 20% free increases initial page count yet can absorb updates. A fill factor is therefore not merely wasted space; it is capacity reserved for expected change.

The best setting depends on whether inserts are random, sequential or concentrated in particular key ranges. Claims about a universal optimum should be treated skeptically. Measure split rates, write amplification and scan density together.

Prefix separators and key compression

An internal separator may not need to store a full long key if a shorter prefix still distinguishes adjacent child ranges. Prefix compression can raise fan-out, but comparison logic and reconstruction become more complex. Variable-size separators also make capacity depend on the actual dataset.

Ask students to find the shortest distinguishing prefix between “mathematics” and “measurement.” A separator such as “mb” would be wrong because lexical boundaries need careful definition; a practical system derives a valid boundary according to its collation rules. The exercise exposes the connection among ordering, encoding and space.

Range-query cost with output

If a B+ tree has height h and a query returns records spanning r leaf pages, a useful page-access model is about h+r, with possible reductions from caching. Reporting only O(log N) ignores the unavoidable output scan. Reporting only r ignores the search needed to find its start.

The same two-part analysis appears in many algorithms: locate efficiently, then pay for the answer produced. It is a good antidote to complexity claims that hide output size.

Separate logical keys from physical pages

A page split changes page identifiers and parent links without changing the ordered set represented by the index. A concurrent cursor that remembers only a physical address may therefore become stale. Systems solve this with latches, versions, sibling navigation, restart rules or stable indirection according to their design.

This distinction is educationally useful. Logical correctness says the same key-value relation remains visible. Physical correctness says every page reference and recovery record leads to a valid representation. Both matter, but they are proved and tested at different layers.

Students can model the separation by assigning page numbers to paper nodes, then splitting a page while preserving the in-order key list. Check the abstract list first and the pointer graph second. The two checks catch different mistakes.


Guidance for parents and educators

Use a filing-cabinet analogy carefully. One drawer represents a page and holds several dividers. Opening a drawer is expensive; comparing divider labels while it is open is relatively cheap. The analogy motivates wide nodes without claiming storage is literally a cabinet.

Ask for arithmetic, not slogans

Give a 256-byte toy page, 8-byte keys, 4-byte child identifiers and a 16-byte header. Ask how many keys fit when k keys require k+1 children. Let students discover the extra pointer term.

Make students state the convention

“Order” can mean maximum children in one source and minimum degree in another. Require a sentence defining t, key limits and root exceptions before any calculation. This prevents correct formulas being applied to incompatible notation.

Compare workloads

Ask whether the application needs equality, ranges, ordered iteration, heavy writes or compact static storage. A B-tree is a candidate, not a universal answer.

Treat systems claims responsibly

Avoid saying B-trees make databases fast by themselves. Buffer pools, query planning, concurrency, logging, storage devices and data distribution all contribute. The tree provides an ordered page index with bounded height.

Keep pathways open

The topic supports interest in databases, operating systems and software engineering, but its broader benefits are algebraic modelling, logarithms, invariant reasoning and evidence. No single topic guarantees a career or outcome.

For random expected balance in memory, see Why Mathematics? | Treaps, Random Priorities, Rotations and Expected Balance. For compact ordered integers, read Why Mathematics? | Elias–Fano Encoding, Monotone Sequences, Bitvectors and Succinct Indexes.


Frequently asked questions

Is a B-tree binary?

No. A node can have many children. That high fan-out is central to reducing storage-page levels.

What does the B stand for?

Popular explanations differ. Unless using a definitive historical statement, it is safest to use the established name without expanding it.

Are B-trees always stored on disk?

No. They can be used in memory, and pages may live on SSDs or other media. Their wide-node design is especially motivated by block-oriented memory hierarchies.

What is the difference between a B-tree and B+ tree?

In a common B+ tree layout, full records or record references are stored in leaves, internal nodes hold separators, and leaves are linked for scans. Textbook conventions vary, so inspect the definition in use.

Why are all leaves at the same depth?

Insertion and deletion preserve that invariant through splits, merges and root changes. It gives a uniform worst-case path length.

Is search O(log N)?

Yes under standard balance and occupancy assumptions, but the more revealing storage cost is O(log_F N) page levels for fan-out F, plus in-page work.

Why not make one gigantic root?

It must fit accessible memory or a page layout, and searching or updating it has costs. Nodes are sized to the storage hierarchy and concurrency design.

What happens with duplicate keys?

The implementation defines a policy: combine with record identifiers, store lists, or use composite keys. Our worked example assumes distinct keys.

Does a split lose the median record?

No. In a textbook B-tree it moves into the parent. In B+ tree variants, separator copying and leaf record retention can differ.

Is a B-tree always faster than hashing?

No. Hash indexes can excel at equality lookups. B-trees preserve order and support range queries. Memory, persistence and workload decide.


Useful next reading

The primary historical source is Rudolf Bayer and Edward McCreight’s Organization and Maintenance of Large Ordered Indexes, published in *Acta Informatica* in 1972. It establishes the family’s original context; contemporary database implementations add decades of engineering.

For the external-memory model that formalises block transfers, read Aggarwal and Vitter’s The Input/Output Complexity of Sorting and Related Problems. For PostgreSQL’s current implementation-facing documentation, consult the official B-Tree Indexes chapter while remembering that product details can change by version.

To compare a bounded-universe ordered structure, continue with this batch’s van Emde Boas article after publication. For an existing probabilistic dictionary mechanism, see Why Mathematics? | Cuckoo Hashing, Two Choices, Displacement Paths and Constant-Time Lookup. For integrity-oriented trees rather than ordered page indexes, read Why Mathematics? | Merkle Trees, Hash Hierarchies and Verifiable Data.

The central insight is beautifully practical: a page is not just a container after the algorithm is designed. Its capacity determines fan-out; fan-out determines height; height influences I/O; and update rules preserve the intervals and occupancy that make search reliable. Mathematics connects all four layers.