AlgoViz

B-tree

medium 26 min

A B-tree is a sorted, always balanced tree with hundreds of keys in each page-sized node.

Video lesson · Chapter 1 of 5

Where can forty-two still be?

0:00 / 4:02

Four hops to one row in a billion

1:20Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

A B-tree is a search tree whose nodes are as large as a disk page. Each node holds many sorted keys and one more child pointer than keys, so every step of a search rules out almost everything.

It balances itself: every leaf has the same depth. Search, insert and delete take logarithmic time. Databases mostly use the B+ tree variant, where internal nodes only guide the search and the leaves hold the entries in one linked, sorted row.

Why it exists

A binary tree over a billion keys is 30 levels deep. If each level is a page that must come from disk, one lookup costs 30 slow reads. Packing hundreds of keys in one page makes the tree four levels deep.

Keeping the keys sorted matters as much as finding them. A sorted index answers equality, ranges, prefixes, minimum, maximum and ordering with one structure.

A short history

  1. 1970

    Rudolf Bayer and Edward McCreight of Boeing present "Organization and maintenance of large ordered indices", the paper that introduces the B-tree.

  2. 1973

    An IBM article describes the index behind the VSAM access method, which a later survey counts among the early B+ trees.

  3. 1979

    Douglas Comer's survey "The Ubiquitous B-Tree" appears. The title says how far the structure had spread.

Words to know

Fan-out
How many children a node has. High fan-out means few levels.
Order m
The largest number of children a node may have, so at most m - 1 keys.
Root, internal node, leaf
The top page, the guiding pages in between, and the pages at the bottom.
Split
A full node becomes two, and a key moves up to the parent.
Underflow
A node with fewer keys than allowed after a delete. It borrows or merges.
B+ tree
Variant with all entries in the leaves, and the leaves linked in order.
Clustered index
An index whose leaves hold the whole rows.

How it works

Step through the idea, or press Play.

Step 1 of 3

Compare inside one page. Binary search among hundreds of sorted keys

Understand it

Start here

The signpost story

A hiker looks for hut 42. Nobody checks every hut. At each crossing a signpost says which numbers lie in which direction. It is the same with a library directory that says A to M left, N to Z right: each sign leads to a smaller sign, until you stand in front of the book.

Looking for hut 42
1 to 2526 to 5051 to 7576 to 99Hut 42?The first signpost

Signs are cheap to read. Walking to each crossing is what takes time, like reading a page from disk.

The idea

Why not a binary tree?

Binary: one key per node

Seven keys already need three levels. A binary node has one key and two children.

B-tree: many keys per node

Fifteen keys in two levels, and a real page holds hundreds.
  • Self-balancing

    All leaves have the same depth. No branch grows long.

  • High fan-out

    Often hundreds of children per node, depending on key size.

  • Made for pages

    One node fills one page of 4 to 16 KB, so one step is one read.

  • Sorted

    Ranges, prefixes, minimum, maximum and ORDER BY come free.

Structure

The rules for order m

RuleIn generalOrder 4
Most children of a nodem4
Most keys in a nodem - 13
Fewest keys, not the rootceil(m / 2) - 11
Keys in the root1 to m - 11 to 3
Children of a node with k keysk + 13 keys, 4 children
LeavesAll at the same depthAlways balanced
An empty tree has an empty root. Books differ in how they define order, so say which you mean.

A node with the keys 25, 50, 75 has four pointers: below 25, between 25 and 50, between 50 and 75, above 75. In a plain B-tree a search can stop at a key in any node. In a B+ tree a key equal to a separator continues to the right.

Size

How deep is it?

Fan-out and levels

f≈pageentry=819220≈400L=⌈log⁡fN⌉=⌈log⁡400109⌉=4f \approx \frac{\text{page}}{\text{entry}} = \frac{8192}{20} \approx 400 \qquad L = \lceil \log_f N \rceil = \lceil \log_{400} 10^9 \rceil = 4
Assuming 20 bytes for a small key, its pointer and its slot. Long keys lower the fan-out.

Levels by number of entries

EntriesBinaryFan-out 100Fan-out 400Fan-out 1,000
1,00010221
1,000,00020332
1,000,000,00030543
Full pages. Real pages are partly empty, so a tree can be one level deeper.

How much must stay in memory?

