B-Trees and Write-Ahead Logs

How a B-tree finds any key in a few page reads, how it splits pages as it grows, and how the write-ahead log keeps in-place updates safe after a crash.

Overview

A B-tree is a sorted, balanced tree built out of fixed-size disk pages. It is the default index in most relational databases: PostgreSQL's default index type is a B-tree, and every InnoDB table in MySQL is itself a B-tree ordered by its primary key. It answers point lookups and range scans in a small, predictable number of page reads.

Where an LSM-tree never changes a file, a B-tree changes pages in place. That is what makes reads simple, and it is also why a B-tree needs a write-ahead log: a crash in the middle of changing pages must not leave the tree broken.

Pages and the tree

The disk is split into pages of one fixed size. PostgreSQL uses 8 kB pages by default, InnoDB 16 KB, and SQLite 4096 bytes. Each page holds sorted keys. In an inner page, the keys sit between pointers to child pages, and each pointer covers the range of keys between its two neighbors. Leaf pages hold the entries themselves, or pointers to the rows.

A lookup starts at the root and reads one page per level until it reaches a leaf. The number of children per page is the branching factor, and it is large: a page of several kilobytes holds hundreds of keys and pointers. So the tree is short, and the top levels are small enough to stay in memory.

The height follows from simple arithmetic, not a measurement: leaf pages = branching factor to the power (levels minus 1). Assume about 100 keys per leaf to estimate the total.

  • Branching factor 300, 3 levels: 300 × 300 = 90,000 leaf pages, which hold about 9 million keys.
  • Branching factor 300, 4 levels: 300 × 300 × 300 = 27 million leaf pages, which hold about 2.7 billion keys.
  • Branching factor 500, 4 levels: 500 × 500 × 500 = 125 million leaf pages, which hold about 12.5 billion keys.

Four levels with a few hundred children per page already reach billions of keys, which is why lookups take about three or four page reads.

Key concepts

  • Page
  • Branching factor
  • Page split
  • Sibling links
  • Write-ahead log (WAL)
  • Checkpoint
  • Torn page
  • Fill factor

Interview questions

  • How does a B-tree survive a crash in the middle of a write?
  • Why is a B-tree only three or four levels deep, even for a huge table?
  • Walk me through an insert that causes a page split.
  • When would you pick a B-tree engine over an LSM-tree engine?
  • How can a B-tree be crash safe without a write-ahead log?

Sign up free to read the full topic

More DDIA topics

Start free on Cariara · Coding problems · System design studio