← The Ledger
Vol. I, No. 25 · Storage Structures

The B-Tree

A search tree with page-sized nodes, so that a billion keys sit three or four reads from the root.

Written by Khushal Agrawal

loading…

Pages, Not Nodes

A B-tree is a balanced search tree whose node is a disk page. Storage moves data in blocks of 4 to 16 KB, and reading one byte costs the same as reading the whole block, so each node holds as many keys as fit in a page. With 8 KB pages and 16-byte entries that is about 500 keys and 501 children per node.

level 1   1 page                    root
level 2   500 pages       ~4 MB     cached
level 3   250,000 pages   ~2 GB
level 4   125,000,000 leaf pages    ~6 x 10^10 keys

Height is O(log_B n) for fanout B, not O(log₂ n). Four levels address tens of billions of keys, and with the top two levels in memory a point lookup costs two page reads.

The Node Layout

A node with n keys stored in sorted order has n + 1 children, and child i holds exactly the keys between key[i-1] and key[i]. The keys act as signposts that divide the key range among the children.

typedef struct node {
    int          n;             // keys in use
    bool         leaf;
    key_t        key[2*T - 1];  // sorted
    value_t      val[2*T - 1];
    struct node *c[2*T];        // c[i] holds keys in (key[i-1], key[i])
} node;

The balance invariant is on occupancy: every node except the root holds between T − 1 and 2T − 1 keys for a minimum degree T, and every leaf sits at the same depth. Half-full pages are the price of never rebalancing by rotation.

Splitting A Full Node

Insertion always lands in a leaf. When the node it must enter already holds 2T − 1 keys, the node is split around its median: the lower half stays, the upper half moves to a new sibling, and the median rises into the parent as the separator between them.

void split_child(node *x, int i) {            // x->c[i] is full
    node *y = x->c[i], *z = new_node(y->leaf);
    z->n = y->n = T - 1;
    copy_keys(z, 0, y, T, T - 1);             // upper half to the sibling
    if (!y->leaf) copy_children(z, 0, y, T, T);
    shift_right(x, i);                        // open slot i in the parent
    x->c[i + 1] = z;
    x->key[i]   = y->key[T - 1];              // the median moves up
    x->n++;
}

Splitting each full node on the way down guarantees the parent has room for the median, so insertion never has to walk back up.

Growth At The Root

The only node that can split without a parent to receive the median is the root. Splitting it creates a new root holding one key, and that is the only way the tree ever gets taller.

void insert(tree *t, key_t k) {
    node *r = t->root;
    if (r->n == 2*T - 1) {             // full root: height grows here
        node *s = new_node(false);
        s->c[0] = r;
        t->root = s;
        split_child(s, 0);
        r = s;
    }
    insert_nonfull(r, k);              // descends, splitting full children
}

Because growth happens at the top, every leaf gains a level at the same moment and all leaves stay at equal depth. With occupancy at least T children per internal node, height is at most log_T((n + 1) / 2).

Deletion: Borrow And Merge

Deletion mirrors insertion. Before descending into a child that holds only T − 1 keys, the algorithm brings it up to T, so the eventual removal cannot leave it under-full.

void ensure_t_keys(node *x, int i) {
    if (x->c[i]->n >= T) return;
    if (i > 0 && x->c[i-1]->n >= T)          borrow_from_left(x, i);
    else if (i < x->n && x->c[i+1]->n >= T)  borrow_from_right(x, i);
    else if (i < x->n)                        merge(x, i);     // c[i] + key[i] + c[i+1]
    else                                      merge(x, i - 1);
}

A borrow rotates through the parent: the separator comes down into the child and the sibling's nearest key goes up to replace it. A merge pulls the separator down between two minimal siblings. Merging the root's last two children empties the root, and the tree loses a level.

B+ Tree Leaves

A B+ tree stores records only in the leaves. Internal nodes keep separator keys and child pointers and nothing else, and each leaf links to its right sibling.

typedef struct inner {
    int    n;
    key_t  sep[F - 1];          // routing copies, not records
    void  *child[F];
} inner;