109400=2.5M leaf pages≈20 GB6250+16+1=6267 upper pages≈50 MB\frac{10^9}{400} = 2.5\text{M leaf pages} \approx 20\,GB \qquad 6250 + 16 + 1 = 6267 \text{ upper pages} \approx 50\,MB
With the upper three levels in memory, a lookup reads one leaf from disk. PostgreSQL says that typically over 99% of the pages of a B-tree index are leaves.

Where the pages of one lookup live

An application asks one database server for a key. Inside the server, the root page and the internal pages are in the buffer pool in memory. The leaf page and the table page are on disk.
The top of the tree is tiny and hot, so it stays in the buffer pool.

Search

Find 42

  1. 1

    Root: 25, 50, 75

    42 lies between 25 and 50. Take the second pointer.

  2. 2

    Internal: 30, 40

    42 is larger than 40. Take the last pointer.

  3. 3

    Leaf: 41, 42, 44

    Found. If 42 were not here, it would not exist.

Inside a page the keys are sorted, so a binary search takes a few comparisons in memory. Compared with loading a page, that costs almost nothing.

Insert

The middle goes up

Insert

Splits can travel up to the root. That is the only way the tree grows taller, so it stays balanced.

Order of arrival matters. Keys that arrive in order always go to the last page. InnoDB then leaves pages about 15/16 full; with random keys they are between 1/2 and 15/16 full. Random keys also touch pages all over the disk, which is why random identifiers make a clustered table slower to load.

Delete

Borrow or merge

CaseWhat happens
Key in a leaf, enough keys leftRemove it
Key in an internal nodeReplace it with its predecessor or successor from a leaf, then remove that one
Underflow, a sibling has spare keysBorrow one through the parent
Underflow, no spare keysMerge with the sibling and pull the separator down
The root has no keys leftIts only child becomes the root: one level less

B+ tree

All entries in the leaves

B+ tree

  • Entries only in the leaves
  • Leaves linked in order, often both ways
  • More separators fit in a page, so more fan-out
  • Range scans go sideways
  • Every lookup has the same length

Plain B-tree

  • Entries in all nodes
  • No leaf links needed
  • A lookup may end early, near the root
  • No key is stored twice
  • A range must walk up and down

Range from 35 to 75

Descend once to 35, read 40 and 50, follow the link, read 60 and 70, stop at 80.

Why databases like it

  • Linked leaves

    Fast range scans.

  • Thin upper levels

    No rows there, so more keys per page.

  • Neighbouring pages

    Reading ahead is possible.

  • Same depth

    Predictable number of reads.

Cost

Time and page reads

OperationComparisonsPage reads
SearchO(log n)O(log_f n)
InsertO(log n)O(log_f n)
DeleteO(log n)O(log_f n)
Range of k entriesO(log n + k)O(log_f n + k / f)
n entries, fan-out f. Inserting also shifts keys inside a page, which is memory work.

In a database

From the index to the row

In a clustered index the leaf holds the row. InnoDB stores its tables that way, ordered by primary key. A secondary index leaf holds a reference, so a lookup continues at the row: one more step. If the index holds every column the query needs, that step is saved; such an index covers the query. More on queries in SQL databases.

Limits

When B-trees struggle

SituationWhyThink about
Heavy small writesOne 100-byte change can rewrite an 8 KB page, about 80 times as muchBatching, or an LSM tree
Append-only logs and metricsTime order makes other structures cheaperLSM tree, partitions by time
Random keysPages all over the tree are dirtied and splitOrdered identifiers
Very long keysLow fan-out, deeper treeA shorter key or a hash of it
Scans of most rowsIndex hops cost more than reading in orderFull scan, or a column store for OLAP
A page changed many times in memory is written once, so real write cost is often lower than the worst case.

Which structure?

Summary

The whole topic in one minute.

A B-tree turns one disk page into one decision among hundreds of ranges. Four such decisions find a row among a billion, and the upper levels are small enough to stay in memory, so often only one page is read from disk.

Inserts split full pages and push a key up; deletes borrow or merge. The price is paid by writes: small changes scattered over many pages. When writes dominate, an LSM tree may serve better.

  • One node is one page with hundreds of sorted keys.
  • A billion entries need about four levels, and the upper ones fit in memory.
  • A full node splits and the middle key goes up; the tree grows at the root.
  • Deletes borrow from a sibling or merge.
  • B+ trees keep entries in linked leaves, which makes ranges cheap.
  • Small scattered writes are the weak side.

Sources