Sub topic 2
What happens at COMMIT: flushing WAL
This chapter assumes you know basic SQL, transactions and the ACID properties, and that you can read postgresql.conf settings. It covers what PostgreSQL does at COMMIT, what a checkpoint writes, why the first change to a page after a checkpoint logs a full page image, and how crash recovery uses all of this.
The commit path
When you run COMMIT, PostgreSQL writes a commit record to the write-ahead log (WAL), a sequential log of every change. It then flushes that WAL to disk with fsync before it reports success. The data pages themselves may still sit in memory.
With synchronous_commit = off, the flush happens asynchronously, so a crash can lose the last few transactions. Keep fsync = on in production.
Check the setting on your server:
SHOW synchronous_commit;
SELECT pg_current_wal_lsn();The second query returns the current WAL position, called the log sequence number (LSN).
What a checkpoint does
A checkpoint is a point where PostgreSQL writes all dirty data pages to disk. It then records a redo point, the LSN where crash recovery must start replaying WAL. Once a checkpoint completes, older WAL segments are no longer needed for crash recovery.
Checkpoints run when:
checkpoint_timeout(default 5 minutes) elapses.- WAL grows to
max_wal_size. - A user runs
CHECKPOINT. - The server shuts down or a base backup starts.
Full-page writes and torn pages
A data page is 8 kB, but a disk write may complete only partly during a crash. This is a torn page. To repair it, PostgreSQL logs a full image of a page the first time it changes after a checkpoint, when full_page_writes is on. This is why WAL volume jumps right after a checkpoint.
Crash recovery
After a crash, PostgreSQL reads the redo point from the last checkpoint and replays WAL forward from there. Full-page images restore torn pages first, then ordinary change records reapply the rest. A shorter gap between checkpoints means less WAL to replay.
Exercise
Exercise
After a crash, where does PostgreSQL start replaying WAL, and why does a checkpoint move that starting point forward?
Show answer
It starts at the redo point recorded by the last completed checkpoint. A newer checkpoint records a later redo point, so less WAL must be replayed and older segments can be recycled.