Skip to content

System Design

Write-Ahead Log (Durability)

O(1) time to append one log record · O(n) time to replay n log records during recovery.

The idea, in plain English

Before a careful accountant erases a number on a whiteboard and writes the new one, they first jot the change in a permanent notebook: 'changing balance from 100 to 80.' If the power goes out right after the whiteboard is half-erased, the notebook still says exactly what was supposed to happen. The accountant can finish the job later without losing track. A write-ahead log (WAL) does this for a computer system. Before changing the real data, it first appends a record of that change to a durable, append-only log. If the process crashes mid-change, replaying the log rebuilds the data exactly as it should be. Nothing is lost.

How it works

  1. 1Before applying any change to the actual data, first append the change as a record to the write-ahead log — a durable, append-only file. This record describes exactly what is about to happen.
  2. 2Only after the log record is safely written, apply the same change to the real data store.
  3. 3If the system crashes before finishing, replay every record in the log from the start on restart. Reapply each change. This reconstructs the data exactly as it should be, even though the crash happened mid-work.

When you'd use it

Use a write-ahead log once your app can't afford to lose data if the server crashes mid-write. A database engine, a bank ledger, and a message queue all use one. As long as the log write succeeded, you can always recover the change after a crash — even if the actual data file never got updated.

Common beginner mistakes

  • Applying the change to the data store before — or instead of — writing it to the log. If a crash happens in between, that change is lost forever. This defeats the entire purpose of a WAL.
  • Forgetting to actually replay the log on restart. The log only protects you if something reads it back and rebuilds the data from it after a crash.

Try it — edit and run

Click the code to edit · press ⌘/Ctrl+↵ to run

Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.

Expected output — hit Run to try it
Before crash:
log entries: 3
data: balance:alice=80, balance:bob=50
After crash + replay from the log:
log entries: 3
data: balance:alice=80, balance:bob=50

Not sure this is the right topic? See the learning paths → or where this leads →