Transcript
A database can keep a billion records on disk, and still find any one of them in just a few disk reads. The trick is a tree that's short and wide, with hundreds of keys in every node. Today: B-trees, the shape behind almost every database.
Last time, finding something meant walking down the tree, one level at a time. When the tree lives on disk, every level is one disk read, and disk reads are slow. If reading memory took one second, an SSD read would take more than ten minutes, and a spinning hard drive more than a day. A balanced binary tree with a billion keys is thirty levels deep. That's thirty slow reads.
So make each node wide. A node keeps hundreds of keys in order, with a child between each pair, and the whole node comes in with one read. With five hundred keys per node, four levels can hold over sixty billion keys. Four reads instead of thirty.
Here's a small one, with at most three keys per node. Add numbers, and each one drops into its place, in order. When a node is full, split it: the middle key moves up a level, and the other two become separate nodes. When the root itself is full, it splits too, and the tree grows one level taller, from the top. So every leaf always stays at the same depth.
Most databases and file systems use a variation called a B-plus tree. All the data sits in the bottom row, and the bottom nodes are linked side by side. To find everything from thirty to seventy, go down once, then just walk along the bottom row.
On a slow disk, count the reads, not the steps. A B-tree keeps that count tiny by staying short and wide. Next time: a tree that always keeps the most urgent item on top. Heaps and priority queues. See you there.
Next episode: heaps and priority queues, a tree that always keeps the most urgent item on top.