Write-Ahead Log: the database said “saved”, then the power died — is the data safe?
TL;DR
With a Write-Ahead Log (WAL), every change is appended to a log on disk before the client gets “OK”. Tables are updated later. After a power cut, the database replays the log on startup and recovers every acknowledged change.
What happens
- The client writes 6 records. Each is appended to the on-disk log and acked immediately.
- The table (in RAM) lags behind: only 3 records so far.
- Power cut. Everything in RAM is gone; the on-disk log still has all 6.
- On restart the database replays the log from record 1 to 6. Nothing is lost.
Why it’s fast and safe
| Writing the table directly | Writing the WAL first |
|---|---|
| Random writes across many data pages — slow | Sequential appends to the end of the log — fast |
| A crash mid-write can leave half-written pages | The log is the source of truth for recovery |
| Also powers replication and point-in-time recovery |
How to put it to work
- Know what an “ack” means: in PostgreSQL it comes from the WAL being flushed to disk (with
synchronous_commiton), not from the table. - Weigh the trade-off: disabling synchronous flush is faster but can lose the last few transactions in a crash.
- Operations: monitor WAL size and archive WAL for backups and point-in-time recovery.