To find one key among a billion, a balanced binary tree reads 30 pages from disk. A B-tree with 4 KB pages reads at most 5. Each page holds hundreds of keys, so the tree is short.
Pick a tree and drag the number of keys. Press Race and watch each lane read one page per step. Then we build, piece by piece, the node rules, the height bound, the page size, search, split, merge and the B+ tree that databases use.
You need a little Python and binary search trees (a key per node, smaller keys left). We build the rest from zero.
Based on Chapter 18, B-Trees, of Introduction to Algorithms (CLRS) by Cormen, Leiserson, Rivest and Stein. Previous: Amortized Analysis. Next: Fibonacci Heaps.
Worst-case pages on one root-to-leaf path, root included, nothing cached. The B-trees use 8-byte keys and pointers with a 24-byte page header (Chapter 3): t = 127 for 4 KB, t = 511 for 16 KB. The range runs from full pages to half-full pages. The 10 ms per read is an illustrative hard-disk figure.
Chapter 0
Price one search on a disk and see which cost decides the answer
You store a billion user records on disk. A user logs in and you must find one record by its ID. A balanced binary search tree finds it in 30 steps. That sounds fast.
Each step visits a different node, and each node sits in a different page. A page is the fixed block of bytes the disk reads in one go, often 4 KB. Reading one page from a hard disk takes about 10 ms. Thirty pages take 300 ms, for one login.
Each bar is the time to find one key among a billion. Warm is time spent reading pages; grey is time spent comparing keys. Switch the memory.
Illustrative orders of magnitude: 100 ns per page in RAM, 100 µs on an SSD, 10 ms on a hard disk, 1 ns per comparison. Binary tree: 30 pages, 30 comparisons. B-tree with 4 KB pages: 5 pages, binary search of at most 8 comparisons in each.
Flip to Hard disk. The binary tree spends 300 ms on reads and 30 ns on comparisons. The B-tree makes more comparisons, 40, and still wins by 250 ms, because it reads 5 pages instead of 30. On a disk, comparisons are free and page reads are the whole bill.
So a B-tree packs hundreds of keys into each node and sizes each node to one page. Each read then picks one child out of hundreds, not one out of two. The tree gets short, and short means few reads.
The failure. Symptom: an index that was fast in tests turns slow once the data outgrows RAM. Measure: count page reads per query, not CPU time; the database's I/O statistics show it. Fix: a structure whose height, not its comparison count, is small.
Chapter 1
Fix one number t and read off how full every node may be
A node holds the keys 10, 20 and 30 in sorted order. Below it hang four children: one for keys under 10, one for 10 to 20, one for 20 to 30, one for keys over 30. The keys are signposts. A search reads them and takes one of the four roads.
CLRS controls every node with one number, the minimum degree t, an integer of at least 2. Call the number of keys in a node k and its number of children c. Every node except the root obeys:
t minus one is at most k, which is at most two t minus one; and c equals k plus one.
Pick t. Every node but the root keeps at least t − 1 keys and at most 2t − 1. An internal node with k keys has k + 1 children. The root may hold as few as 1 key.
With t = 3, a node holds 2 to 5 keys and an internal node has 3 to 6 children. With t = 2, a node holds 1 to 3 keys: this is the 2-3-4 tree.
The boxes are the slots a node may use. Drag the keys up and down past both limits, then mark the node as the root.
Keys are illustrative multiples of 10.
Two more rules finish the definition. A node keeps its keys sorted, and every key in child i lies between the keys on either side of that road. And all leaves sit at the same depth. No other search tree in CLRS demands this; the B-tree keeps it by growing at the root, as Chapter 5 shows.
Why a lower limit? Without it, nodes could hold one key each, and the tree would be as tall as a binary tree. The floor keeps every non-root node about half full, and that caps the height.
The failure. Symptom: a hand-built tree passes every search test, then breaks on a delete. Measure: check every non-root node for k ≥ t − 1 and every leaf for the same depth. Fix: run that check after every operation while you debug.
Chapter 2
Build the thinnest legal tree and count the keys it must hold
How tall can a B-tree with n keys get? Turn the question around. Build the tree of height h with the fewest keys the rules allow. If even that tree holds many keys, no tree of n keys can be tall. The height h counts the edges on a path from the root down to a leaf.
Each row is one level, with its fewest nodes. The root holds 1 key; every other node holds t − 1. Drag t and h.
Exact counts from the rules of Chapter 1. Wide rows draw the first nodes and print the count.
Count level by level. The root has 1 key, so it has at least 2 children. Each of those has at least t children, so level 2 has at least 2t nodes. Level 3 has at least 2t², and level h at least 2th−1. Below the root, every node holds at least t − 1 keys. Add it up, and the sum of the levels collapses:
The middle step uses the geometric sum: (t − 1) times (1 + t + … + th−1) equals th − 1. So any tree of height h holds at least that many keys. Call the number of keys n.
n is at least two t to the h, minus one.
Raise t to the power h. Double it and subtract one. That is the fewest keys any tree of height h can hold, so the real n is at least that.
With t = 3 and h = 2: 2 × 9 − 1 = 17 keys at least. The thinnest tree has a 1-key root, 2 nodes of 2 keys, and 6 leaves of 2 keys: 1 + 4 + 12 = 17.
Solve for h. Add one, halve, and take the logarithm base t:
h is at most log base t of n plus one, over two.
Add one to n and halve it. Ask how many times you must multiply by t to reach that. Round down. No tree of n keys is taller.
With n = 1,000,000,000 and t = 127: (n + 1)/2 is 500,000,000, and log base 127 of that is 4.13. So h ≤ 4: at most 5 pages on any path. With t = 2 the same n allows h = 28.
| t | Largest h, n = 106 | Largest h, n = 109 |
|---|---|---|
| 2 (2-3-4 tree) | 18 | 28 |
| 3 | 11 | 18 |
| 127 (4 KB page) | 2 | 4 |
| 511 (16 KB page) | 2 | 3 |
The failure. Symptom: a capacity plan says "log n levels" and buys too little cache. Measure: use log base t, not base 2, and round down. Fix: plan with the bound for the worst case and with full nodes for the best.
Chapter 3
Fit keys and child pointers into a page and read off t
A disk does not read one key. It reads a whole page, so a node should fill exactly one page: every byte of that read then helps the search. In a real index, a child pointer is not a memory address. It is a page number, and following it means one disk read.
Call the page size P bytes, the key size sk and the pointer size sp. The header H is the fixed bytes that describe the page itself. A node with k keys stores k keys and k + 1 pointers. It must fit:
k times s-k, plus k plus one times s-p, plus H, is at most P.
Add the bytes of k keys, k + 1 pointers and the header. Raise k until the total passes P. The last k that fits is the most keys a page can hold.
With P = 4,096, sk = sp = 8 and H = 24: 16k + 32 ≤ 4,096, so k ≤ 254. A full node has 2t − 1 keys, an odd number, so t = 127 and a node holds at most 253 keys and 254 children.
The bar is one page. Grey is the header, warm the keys, blue the pointers. The dim end holds nothing. Change the page and the key size.
Pointers are 8 bytes and the header is 24 bytes, both illustrative. Real pages also store record offsets and free space; the formula keeps only what sets t.
Bigger keys mean fewer keys per page, a smaller t and a taller tree. A 32-byte key in a 4 KB page gives t = 51 and up to 5 levels below the root for a billion keys. This is why indexes on long strings are slower than indexes on integers.
The failure. Symptom: an index on a long text column is much deeper than one on an integer ID. Measure: divide the page size by the bytes per key plus pointer. Fix: index a shorter key, such as a fixed-size ID or a prefix.
Chapter 4
Read one page per level and pick the road inside it
Look for 45 in the tree below (t = 3). Read the root, [50]: 45 is smaller, so take road 0. Read [20, 35]: 45 is larger than both, so take road 2. Read the leaf [40, 45]: found. Three pages.
Pick a key and press Step. Each warm page is one disk read; the teal mark shows where the scan stopped. Try a missing key.
A toy tree with t = 3 and 17 keys: the thinnest tree of height 2 from Chapter 2. The device scans each page left to right, as CLRS does.
Inside a page, the search finds the first key that is not smaller than the target. If it equals the target, stop. If the page is a leaf, the key is missing. Otherwise read the child on that road and repeat. CLRS scans left to right; a real index uses binary search inside the page.
How many pages does a search read? Call the depth of the page where it stops d: the edges from the root to it. Call the pages read R.
R equals d plus one, which is at most h plus one.
Count the edges from the root to the page where the search stops, and add one for the root. That is R. Every leaf sits at depth h, so a miss always reads h + 1 pages.
45 stops in a leaf at d = 2, so R = 3. 50 stops at the root, d = 0, so R = 1. A missing 47 reads all 3 pages, h + 1 with h = 2.
pythondef search(x, k): # x: a node with .keys, .kids, .leaf while True: i = bisect_left(x.keys, k) # first key >= k, binary search in the page if i < len(x.keys) and x.keys[i] == k: return x, i # found if x.leaf: return None # missing x = disk_read(x.kids[i]) # one page read per level
The CPU work is small. With binary search, each page of 253 keys costs at most 8 comparisons. CLRS counts the left-to-right scan as O(t) per page, O(t logt n) in total. The page reads are O(logt n).
The failure. Symptom: a lookup is slow although the tree is short. Measure: profile the time inside one page. Fix: a linear scan of 1,021 keys is wasteful; switch to binary search inside the page.
Chapter 5
Split every full page on the way down, so the leaf always has room
A new key always goes into a leaf. A binary tree hangs a new leaf below the old one, but that would put one leaf deeper than the others. So the key goes into an existing leaf. If that leaf is full, it must split.
A split takes a full node of 2t − 1 keys. The middle key, the median, moves up into the parent. The keys left of it stay; the keys right of it move to a new node.
Two t minus one equals t minus one, plus one, plus t minus one.
Take the middle key of a full node up to the parent. Each half keeps t − 1 keys, exactly the minimum, so both halves are legal.
With t = 3 the full node [10, 20, 30, 40, 50] splits into [10, 20], the median 30 and [40, 50]: 5 = 2 + 1 + 2. The parent gains one key and one child.
The parent gains a key, so it must not be full. CLRS makes sure of that with one trick: on the way down, split every full node you meet, before you enter it. The parent of any split is then never full. When the insert reaches the leaf, the leaf has room. One pass down, never back up.
Press Step to run each insert one move at a time. Red is a full page about to split; purple is the median moving up.
t = 3, keys 10, 20, 30, 40, 50, 60, 70, 80, 5, 15, 90. Page counts: every page touched is a read, every page changed is a write; pages made in this insert are not read.
Watch three moments. Inserting 60 finds the root full, so the root splits and 30 becomes a new root: the tree grows one level, at the top. Inserting 80 fills the right leaf but does not split it; only the next visit will. Inserting 90 meets that full leaf on the way down and splits it, and 60 moves up beside 30.
The only way the tree grows taller is a root split. A new level appears above all the leaves at once, so all leaves stay at the same depth. A split writes 3 pages: the old node, the new node and the parent.
The failure. Symptom: inserts of sorted keys leave the pages half empty and the index twice its size. Measure: divide the keys by the slots in all pages. Fix: load sorted data with a bulk load, which fills pages in order, instead of inserting one key at a time.
Chapter 6
Make every page you enter hold at least t keys, so a removal never leaves it too thin
Delete mirrors insert. Insert must never enter a full page. Delete must never enter a page with only t − 1 keys, because removing one key would break the floor. So on the way down, CLRS tops up every thin child before it enters. The one exception is the root.
There are three cases, named by where the key is.
| Case | Where the key is | What to do |
|---|---|---|
| 1 | in a leaf | remove it; the descent made sure the leaf has at least t keys |
| 2a | in an internal page, left child has ≥ t keys | replace it by its predecessor (largest key on the left), then delete that key below |
| 2b | in an internal page, right child has ≥ t keys | replace it by its successor (smallest key on the right), then delete that key below |
| 2c | in an internal page, both children have t − 1 | merge: left child + key + right child become one page of 2t − 1 keys, then delete from it |
| 3a | below; the next child has t − 1, a sibling has ≥ t | rotate: a parent key moves down into the child, a sibling key moves up |
| 3b | below; the next child and its siblings have t − 1 | merge the child with a sibling, pulling the parent key down between them |
Pick a case and press Step. Teal is the key to delete; purple marks the pages that change.
Toy trees with t = 3, so every non-root page holds 2 to 5 keys. Rotations check the left sibling first.
Follow case 3a. Delete 40 from root [30, 60] over leaves [10, 20, 25], [40, 50], [70, 80]. The leaf [40, 50] has 2 keys, the minimum, and its left sibling has 3. So 30 moves down into the leaf and 25 moves up into the root: root [25, 60], leaf [30, 40, 50]. Now case 1 removes 40, leaving [30, 50].
Follow case 3b. Delete 50 from root [30] over [10, 20] and [40, 50]. Both children hold 2 keys. Merge them with 30 between: 2 + 1 + 2 = 5 keys, the split equation run backwards. The root is now empty, so the merged page becomes the root and the tree is one level shorter. Trees grow at the root and shrink at the root.
The failure. Symptom: after many deletes, a check finds a page with fewer than t − 1 keys. Measure: run the node-rule check after every delete in a random test. Fix: the code removed a key and then tried to repair upward; top up each child before you enter it instead.
Chapter 7
Insert and delete any key, change t, and watch the height, the fill and the page counts
Here is the whole tree, with the insert of Chapter 5 and the delete of Chapter 6 running live. Every operation reports the pages it read and wrote and the case it used.
Type a key from 1 to 99 and press Insert or Delete, or use the presets. Changing t starts a fresh tree.
Keys 1 to 99, at most 20 in the tree on a phone and 48 on a wider screen, so the keys stay legible. Fill is the keys stored divided by the 2t − 1 slots of every page.
Try three things. Insert 1 to 20 with t = 2 and count the root splits as the height climbs. Then switch to t = 4 and do the same: fewer, wider pages and a shorter tree. Then delete keys until the root empties and the height drops.
Watch the fill. Sorted inserts always split the rightmost leaf, and every split leaves a half-full page behind. In our simulation of 20,000 inserts with t = 50, sorted keys filled 50% of the slots and random keys filled 70%. Sorted keys also split once per t − 1 inserts, here one split per 49.
| Operation | Pages read | Pages written |
|---|---|---|
| Search | at most h + 1 | 0 |
| Insert, no split | h + 1 | 1 |
| Insert with s splits | h + 1 | 3s + 1 at most |
| Delete | O(h), siblings included | O(h) |
The failure. Symptom: an index that only grows by appending keys, such as timestamps, is twice the size of the data's need. Measure: the fill reading of the workbench after Insert 1 to 20. Fix: fill pages fully when keys arrive in order; real systems add a rule for rightmost inserts.
Chapter 8
Keep records only in the leaves, chain the leaves, and a range becomes one descent and a walk
A query asks for every order placed between 10:00 and 10:05. That is a range query: find the first key, then every key after it until the end. In a CLRS B-tree the keys of a range are spread over leaves and internal pages, so the walk climbs up and down.
A B+ tree changes two things. Records live only in the leaves; internal pages hold only keys and child pointers, as signposts. And each leaf points to the next leaf, a leaf chain. When a leaf splits, a copy of its middle key goes up and the key itself stays in the leaf.
Drag the range ends. Pink keys are the answer; warm pages are read. Switch trees and compare the counts.
Toy trees with the 12 keys 2, 4, ..., 24. The B+ tree has 4 leaves of 3 keys and two internal levels. The B-tree has t = 2; we insert the keys in a fixed shuffled order.
Count the pages of a B+ range scan. Call the internal levels above the leaves d, the leaves the range touches ℓ, the keys returned m and the keys per leaf L.
R equals d plus ell, and ell is at most the ceiling of m over L, plus one.
Descend once through d internal pages to the leaf of the first key. Then walk the chain, one page per leaf, until a key passes the end. R is the descent plus the leaves.
In the toy, the range 6 to 18 returns m = 7 keys with L = 3 and d = 2. The keys sit in 3 leaves, so R = 2 + 3 = 5 pages; the bound allows ℓ up to 3 + 1 = 4. With d = 3 and L = 200, a scan of 10,000 rows reads at most 3 + 51 = 54 pages.
The descent is paid once, and the rest is reading leaves in key order. B+ internal pages also hold more keys, because they carry no record data. Take our 4 KB example. A B-tree that stores an 8-byte record pointer beside each key fits 169 keys per page. A B+ internal page fits 254.
The failure. Symptom: a range query on a large table reads far more pages than rows it returns. Measure: compare pages read with ⌈m/L⌉. Fix: make sure the query uses the ordered index and scans its leaves, not a fresh descent per row.
Chapter 9
Keep the small upper levels in RAM and pay disk reads only near the leaves
Every lookup reads the root. Most lookups read the same few pages just below it. So a database keeps recently used pages in RAM, in a buffer pool, and reads from disk only on a miss. CLRS makes the same assumption for the root: it is always in memory.
The levels grow fast going down, so the top ones are cheap to keep. Take a B+ tree of a billion records, 200 records per leaf and 200 children per internal page, with 4 KB pages. From the bottom: 5,000,000 leaves, then 25,000 pages, then 125, then the root.
Each bar is one level, wider for more pages (log scale). Blue levels sit in RAM. Drag the levels to cache and the size of the table.
Illustrative B+ tree: 200 records per leaf, 200 children per internal page, 4 KB pages. Real fan-outs depend on key size and fill.
Call the levels cached c. The disk reads left for one lookup are
R equals h plus one, minus c.
Count the levels. Subtract the levels kept in RAM. The rest each cost one disk read per lookup.
The billion-record tree has h + 1 = 4 levels. Cache the root and the 125 pages below it, 126 pages or about 0.5 MB, and c = 2, so R = 2. Cache the 25,000-page level too, about 103 MB, and R = 1.
Page sizes vary by system, so the numbers shift. These come from each system's own documentation.
| System | Page size | What its docs say about the tree |
|---|---|---|
| SQLite | 4,096 bytes by default since version 3.12.0 | table b-trees keep all data in the leaves; interior pages hold only keys and child pointers |
| PostgreSQL | usually 8 kB; a build option can change it | every table and index is an array of fixed-size pages |
| MySQL InnoDB | 16 KB by default; 4, 8, 32 or 64 KB allowed | every tablespace uses pages of this size |
The failure. Symptom: lookups slow down sharply once the data grows past a certain size. Measure: the buffer pool hit rate; a drop means an upper level no longer fits. Fix: give the buffer pool enough RAM to hold every internal level of the hot indexes.
Chapter 10
Keep the terms, the numbers, the checks and the core code on one page
A B-tree trades comparisons for page reads. Each node fills one page and holds between t − 1 and 2t − 1 keys, so the height is at most logt((n + 1)/2). Insert splits full pages on the way down; delete tops up thin pages on the way down. Both make one pass, and the tree grows and shrinks only at the root.
| Term | Meaning | Number on this page |
|---|---|---|
| Minimum degree t | t − 1 to 2t − 1 keys per non-root node | t = 3: 2 to 5 keys |
| Height bound | n ≥ 2th − 1, so h ≤ logt((n + 1)/2) | t = 127, n = 109: h ≤ 4 |
| Page fit | k·sk + (k + 1)·sp + H ≤ P | 4 KB, 8-byte keys: t = 127 |
| Search | R = d + 1 ≤ h + 1 pages | 45 in the toy: 3 pages |
| Split | 2t − 1 = (t − 1) + 1 + (t − 1); writes 3 pages | [10..50] to [10, 20], 30, [40, 50] |
| Merge | the split run backwards | [10, 20] + 30 + [40, 50] |
| B+ range scan | R = d + ℓ, ℓ ≤ ⌈m/L⌉ + 1 | 10,000 rows, L = 200: 54 pages at most |
| Cached levels | R = (h + 1) − c disk reads | a billion records, 0.5 MB cached: 2 reads |
pythonclass Node: def __init__(self, leaf=True): self.keys, self.kids, self.leaf = [], [], leaf class BTree: def __init__(self, t): self.t, self.root = t, Node() def split_child(self, x, i): # x.kids[i] is full: 2t - 1 keys t, y = self.t, x.kids[i] z = Node(y.leaf) x.keys.insert(i, y.keys[t - 1]) # the median moves up 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(self, k): r = self.root if len(r.keys) == 2 * self.t - 1: # full root: grow at the top self.root = Node(leaf=False) self.root.kids.append(r) self.split_child(self.root, 0) x = self.root while not x.leaf: i = bisect_right(x.keys, k) if len(x.kids[i].keys) == 2 * self.t - 1: self.split_child(x, i) # split before entering if k > x.keys[i]: i += 1 x = x.kids[i] insort(x.keys, k) # the leaf has room t = BTree(3) for k in [10, 20, 30, 40, 50, 60, 70, 80, 5, 15, 90]: t.insert(k) print(t.root.keys, [c.keys for c in t.root.kids]) # [30, 60] [[5, 10, 15, 20], [40, 50], [70, 80, 90]]
The code needs from bisect import bisect_right, insort. Delete follows the six cases of Chapter 6.
Now press Present or Teach. Derive the height bound from memory, size t for a 4 KB page, and walk one split and one merge. Then go back to the race and say why the 16 KB lane wins.
T. H. Cormen, C. E. Leiserson, R. L. Rivest and C. Stein, Introduction to Algorithms, MIT Press, Chapter 18, B-Trees. The rules, the height bound and the procedures follow the book.
R. Bayer and E. McCreight introduced B-trees in "Organization and Maintenance of Large Ordered Indices" (Acta Informatica, 1972). Page sizes come from the SQLite, PostgreSQL and MySQL documentation. The devices, toy trees, byte layouts and fill simulations are our own.