typedef struct leaf {
    int          n;
    key_t        key[L];
    value_t      val[L];
    struct leaf *next;          // right sibling
} leaf;

With no values inside, an internal page fits more separators, so fanout rises and the tree gets shorter. A leaf split copies the new right leaf's first key up as a separator, while an inner split moves its median up. Every lookup therefore ends at a leaf.

Range Scans

The sibling links make a range query one descent followed by a sequential walk. Find the leaf where the lower bound would live, then follow next pointers until a key passes the upper bound.

leaf *l = find_leaf(root, lo);
int i = lower_bound(l->key, l->n, lo);
for (; l; l = l->next, i = 0)
    for (; i < l->n; i++) {
        if (l->key[i] > hi) return;
        emit(l->key[i], l->val[i]);
    }

The cost is O(log_B n + k/B) page reads for k results. A plain B-tree has to climb back through internal nodes to continue an in-order walk; the linked leaves skip that, and when leaves were written in key order the walk is also a sequential read.

Separator Truncation

A separator only has to route searches correctly; it does not have to be a real key. Between a left leaf ending in "smith" and a right leaf starting with "smyth", any string s with "smith" < s <= "smyth" works, and the shortest is "smy".

// length of the shortest prefix of b that is still > a
size_t sep_len(const char *a, const char *b) {   // a < b
    size_t i = 0;
    while (a[i] == b[i]) i++;
    return i + 1;                // one byte past the common prefix
}

Bayer and Unterauer's 1977 prefix B-tree introduced the idea. Shorter separators mean more of them per internal page, higher fanout, and fewer levels. PostgreSQL added suffix truncation of pivot tuples to its B-tree in version 12.

Bulk Loading

Inserting n sorted keys one at a time splits every page on the way and leaves them half full. Building from sorted input bottom-up is faster and produces a denser tree.

level = pack_leaves(sorted, n, fill);   // write leaves left to right
while (level.count > 1)
    level = pack_inner(level, fill);    // first key of each child is its separator
root = level.page[0];

Each page is written once, sequentially, filled to a chosen fraction. The fill factor leaves room for later inserts so the first ones do not immediately split every page. PostgreSQL's CREATE INDEX sorts the table's keys and builds this way, filling leaves to 90% by default.

Latch Crabbing

Many threads descend the same tree, and a split can change every node from a leaf up to the root. Latch crabbing holds latches only on the part of the path that a split could still reach: latch the child, and if the child cannot split, release every ancestor.

latch(root);  path = [root];
for (n = root; !n->leaf; n = c) {
    c = child_for(n, k);
    latch(c);
    if (c->n < MAX_KEYS) {        // c has room: a split stops here
        unlatch_all(path);
        path = [];
    }
    path.push(c);
}

Readers release the parent as soon as the child is latched. Writers usually hold one or two latches, but the root's latch is taken by every operation, which makes it the contention point.

Copy-On-Write B-Trees

A copy-on-write B-tree never modifies a page in place. An update writes a new copy of the leaf, then a new copy of its parent pointing at it, and so on up to a new root, then switches one root pointer. Pages the old root still references are left untouched.

This is the path copying of persistent structures applied to disk pages. Readers that started from the old root see a consistent snapshot with no locks, and a crash before the pointer switch leaves the old tree intact, so no write-ahead log is required. The cost is writing O(log_B n) pages per update and reclaiming the unreferenced ones once no reader holds them.

B-Tree Vs LSM Tree

A B-tree updates data in place: one random page read and one page write per change, plus a write-ahead log record. Changing a 100-byte row rewrites an 8 KB page, which is the write amplification B-trees pay. An LSM tree buffers writes in memory and flushes sorted files sequentially, then merges them in background compaction.

Reads reverse the trade. A B-tree point lookup is one root-to-leaf path, and a range scan reads contiguous leaves. An LSM lookup may consult several levels, mitigated by a Bloom filter per file, and its range scans merge every level. Read-heavy and update-in-place workloads favour the B-tree; ingest-heavy workloads on flash favour the LSM tree.

Engineering Trade-offs

