Skip to the workspace
Pebellslearn by building
High Level Database Concepts  ›  Lesson

The Write-Ahead Log

Write-ahead Log 14 minPostgreSQL records every change in the write-ahead log and flushes it at commit, so after a crash it can replay the log from the last checkpoint.

postgresql dba / The Write-Ahead Log

Explore each scene at your own pace.

01 · The rule

The rule

The Write-Ahead Log

The power fails in Pedal's server room one second after a payment commits. The changed table page was still only in memory. Yet when the server comes back, the payment is there. The reason is one rule PostgreSQL never breaks.

The rule

Log the change first, flush it at commit, write the tables later.

Every change is first described in the write-ahead log (WAL): an append-only stream of records such as "in page 812 of payments, insert this row". The WAL lives in the pg_wal directory, split into segment files of 16 MB by default.

  • Log first: a data page may not reach disk before the WAL record describing its change.
  • Flush at commit: COMMIT returns only after the transaction's WAL records are safely on disk. That is where durability comes from.
  • Tables later: the changed data pages stay in shared_buffers and are written out lazily by the background writer and the checkpointer.

Sequential appends to one log are far cheaper than scattered writes to many table files, so this design is fast as well as safe.

A checkpoint writes every dirty page to the data files and records a point in the WAL where the files are known to be complete. After a crash, PostgreSQL starts from the last checkpoint and replays the WAL forward. WAL older than the last checkpoint is no longer needed for recovery and is recycled.

The same stream powers two more DBA tools:

  • Replication: a standby server receives the WAL and replays it continuously.
  • Point-in-time recovery: a base backup plus archived WAL can rebuild the database as of any moment.
SHOW wal_level;             -- replica by default
SELECT pg_current_wal_lsn(); -- the current position in the log
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.