Write-ahead logs explained: how databases survive crashes and power cuts
If a server loses power in the middle of saving data, why doesn't the database end up corrupted? In many systems the answer is a write-ahead log (WAL).
The core rule
Before the database changes its main data files, it first writes a description of the change to an append-only log and makes sure that log entry is safely on disk. Only then is the transaction reported as committed.
Appending to the end of a file is fast and simple, while updating data pages scattered across a disk is slower. So the database can confirm commits quickly and update the main files later in the background.
Recovery after a crash
When the database restarts, it reads the log:
- Changes that were committed but not yet applied to data files are replayed.
- Changes from transactions that never committed are ignored or undone.
The result is that committed data survives, and half-finished transactions do not leave a mess behind. This is a big part of the "D" (durability) in ACID.
Checkpoints
Logs cannot grow forever. Periodically the database runs a checkpoint: it flushes changes to the data files and marks a point in the log before which nothing needs to be replayed. Older log segments can then be recycled or archived.
Why WAL shows up everywhere
- Replication: replicas can follow along by streaming the primary's log. PostgreSQL's streaming replication works this way.
- Point-in-time recovery: keep a base backup plus archived logs, and you can restore to a specific moment.
- Change data capture: tools read the log to send changes to other systems.
Discussion:
- Have you ever had to restore a database to a specific point in time? How did it go?
- What durability settings do you relax for speed, and where do you never compromise?
Comments · 4
A useful way to picture it: the log is like a diary kept before you rearrange the furniture. If the power goes out mid-move, you read the diary on restart and either finish the job or undo it.
Exactly that analogy. Write the intent to the log first, then change the data. After a crash, replay the log to finish or undo anything half-done.
The point about fsync settings is worth highlighting. Some setups trade durability for speed and nobody realizes until they have an incident.
An interesting follow-up is what "safely on disk" means in practice, since disk and OS caches can report a write as done before it truly is. How databases handle fsync settings is where durability claims get tested.