A B-tree gives O(log_B n) page reads per lookup, insert, and delete in the worst case, ordered iteration, range scans at sequential speed through linked leaves, and a height of three or four for any table that fits on one machine. Its balance is maintained by local splits and merges, never by rotations that cascade across the tree.

The costs are pages that sit between half and fully occupied, write amplification from rewriting a whole page per change, latch contention at the top of the tree, and a write path that needs a log or copy-on-write for crash safety. For data that fits in memory, a skip list or a cache-tuned radix tree can be faster, since page-sized nodes buy little without a disk.

Applications

InnoDB stores every MySQL table as a B+ tree clustered on the primary key, with full rows in the 16 KB leaf pages; each secondary index is a separate B+ tree whose leaves hold the primary-key value, so a secondary lookup traverses two trees. SQLite uses both variants in one file: tables are B+ trees keyed by 64-bit rowid with data only in the leaves, and indexes are B-trees that keep keys in interior pages too.

PostgreSQL's nbtree access method is a Lehman-Yao B-link tree with high keys and right-links, used for every default index and every primary-key and unique constraint. LMDB is a copy-on-write B+ tree in a memory-mapped file; readers run against a snapshot root without locks while a single writer builds the next one.

Summary

A B-tree sizes its nodes to disk pages so that fanout is in the hundreds and height stays at three or four. Search binary-searches inside each page and descends; insertion splits full nodes around the median and grows only at the root; deletion borrows from or merges with a sibling and shrinks only at the root. The B+ variant moves records to linked leaves, raising fanout and turning range queries into sequential scans.

Every operation costs O(log_B n) page accesses in the worst case. The costs are partially empty pages, a full page write for each small change, and coordination for concurrency and crash safety, handled in practice by B-link right-links, write-ahead logs, or copy-on-write roots.

The B-Tree: A search tree with page-sized nodes, so that a billion keys sit three or four reads from the root
The B-Tree — A search tree with page-sized nodes, so that a billion keys sit three or four reads from the root.

Sources & further reading

Every claim in this chapter traces to a primary source. Peer-reviewed papers are linked by DOI.

Primary sources

  1. Bayer, R., & McCreight, E. (1972). Organization and maintenance of large ordered indexes. Acta Informatica, 1(3), 173–189. doi.org/10.1007/BF00288683
  2. Comer, D. (1979). The ubiquitous B-tree. ACM Computing Surveys, 11(2), 121–137. doi.org/10.1145/356770.356776
  3. Bayer, R., & Unterauer, K. (1977). Prefix B-trees. ACM Transactions on Database Systems, 2(1), 11–26. doi.org/10.1145/320521.320530
  4. Bayer, R., & Schkolnick, M. (1977). Concurrency of operations on B-trees. Acta Informatica, 9(1), 1–21. doi.org/10.1007/BF00263762
  5. Lehman, P. L., & Yao, S. B. (1981). Efficient locking for concurrent operations on B-trees. ACM Transactions on Database Systems, 6(4), 650–670. doi.org/10.1145/319628.319663
  6. Cormen, T. H., Leiserson, C. E., Rivest, R. L., & Stein, C. (2009). Introduction to Algorithms (3rd ed.), ch. 18. MIT Press. mitpress.mit.edu/9780262033848/introduction-to-algorithms/

Applications and implementations

  1. PostgreSQL Global Development Group. src/backend/access/nbtree/README — Lehman-Yao B-link implementation. github.com/postgres/postgres/blob/master/src/backend/access/nbtree/README
  2. PostgreSQL Documentation. B-Tree indexes: deduplication and suffix truncation. www.postgresql.org/docs/current/btree.html
  3. MySQL. InnoDB clustered and secondary indexes. dev.mysql.com/doc/refman/8.0/en/innodb-index-types.html
  4. SQLite. Database file format — table B-trees and index B-trees. www.sqlite.org/fileformat2.html
  5. Chu, H. (2011). MDB: A memory-mapped database and backend for OpenLDAP. http://www.lmdb.tech/media/20111010LinuxCon%20-%20LMDB.pdf

Enjoyed this chapter? Support The Ledger.