B-Trees & B+ Trees
Wide nodes for disks and databases.
Reading one byte from an SSD costs as much as reading its whole page of several kilobytes, and one seek on a hard disk takes as long as millions of comparisons in memory. B-trees are built around that fact: every node fills a block, so a billion keys fit in a tree of height 3. More than fifty years after Bayer and McCreight, they are still the index inside most relational databases and many file systems.
What you’ll learn
- Define B-trees of minimum degree , prove , and implement insertion that splits full nodes on the way down.
- Prove that insertions cause at most splits, and that every comparison-based search needs block transfers, which B-trees match.
- Explain B+ trees, bulk loading, B*-trees, and how latch crabbing and B-link trees let many threads share one B-tree.
- Compare the write-optimized -trees and LSM-trees, and cache-oblivious B-trees, by their trade-offs in block transfers.
Definition, height and one-pass insertion
In a B-tree of height , the root has at least 2 children, and every other internal node at least , so level holds at least nodes:
Each of those nodes holds at least keys, and the root at least 1:
Solve for . A search reads nodes and, with binary search inside each node, makes comparisons per node, comparisons in all:
Insertion puts the new key into a leaf. If the leaf is full, it must split around its median key, which moves up into the parent, and the parent may be full too. CLRS avoids that cascade with a single downward pass: it splits every full node it meets on the way down, so the parent of any split always has room. The tree grows only when the root splits, and then it grows at the top, so all leaves stay at the same depth.
import bisect
class BNode:
def __init__(self, leaf=True):
self.keys, self.kids, self.leaf = [], [], leaf
def split_child(x, i, t): # x.kids[i] is full: 2t - 1 keys
y, z = x.kids[i], BNode(x.kids[i].leaf)
x.keys.insert(i, y.keys[t - 1]) # the median key moves up into x
z.keys, y.keys = y.keys[t:], y.keys[:t - 1]
if not y.leaf:
z.kids, y.kids = y.kids[t:], y.kids[:t]
x.kids.insert(i + 1, z)
def insert(root, key, t): # one pass down; returns the root
if len(root.keys) == 2 * t - 1: # a full root splits: the tree grows at the top
new = BNode(leaf=False)
new.kids = [root]
split_child(new, 0, t)
root = new
x = root
while not x.leaf:
i = bisect.bisect_left(x.keys, key)
if len(x.kids[i].keys) == 2 * t - 1:
split_child(x, i, t) # never descend into a full node
if key > x.keys[i]:
i += 1
x = x.kids[i]
bisect.insort(x.keys, key)
return rootCLRS's B-TREE-INSERT. Tested for with thousands of random keys: every non-root node keeps to keys, all leaves stay at one depth, the height respects the bound, and the split count respects the theorem below.
Every split creates one new node, and a root split creates a second one, the new root. So after splits the tree has at least nodes:
Every node except the root holds at least keys and the root at least 1, so the keys fill at most this many nodes:
Hence . Each split rewrites a constant number of nodes, so insertions cost node reads for the descent plus an amortized node writes for splitting:
In a B-tree of minimum degree that starts empty, at least how many insertions are there per split, on average, for every sequence of insertions?
Show the answer
99
At most splits for insertions, so at least 99 insertions per split on average. With nodes this wide, almost every insertion just adds a key to a leaf.
Deletion, and the I/O lower bound
CLRS deletes in one downward pass as well. Before descending into a child that holds only keys, it gives that child an extra key: by a transfer from a sibling with at least keys, rotating a key through the parent, or by merging the child with a sibling that has keys and with the separating key from the parent, which yields a full node of keys. A key in an internal node is replaced by its predecessor or successor from a leaf. When the root loses its last key, its only child becomes the root, and the height drops by one.
Why does CLRS split full nodes on the way down, instead of inserting into the leaf first and splitting upward as needed?
- To keep all leaves at the same depth
- So that the parent of any split always has room for the median: the insertion finishes in one downward pass and never revisits nodes on the way back up
- Because a leaf can never be split
- To make the tree shorter than splitting upward would
Show the answer
B. So that the parent of any split always has room for the median: the insertion finishes in one downward pass and never revisits nodes on the way back up
Splitting upward also works, but it may have to walk back up the path and re-read nodes that were already evicted from memory, and it complicates locking. Proactive splitting guarantees room in every parent, at the cost of occasionally splitting a node that would not have needed it.
The answer is the query's position among the sorted keys, one of gaps. An adversary keeps track of the gaps still consistent with everything the algorithm has seen, and answers every comparison so as to keep the largest group of them:
A block read reveals at most new keys, which cut the current candidate gaps into at most groups; comparisons with keys already in memory add no new information. The adversary keeps the largest group, so after reads
The search can stop only when a single gap remains:
A binary search tree whose nodes lie in different blocks reads blocks, a factor of about more than a B-tree:
B+ trees in real systems
A B+ tree keeps every record in the leaves; internal nodes hold only separator keys that route searches, copies of keys or even shortened prefixes of them. Separators are small, so internal nodes have a larger fan-out and the upper levels are small enough to stay in memory. The leaves are linked in key order, so a range query descends once and then reads consecutive leaves: block reads for results.
Bulk loading. Building a B+ tree by separate insertions costs block reads in the worst case. Bulk loading sorts the records first, with an external merge sort in transfers, then fills the leaves from left to right up to a chosen fill factor and builds each upper level from the one below, in further transfers. Databases do this when they create an index on an existing table.
B*-trees. Knuth's variant delays splits: an overfull node first shifts keys into a sibling, and when both are full, two nodes split into three. Every node except the root stays at least two-thirds full instead of half full, which saves space and height.
Concurrency. A database B-tree is shared by many threads. With latch crabbing (Bayer & Schkolnick, 1977), an operation descends holding a node's latch until the child below is known to be safe, not full for an insertion and not minimal for a deletion, and then releases the latches above, so most operations hold only one or two at a time. B-link trees (Lehman & Yao, 1981) give every node a pointer to its right sibling and an upper bound on its keys, its high key. A reader that reaches a node just split by someone else sees that its search key exceeds the high key and follows the right link, so readers need no locks along the path; PostgreSQL's B-tree indexes follow this design.
| System | Structure | Notes |
|---|---|---|
| InnoDB (MySQL) | B+ trees; each table is the B+ tree of its primary key, with the rows in the leaves | 16 KB pages by default |
| PostgreSQL | Lehman–Yao B-link trees for B-tree indexes | Rows live in a separate heap; index leaves point to them |
| SQLite | One B-tree per table and per index, all in a single file | Tables keep their rows in the leaves |
| File systems | Btrfs, XFS and others keep metadata in B-tree variants | Copy-on-write B-trees in Btrfs |
| In memory | Rust's BTreeMap, Abseil's btree_map, Linux's maple tree | Nodes sized for cache lines instead of disk pages |
Write-optimized and cache-oblivious descendants
A B-tree insertion reads and writes a whole root-to-leaf path, block transfers, to place one small record. Write-optimized structures batch insertions instead, and pay a little at query time.
Choose . Internal nodes have fan-out and use the rest of their block, about records, as a buffer of pending insertions. The height is
An insertion goes into the root's buffer. When a buffer fills, the node flushes the messages bound for its busiest child; by the pigeonhole principle that is at least messages, moved for block transfers. Each message therefore pays per level:
A search reads one root-to-leaf path and checks the buffers on it:
With , insertions become about times cheaper than in a B-tree, while searches cost twice as much; is a B-tree. Brodal and Fagerberg also proved lower bounds showing that this trade-off between insertions and searches is essentially the best possible for comparison-based external dictionaries:
LSM-trees (O'Neil, Cheng, Gawlick & O'Neil, 1996) push batching further. New records go into a sorted buffer in memory, which is written out as a sorted run when it fills; runs are merged in the background into progressively larger levels, so every write to disk is sequential. A lookup checks the buffer and then the levels, usually consulting a Bloom filter per run to skip runs that cannot contain the key. LevelDB, RocksDB and Cassandra are built on LSM-trees, while TokuDB and the research file system BetrFS used -trees.
Cache-oblivious B-trees (Bender, Demaine & Farach-Colton, 2000) need no block size at all. Storing a balanced binary tree in the van Emde Boas layout (cut the tree at half its height, store the top part recursively, then each bottom subtree recursively) makes every search cost transfers for every at once, so one layout is optimal at every level of the memory hierarchy; a dynamic version supports insertions and deletions too.
Learned indexes (Kraska, Beutel, Chi, Dean & Polyzotis, 2018) replace the upper levels of a B-tree by a model that predicts a key's position from its value, then search a small window around the prediction. They shine on read-mostly data with smooth key distributions.
Key takeaways
- A B-tree of minimum degree keeps to keys in every non-root node and all leaves at one depth, so : with , a billion keys fit in height 3.
- One-pass insertion splits full nodes on the way down, with at most splits for insertions; deletion transfers or merges on the way down.
- In the external-memory model every comparison-based search needs block transfers, and B-trees achieve ; B+ trees add linked leaves for range scans.
- -trees and LSM-trees make insertions far cheaper at a small cost in searches, B-link trees make B-trees concurrent, and cache-oblivious B-trees reach without knowing .
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Why does a B-tree's height grow only when its root splits?
- A split below the root adds a sibling on the same level; only a root split adds a level, above all the others, so every leaf stays at the same depth
- Only the root can ever be full
- Insertions take place at the root
- B-trees never split leaves
Show the answer
A. A split below the root adds a sibling on the same level; only a root split adds a level, above all the others, so every leaf stays at the same depth
Splitting a non-root node turns one node into two siblings at the same depth and pushes one key into the parent. Only when the root itself splits does a new root appear above it, adding one to the depth of every leaf at once.
What does the split bound say about insertions into an empty B-tree of minimum degree ?
- splits per insertion
- At most splits in total, so on average at most one split per insertions
- Exactly one split per insertion
- splits per insertion
Show the answer
B. At most splits in total, so on average at most one split per insertions
Each split creates a node, and keys cannot fill more than nodes when every non-root node holds at least keys.
A B+ tree answers a range query that returns records in block reads. Which feature produces the term?
- The records sit in leaves linked in key order, which the query reads one after another
- Binary search inside each node
- The separator keys in the internal nodes
- Keeping the root in memory
Show the answer
A. The records sit in leaves linked in key order, which the query reads one after another
After one descent to the first record, the query follows the leaf links, and each leaf it reads delivers about records.
Compared with a B-tree on the same block size, what does a -tree with trade?
- Both insertions and searches become cheaper
- Insertions become about times cheaper in amortized block transfers, while searches cost about twice as many
- Searches become cheaper and insertions more expensive
- It saves space but changes no running time
Show the answer
B. Insertions become about times cheaper in amortized block transfers, while searches cost about twice as many
With fan-out the tree is twice as tall, which doubles the search cost, but buffers move insertions down in batches of , so each insertion costs amortized transfers instead of .
Further reading
- R. Bayer & E. McCreight, "Organization and maintenance of large ordered indexes," Acta Informatica 1 (1972), 173–189.
- D. Comer, "The ubiquitous B-tree," ACM Computing Surveys 11(2) (1979), 121–137.
- P. L. Lehman & S. B. Yao, "Efficient locking for concurrent operations on B-trees," ACM Transactions on Database Systems 6(4) (1981), 650–670.
- G. S. Brodal & R. Fagerberg, "Lower bounds for external memory dictionaries," Proceedings of the 14th ACM-SIAM Symposium on Discrete Algorithms (SODA) (2003).
- M. A. Bender, E. D. Demaine & M. Farach-Colton, "Cache-oblivious B-trees," SIAM Journal on Computing 35(2) (2005); first presented at FOCS 2000.