15. B-Trees

The wide, shallow tree that databases and filesystems actually use

Binary search trees are elegant in theory. In RAM, an AVL tree or red-black tree gives you O(log2 n) lookups — and with a billion keys that's only about 30 comparisons. Sounds fast, right?

Now imagine your data lives on a spinning hard disk. Each tree level means following a pointer, and each pointer chase means a disk seek — roughly 10 milliseconds of waiting for a mechanical arm to swing into position. Thirty levels × 10 ms = 300 ms for a single lookup. That's an eternity.

The B-tree, invented by Rudolf Bayer and Edward McCreight at Boeing in 1972, solves this with a simple but powerful idea: make nodes wide instead of tall. Pack hundreds or thousands of keys into each node so the entire tree is only 3 or 4 levels deep. Every level is one disk read — and 3 disk reads is perfectly acceptable.

The Problem: Binary Trees Are Too Tall

Binary search tree vs. B-tree — height comparison

Binary search tree (1 billion keys):
  Height = log₂(1,000,000,000) ≈ 30 levels
  30 disk seeks × 10 ms = 300 ms per lookup

B-tree of order 1000 (1 billion keys): Height = log₁₀₀₀(1,000,000,000) = 3 levels 3 disk seeks × 10 ms = 30 ms per lookup

That's a 10× speedup — from unusable to practical.

The insight is that a single disk read fetches an entire block (typically 4 KB to 16 KB). A binary tree node wastes almost all of that block — it holds just one key and two pointers. A B-tree node fills the block with as many keys as it can, getting maximum value from every disk read.

What Is a B-Tree?

A B-tree of order m (also called the branching factor or maximum degree) is a self-balancing search tree with these properties:

B-Tree Properties (order m)

  • Every node has at most m children (and therefore at most m − 1 keys)
  • Every non-root internal node has at least ⌈m/2⌉ children
  • The root has at least 2 children (unless it is a leaf)
  • All leaves are at the same depth — the tree is perfectly balanced
  • Keys within each node are sorted in ascending order
  • A node with k keys has exactly k + 1 children (if it is internal)

The "at least half full" rule is what keeps the tree balanced without wasting too much space. Every node (except possibly the root) is guaranteed to be between 50% and 100% full.

Inside a B-Tree Node

A node of order 5 (max 4 keys, max 5 children)

        ┌─────────────────────────────┐
        │  10  │  20  │  35  │  50  │
        └──┬──────┬──────┬──────┬──────┬──┘
           │      │      │      │      │
           v      v      v      v      v
         <10   10-20  20-35  35-50   >50
      (child₀) (child₁) (child₂) (child₃) (child₄)

Each child pointer leads to a subtree whose keys fall in the range between the surrounding keys.

Think of it like a multi-way signpost. At each node, you do a small search among the keys (binary search or linear scan — the node fits in RAM once loaded) and then follow the appropriate child pointer down.

Search

Searching a B-tree is a natural generalization of binary search tree lookup:

  1. Start at the root

    Load the root node from disk into memory.

  2. Search within the node

    Use binary search to find the key among the node's sorted keys. If you find it, return it.

  3. Follow the right child pointer

    If the key is not in this node, binary search tells you which child subtree it must be in. Follow that pointer and repeat from step 1.

  4. Reach a leaf without finding the key

    If you reach a leaf and the key is not there, it does not exist in the tree.

Pseudocode: Search

function btree_search(node, key):
    i = 0
    while i < node.num_keys and key > node.keys[i]:
        i = i + 1

    if i < node.num_keys and key == node.keys[i]:
        return (node, i)          // found it

    if node.is_leaf:
        return NOT_FOUND

    disk_read(node.children[i])   // one disk seek
    return btree_search(node.children[i], key)

Each recursive call reads one node from disk. The total number of disk reads equals the height of the tree — and as we'll see, that height is remarkably small.

Insertion

Insertion is where B-trees get interesting. The key idea: always insert into a leaf, and if the leaf overflows, split it and push the middle key up to the parent.

  1. Find the correct leaf

    Use the search procedure to walk down to the leaf where the new key belongs.

  2. Insert the key into the leaf

    Add the key in sorted position. If the leaf now has fewer than m keys, you're done.

  3. Split if full

    If the node now has m keys (one too many), split it into two nodes at the median key. The left half gets the keys before the median, the right half gets the keys after it, and the median key is promoted to the parent.

  4. Propagate splits upward

    The parent might also overflow from receiving the promoted key. If so, split the parent too. In the worst case, splits propagate all the way up to the root.

  5. Split the root → tree grows taller

    If the root itself splits, create a new root with the median key and two children. This is the only way a B-tree grows taller — from the top, never from the bottom.

Pseudocode: Insertion

