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
- C. Mohan, Don Haderle, Bruce Lindsay, Hamid Pirahesh, Peter Schwarz (1992). ARIES: A Transaction Recovery Method Supporting Fine-Granularity Locking and Partial Rollbacks Using Write-Ahead Logging.
- PostgreSQL Global Development Group (2024). Write-Ahead Logging (WAL).