Write-Ahead Logging (WAL)

Difficulty: Advanced

Question

What is Write-Ahead Logging (WAL) and how does it guarantee durability after a crash?

Answer

Write-Ahead Logging means the database records every change in an append-only log on disk, and forces that log record to stable storage before the transaction is reported as committed and before the modified data page is written. If the server crashes, the data files may be stale or half-written, but replaying the log from the last checkpoint brings them back to a consistent, committed state. That is how the D in ACID is delivered without writing every data page on every commit.

The one rule WAL enforces

A modified data page may not be flushed to disk until the log records describing that change are already durable. In practice:

  1. A transaction changes a row. The page is modified in the buffer pool (memory) and becomes "dirty".
  2. A WAL record describing the change is appended to the in-memory WAL buffer and gets a Log Sequence Number (LSN).
  3. On COMMIT, the WAL is flushed with fsync (or equivalent) up to the commit record's LSN.
  4. Only then does the client get success. The dirty data page can be written much later by a background writer or checkpoint.

Each page stores the LSN of the last change applied to it, so recovery knows which records still need replaying.

Why this is faster than writing the data directly

  • Log writes are sequential appends; data page writes are random I/O across the whole table and its indexes.
  • One commit may touch many pages but needs only one log flush.
  • Many concurrent commits can share a single flush (group commit).

What happens during crash recovery

When PostgreSQL restarts after a crash it reads the last checkpoint location from pg_control and replays (redoes) every WAL record from that point forward. Records for transactions that never committed are replayed too, but MVCC makes their row versions invisible, so PostgreSQL needs no separate undo phase. Engines like InnoDB and the ARIES family do redo first and then undo (roll back) uncommitted changes using undo logs.

Partial page writes are handled separately: PostgreSQL's full_page_writes logs a full image of a page the first time it changes after a checkpoint, and InnoDB uses a doublewrite buffer for the same purpose.

WAL does more than recovery

  • Replication: streaming replicas in PostgreSQL apply the primary's WAL stream. MySQL's binlog plays a similar role.
  • Point-in-time recovery: a base backup plus archived WAL lets you restore to any moment, for example just before someone ran a bad DELETE.
  • Change data capture: tools like Debezium read logical decoding output from the WAL to stream changes to Kafka.

Trade-offs and settings to know

Setting (PostgreSQL)Effect
synchronous_commit = on (default)Commit waits for local WAL flush; no committed data lost
synchronous_commit = offCommit returns before flush; a crash can lose the last few hundred milliseconds of commits, but never corrupts data
fsync = offNever safe in production; a crash can corrupt the cluster
wal_levelreplica (default) or logical for logical decoding

A common mistake is assuming the disk is durable when fsync returns. Consumer SSDs or virtual disks with volatile write caches can lie, which is why production databases run on storage with power-loss protection.

Commit path with WAL. The commit is acknowledged only after the log record is durable; the data page is written later.
  1. Client → Buffer Pool: UPDATE row, page marked dirty
  2. Buffer Pool → WAL on Disk: Append WAL record with LSN
  3. Client → WAL on Disk: COMMIT forces fsync of WAL
  4. WAL on Disk → Client: Flush done, commit acknowledged
  5. Buffer Pool → Data Files: Dirty page written later at checkpoint

Code examples

Inspecting WAL in PostgreSQL

-- Current WAL write position
SELECT pg_current_wal_lsn();

-- How much WAL an operation generates
SELECT pg_current_wal_lsn() AS before \gset
UPDATE orders SET status = 'SHIPPED' WHERE created_at < now() - interval '7 days';
SELECT pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), :'before')) AS wal_generated;

-- Durability-related settings
SHOW wal_level;            -- replica by default
SHOW synchronous_commit;   -- on by default
SHOW full_page_writes;     -- on by default

-- Relax durability for one low-value transaction only
BEGIN;
SET LOCAL synchronous_commit = off;
INSERT INTO page_views (user_id, path) VALUES (42, '/jobs');
COMMIT;

pg_wal_lsn_diff measures how many bytes of WAL a statement produced. SET LOCAL synchronous_commit = off trades a tiny window of possible loss for faster commits on data you can afford to lose, without risking corruption.

Key points

  • Log first, data later: a page cannot hit disk before its WAL record does.
  • Commit durability comes from flushing the WAL, not the data files.
  • Sequential log appends plus group commit make WAL cheaper than random page writes.
  • Recovery replays WAL from the last checkpoint; PostgreSQL needs no undo phase thanks to MVCC.
  • The same WAL powers replication, point-in-time recovery and CDC.

Common follow-up questions

  • What is a checkpoint and how does it bound recovery time?
  • How does synchronous_commit = off differ from fsync = off?
  • How do torn pages get handled (full_page_writes, doublewrite buffer)?
  • How does streaming replication use the WAL?

Interview tips

  • State the rule precisely: the log record must be durable before the commit is acknowledged and before the dirty page is flushed.
  • Explain why it is faster (sequential vs random I/O, group commit); that is what separates a memorised answer from understanding.
  • Bring up replication and PITR as other uses of the WAL to show breadth.

Concepts covered

Write-Ahead Log, Durability, Crash Recovery, fsync, Log Sequence Number

More Database Design questions