function btree_insert(tree, key):
    root = tree.root

    if root is full (has m-1 keys):
        new_root = allocate_node()
        new_root.is_leaf = false
        new_root.children[0] = root
        split_child(new_root, 0)
        tree.root = new_root
        insert_non_full(new_root, key)
    else:
        insert_non_full(root, key)

function insert_non_full(node, key):
    i = node.num_keys - 1

    if node.is_leaf:
        // Shift keys right and insert
        while i >= 0 and key < node.keys[i]:
            node.keys[i+1] = node.keys[i]
            i = i - 1
        node.keys[i+1] = key
        node.num_keys = node.num_keys + 1
        disk_write(node)
    else:
        // Find the child to descend into
        while i >= 0 and key < node.keys[i]:
            i = i - 1
        i = i + 1
        disk_read(node.children[i])

        if node.children[i] is full:
            split_child(node, i)
            if key > node.keys[i]:
                i = i + 1

        insert_non_full(node.children[i], key)

function split_child(parent, i):
    full_child = parent.children[i]
    new_child = allocate_node()
    mid = floor((m-1) / 2)

    // Move upper half of keys to new_child
    // Promote median key to parent
    // Update child pointers accordingly

Worked Example: Inserting 1–10 into Order 3

An order-3 B-tree has at most 3 children and at most 2 keys per node. Nodes must have at least ⌈3/2⌉ = 2 children (i.e. at least 1 key), except the root. Let's insert keys 1 through 10.

Step-by-step insertions

Insert 1:    [1]

Insert 2: [1, 2]

Insert 3: [1, 2] is full, insert 3 → overflow → split! Promote median (2) to new root.

             [2]
            /   \
         [1]     [3]

Insert 4: 4 goes into right leaf → [3, 4]

             [2]
            /   \
         [1]     [3, 4]

Insert 5: [3, 4] is full, insert 5 → overflow → split! Promote median (4) to root.

           [2, 4]
          /  |   \
       [1]  [3]  [5]

Insert 6: 6 goes into rightmost leaf → [5, 6]

           [2, 4]
          /  |   \
       [1]  [3]  [5, 6]

Insert 7: [5, 6] full, insert 7 → overflow → split! Promote 6 to root → but root [2, 4, 6] overflows! Split root! Promote median (4) to new root.

                [4]
               /   \
           [2]       [6]
          /   \     /   \
       [1]   [3] [5]   [7]

Insert 8: 8 goes into [7] → [7, 8]

                [4]
               /   \
           [2]       [6]
          /   \     /   \
       [1]   [3] [5]   [7, 8]

Insert 9: [7, 8] full, insert 9 → split! Promote 8 to parent → [6, 8]

                [4]
               /   \
           [2]       [6, 8]
          /   \     /  |   \
       [1]   [3] [5] [7]  [9]

Insert 10: 10 goes into [9] → [9, 10]

                [4]
               /   \
           [2]       [6, 8]
          /   \     /  |   \
       [1]   [3] [5] [7]  [9, 10]</code></pre>

Notice how the tree only grew taller twice (at insert 3 and insert 7), and both times it grew from the top. This is how B-trees maintain perfect balance — all leaves are always at the same depth.

Deletion

Deletion is the trickiest B-tree operation. When you remove a key, a node might end up with too few keys (fewer than ⌈m/2⌉ − 1). You need to fix this with either redistribution or merging.

  1. Key is in a leaf

    Simply remove it. If the leaf still has enough keys, you're done.

  2. Key is in an internal node

    Replace it with its in-order predecessor (largest key in the left child subtree) or in-order successor (smallest key in the right child subtree). Then delete that predecessor/successor from the leaf where it lives.

  3. Node underflows — try redistribution

    If after deletion a node has too few keys, check its siblings. If a sibling has a spare key, rotate: borrow a key from the sibling through the parent.

  4. Redistribution fails — merge

    If no sibling has a spare key, merge the underflowing node with a sibling, pulling down the separating key from the parent. The parent now has one fewer key — it might underflow too, propagating the merge upward.

Deletion example: remove 3 from our order-3 tree

Before:
                    [4]
                   /   \
               [2]       [6, 8]
              /   \     /  |   \
           [1]   [3] [5] [7]  [9, 10]

Delete 3 from leaf [3] → leaf becomes empty []! Underflow! Check sibling [1] — it has only 1 key, can't spare. Merge: combine [] and [1] with parent key 2 → [1, 2] Parent [4] lost its left child's separator, but [4] only had 1 key... Root underflow triggers further restructuring.

After (one possible result): [6] /
[2, 4] [8] / | \ /
[1] [5] ∅ [7] [9, 10]

(Exact result depends on implementation choices.)

Why deletion is complex

Insertion only needs to handle one case: overflow (split). Deletion must handle three cases: simple removal, redistribution from a sibling, and merging. Merges can cascade upward just like splits — in the worst case, all the way to the root, which is the only way a B-tree gets shorter.

