Try
↑ ↓ move↵ openesc close

Interview prep / B-trees

Mid · B-trees · System design interview question

Why does a B-tree database write a log before it changes pages, and why not just write the pages?

Sketch your own answer first, then compare it with the one below.

A strong answer

Changing a page in place is a random write, and a split changes several pages. If the machine crashes halfway, the tree can be left with a half-finished split and be corrupt.

A write-ahead log is an append-only file. The engine writes a record describing the change and flushes the log, and only then calls the write committed. The changed pages can sit in memory and be written later, in batches. After a crash, the engine replays the log to redo committed changes and undo unfinished ones.

So the log buys two things: durability with one sequential write, and a safe way to put off the random page writes. The cost is that every change is written twice, once in the log and once in the page.

Sources

Learn it by running it

The b-trees and page writes lesson explains the mechanism behind this question, and its lab lets you change the parameters and watch the effect.

Your progress is saved in this browser. Sign in to keep it on every device. Privacy · Terms