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:
COMMITreturns 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_buffersand 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