System Design

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

  1. The client writes 6 records. Each is appended to the on-disk log and acked immediately.
  2. The table (in RAM) lags behind: only 3 records so far.
  3. Power cut. Everything in RAM is gone; the on-disk log still has all 6.
  4. On restart the database replays the log from record 1 to 6. Nothing is lost.

Why it’s fast and safe

Writing the table directlyWriting the WAL first
Random writes across many data pages — slowSequential appends to the end of the log — fast
A crash mid-write can leave half-written pagesThe 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_commit on), 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.