databases · durability · write-ahead-log
How a database survives being unplugged mid-write
The trick is not writing faster. It is writing the intention down somewhere durable before touching the data at all.
Step by step
One row needs changing
A balance goes from 100 to 150. The obvious move is to find that row on disk and overwrite it, and that is the move that loses your data.
The intention is written down first, and flushed
Before anything is modified, a record of what is about to change is appended to the log and forced to disk. Appending is sequential, which is the fastest thing a disk does.
Only now is the row changed, and only in memory
The row is modified in the page cache. Fast, and completely lost if the power goes. That is safe to do, and it is only safe because the log already knows.
The commit is acknowledged from the log, not the data
The client is told the write succeeded once the LOG is durable, not once the data files are. This is the whole performance win: one sequential flush instead of a random write.
The data files catch up later, in the background
A background checkpoint writes dirty pages out eventually, batched, in an order the disk likes. Nothing is waiting on it, which is exactly why it may not have happened yet.
Pull the plug right now. What survives?
Three components are holding something. Only some of it is still there a second later, and which parts is the entire design.
Memory is gone. The disk is stale. The log is intact.
The page cache held the only copy, and it was never durable. The data files still say 100. Nothing is corrupt, but a write was acknowledged that the files do not contain.
On restart the log is replayed onto the data
Recovery reads forward from the last checkpoint and redoes every committed change. The log entry is still there, so the lost page cache costs nothing but the time to reapply it.
Durability is an ordering guarantee, not a speed
Nothing here writes faster or more carefully. It works because the log is made durable BEFORE the data, so every crash leaves a state the log can explain and repair.
Why not just write the row?
A row lives on a page, and a page is bigger than what a disk writes atomically. A crash halfway leaves a page that is neither the old value nor the new one. Nothing is left to say which rows were hit, so there is nothing to repair from.
The two things the log buys
- Recovery. After a crash, replay committed records and roll back uncommitted ones. The log is the only source of truth about what was in flight.
- Speed. Committing means one sequential append, not a scattered write to wherever the rows happen to live. Sequential writes are far faster, even on SSDs.