B+ Trees: What Databases Actually Use

Most real database systems don't use plain B-trees. They use a variant called the B+ tree, which makes one important change:

B-tree vs. B+ tree

  • B-tree: Both internal nodes and leaves store data (key-value pairs)
  • B+ tree: Only leaves store data. Internal nodes store copies of keys as a pure routing index. Leaves are linked together in a doubly-linked list.

B+ tree structure

Internal nodes (index only — no data):

                [15 | 30]
               /    |    \

      [5 | 10]    [20 | 25]    [35 | 40]
      /  |  \      /  |  \      /  |  \

Leaf nodes (hold actual data, linked together):

[1,3,5]↔[6,8,10]↔[12,14,15]↔[18,20]↔[22,25]↔[28,30]↔[32,35]↔[38,40]↔[42,45]

Why do databases prefer B+ trees?

FeatureB-treeB+ tree
Range queries Require in-order traversal of the whole tree Just follow the leaf linked list — sequential reads
Internal node fan-out Lower (keys + data consume space) Higher (keys only, so more keys per node = shorter tree)
Full scans Must visit every node in the tree Just scan the leaf level sequentially
Cache behavior Data scattered across all levels Hot index nodes stay cached; data is only at leaves

The leaf linked list is the killer feature. When a database runs SELECT * FROM users WHERE age BETWEEN 25 AND 35, it searches the B+ tree to find age=25, then walks the linked list to age=35. That's the tree height in random reads plus a sequential scan — exactly what disks (and SSDs) are good at.

Height Analysis

The height of a B-tree determines the number of disk reads per operation. Let's work out how shallow these trees really are.

Height formula

For a B-tree of order m containing n keys, the height h satisfies:

h ≤ log⌈m/2⌉((n + 1) / 2)

In practice, this means the height is O(logm n).

Concrete numbers (order m = 1000)

Each internal node holds up to 999 keys and 1000 children.

Level 0 (root): 1 node → up to 999 keys Level 1: 1,000 nodes → up to 999,000 keys Level 2: 1,000,000 nodes → up to 999,000,000 keys Level 3: 1,000,000,000 nodes → up to ~10¹² keys

A billion keys? Only 3 levels deep. A trillion keys? Only 4 levels.

And the root node is almost always cached in RAM, so a lookup typically costs just 2 disk reads.

This is why B-trees dominate disk-based data structures. The logarithm base isn't 2 — it's the branching factor, which is typically in the hundreds or thousands.

Complexity

OperationDisk readsCPU time per nodeTotal
Search O(logm n) O(log m) with binary search O(logm n × log m) = O(log n)
Insert O(logm n) O(m) for splits O(logm n × m) worst case
Delete O(logm n) O(m) for merges O(logm n × m) worst case

The crucial metric for disk-based systems is disk reads, not total CPU time. And the number of disk reads is O(logm n) — with m in the hundreds, that's just a handful of reads for billions of keys.

Where B-Trees Are Used

SystemHow it uses B-trees
PostgreSQL Default index type is a B+ tree. Every CREATE INDEX builds one.
MySQL (InnoDB) Both the primary key (clustered index) and secondary indexes are B+ trees.
SQLite Tables and indexes are both stored as B-trees (B+ trees for tables, B-trees for indexes).
NTFS Windows' filesystem uses B+ trees for the Master File Table directory index.
ext4 Linux's filesystem uses extent trees (a form of B-tree) for file block mapping.
MongoDB Uses B-trees for its WiredTiger storage engine indexes.
Btrfs The Linux filesystem is literally named after B-trees — it's B-trees all the way down.

Key Takeaways

  • B-trees solve the disk access problem by packing many keys into wide nodes, keeping the tree extremely shallow
  • All leaves are at the same depth — the tree is always perfectly balanced
  • Nodes must be at least half full, guaranteeing good space utilization
  • Insertion splits overflowing nodes upward; deletion merges or redistributes underflowing nodes
  • The tree only grows or shrinks at the root, preserving the "all leaves at same depth" invariant
  • B+ trees (leaves hold data, internal nodes are pure index) are the variant databases actually use
  • With order 1000 and a billion keys, the tree is only 3 levels deep — 3 disk reads per lookup
  • B-trees are the backbone of PostgreSQL, MySQL, SQLite, NTFS, ext4, and countless other systems

Try It Yourself — B-Tree Visualizer

Choose an order (max children per node), then insert or delete keys to see the tree restructure in real time. Watch splits and merges happen as nodes overflow or underflow.

0
Total keys
0
Height
0
Nodes
5
Order

Search Path


B-trees are one of the most impactful data structures ever invented. They turn the economics of disk storage — where random access is expensive but sequential reads are cheap — into a design advantage. Every time you run a database query, open a file, or search an index, there's almost certainly a B-tree (or B+ tree) doing the heavy lifting underneath.