Want the details?
What is a write-ahead log?
A change in a database often touches several places on the disk: two accounts, a row and its index, a page and the page after it. The disk writes them one by one. If the power fails or the program crashes in between, the data is left half-changed and no longer makes sense.
A write-ahead log (WAL) fixes this with one rule: before changing the data, write a description of the whole change to the end of a log file, and make sure it is on the disk. Appending one record is a single, fast write. After a crash, the database reads the log and finishes every change it finds there (it replays the log). A change that never reached the log was never confirmed to anyone, so it is safe to forget.
How to read the bench
| Part on the bench | What it means in a real system |
|---|---|
| Box at the left | The client, sending transfers. Its lamp is lit while a transfer is in progress. |
| Coin stacks A to D | Data on the disk: four account balances. One coin is 10. |
| Coin in the air | The dangerous moment: the debit is on the disk, the credit is not. |
| Cards in the tray | Records in the log. A pale card's change is already applied to the accounts. |
| Switch at the front | The power. Lever down and lamp off: the machine is off and everything is dim. |
The numbers
- 4 accounts with 100 each: 400 in total. Every transfer moves 10.
- A new transfer starts about every 1.4 s; each step (log, confirm, debit, credit) takes 0.35 s.
- A power cut lasts 2.5 s, then the machine restarts.
- Without the log, a cut between debit and credit turns 400 into 390 for good.
- With the log, the test pulls the plug at hundreds of random moments: the total is 400 every time the power is back, and every confirmed transfer is applied.
In real systems
- PostgreSQL calls it the WAL; MySQL InnoDB the redo log; SQLite has a WAL mode and an older "rollback journal". The idea is the same.
- fsync. The log record only counts once the operating system confirms it is on the physical disk, not just in a memory buffer. Skipping this makes databases fast and unsafe.
- Checkpoints write the changed pages to disk and let the database remove old log records, so restarts stay quick.
- Replication often sends the same log to other servers (the replication lab): the log is the single story of what happened.
- Event sourcing takes the idea further: the log of events is the main data, and the tables are built from it.
Words to know
- Atomic
- All or nothing: a transfer either happens completely or not at all.
- Durable
- Once confirmed, a change survives a crash.
- Write-ahead log (WAL)
- A file where every change is written before the data itself is changed.
- Replay (redo)
- Reading the log after a crash and finishing the changes it lists.
- Checkpoint
- A point after which old log records are no longer needed.