Sub topic 8
Crash recovery: replaying WAL from the redo point
This chapter assumes you know the write-ahead rule, what an LSN is, and what a checkpoint writes. It also assumes you can use psql and a shell on a test server. Here you will follow what PostgreSQL does after an unclean stop, from the first line of the startup log to the first accepted connection.
What a crash leaves behind
At the moment of a crash, the data files can be in any of these states:
- Some changed pages were written to disk and others were not.
- Committed changes may exist only in WAL, because the write-ahead rule only requires WAL to reach disk first.
- Changes from transactions that never committed may be partly on disk.
- Pages may be torn, meaning only part of an 8 kB page was written.
Crash recovery has one job. It must bring the data files to a state consistent with the WAL that reached disk, without any help from the user. It does this by replaying WAL forward from a known starting point. It never undoes anything.
Finding the starting point
The starting point comes from the control file, global/pg_control. Every checkpoint updates it. It records the following:
- The cluster state, such as
in productionorshut down. - The location of the latest checkpoint record.
- The redo point of that checkpoint, which is the LSN where replay must begin.
- The timeline ID.
You can read these fields with SQL on a running server:
SELECT checkpoint_lsn, redo_lsn, redo_wal_file, timeline_id, checkpoint_time
FROM pg_control_checkpoint();You can also read them with the command-line tool, even when the server is stopped:
pg_controldata "$PGDATA" | grep -E 'cluster state|Latest checkpoint|REDO'The redo point is usually earlier than the checkpoint record itself. A checkpoint takes time to write dirty pages, and the redo point is the WAL insert position at the moment the checkpoint began. Pages dirtied while the checkpoint was running may not have been written by it. Their WAL records lie between the redo point and the checkpoint record, so replay must start at the redo point.
If the cluster state is shut down, the last action was a shutdown checkpoint and there is nothing to replay. Any other state means the server did not stop cleanly, so recovery runs.
The startup sequence
The postmaster launches the startup process, which does the replay. The postmaster accepts no connections until replay finishes.
Replay reads WAL segments from pg_wal in LSN order. Each record carries a checksum (CRC-32C) and a link to the previous record. The startup process keeps reading until it finds a record that fails validation. That is the end of the usable WAL. It may be a zero-filled area, a bad length, or a checksum mismatch where a write was cut off.
A typical server log from this sequence looks like this. Exact wording and LSNs vary by version.
LOG: database system was interrupted; last known up at 2026-11-27 22:30:12 UTC
LOG: database system was not properly shut down; automatic recovery in progress
LOG: redo starts at 0/1A2B3C48
LOG: invalid record length at 0/1B7F2210: expected at least 24, got 0
LOG: redo done at 0/1B7F21D8 system usage: CPU: user: 0.03 s, system: 0.02 s, elapsed: 0.21 s
LOG: checkpoint starting: end-of-recovery immediate wait
LOG: database system is ready to accept connectionsThe line invalid record length ... got 0 looks like an error but is normal. It marks the end of valid WAL after a crash. It is a problem only if it appears well before the point where you expect WAL to end, for example because segment files are missing.
How a single record is replayed
Each WAL record belongs to a resource manager, such as Heap, Btree, Transaction or XLOG. The resource manager supplies the redo routine that applies the record. Each record also lists the data pages it touches (its block references). For each block reference, replay follows this logic:
- If the record carries a full-page image for the block, restore the whole page from the image. This also repairs a page that was torn by the crash.
- Otherwise, read the page from disk and compare its page LSN with the record's LSN.
- If the page LSN is greater than or equal to the record's LSN, the change is already on the page, so skip it.
- If the page LSN is lower, apply the change and set the page LSN to the record's LSN.
Step 3 makes replay idempotent: applying the same record twice has the same effect as applying it once. This matters because recovery can itself be interrupted. If the server crashes again during replay, the next startup begins from the same redo point and gets the same result.
Replay is safe for pages that were flushed after the redo point, and for pages that were never flushed. It does not depend on knowing which pages reached disk.
You can see the records that recovery would process with pg_waldump. Replace the LSN with your own redo LSN:
pg_waldump -p "$PGDATA/pg_wal" -s 0/1A2B3C48 -n 10The output shows each record's resource manager, length, transaction ID and block references. For a record that has a full-page image, it also shows the image (FPW).
Why there is no undo phase
Many database systems have a redo pass followed by an undo pass that rolls back unfinished transactions. PostgreSQL has no undo pass. It does not need one for these reasons:
- Row versions are never overwritten in place. An
UPDATEwrites a new tuple version and marks the old one with the updating transaction ID. - Visibility is decided from the commit status. Whether a tuple is visible depends on whether its transaction is recorded as committed in
pg_xact. - Commit status comes from WAL. Replaying a transaction's commit record marks it committed. A transaction that crashed before writing its commit record has no such record, so it counts as aborted. Its tuples stay on the pages but are invisible, and
VACUUMremoves them later.
The cost of this design is dead tuples that remain after a crash. The benefit is that recovery time depends only on how much WAL must be replayed, not on how long the crashed transactions had been running.
Other work done during startup
Recovery handles more than heap and index pages:
- Unlogged tables are not WAL-logged, so their contents cannot be recovered. After a crash, PostgreSQL resets each one to empty by copying its init fork.
- Temporary files and leftover temporary relations from the crashed session are removed.
- Data directory fsync. Before replay, PostgreSQL syncs the data directory so that earlier writes are durable. The
recovery_init_sync_methodsetting (PostgreSQL 14 and later) chooses betweenfsyncandsyncfson Linux. On clusters with very many files,syncfscan shorten this step. - End-of-recovery checkpoint. After replay, the server writes a checkpoint so that a second crash does not repeat the same replay. The server then starts a new WAL timeline segment position from the end of valid WAL and begins accepting connections.
What determines recovery time
Replay is performed by one process, and it often reads pages from disk at random. Recovery usually runs slower than the original workload that generated the WAL. Recovery time grows with the amount of WAL between the redo point and the end of WAL. The distance is bounded by checkpoint settings:
| Setting | Effect on recovery |
|---|---|
| `checkpoint_timeout` | Longer intervals allow more WAL since the last redo point. |
| `max_wal_size` | A larger value allows more WAL before a requested checkpoint. |
| `checkpoint_completion_target` | Spreading writes does not change the redo point, which is set when the checkpoint starts. |
| `full_page_writes` | Full-page images increase WAL volume, but they are what repair torn pages. |
Spreading checkpoint I/O does not make a crash worse. The redo point is fixed at checkpoint start. Replay starts there regardless of how long the checkpoint takes to finish.
A common mistake is to measure recovery time by the size of the database. The size of the WAL since the redo point matters, and the size of the database does not.
Trying it yourself
Use a disposable test cluster. Do not run this on a server that holds data you need.
psql -c "CREATE TABLE IF NOT EXISTS crash_demo (id int PRIMARY KEY, note text);"
psql -c "INSERT INTO crash_demo SELECT g, 'row' FROM generate_series(1, 100000) g ON CONFLICT DO NOTHING;"
pg_ctl -D "$PGDATA" stop -m immediate
pg_controldata "$PGDATA" | grep 'cluster state'
pg_ctl -D "$PGDATA" start
psql -c "SELECT count(*) FROM crash_demo;"stop -m immediate skips the shutdown checkpoint, so the next start goes through crash recovery. pg_controldata should report in production before the restart. After the restart, the table still holds all 100,000 committed rows, and the server log shows the recovery lines above.
Common errors
- Recovery appears to hang. The server accepts no connections while replaying, and clients receive
the database system is starting up. Watch the log and the growth of read activity on the disk. Do not kill the startup process. could not locate a valid checkpoint record. The WAL needed from the checkpoint record is missing or damaged, often because files were removed frompg_wal. Restore from backup.- Unexpectedly long recovery. Check
max_wal_sizeandcheckpoint_timeout. With very large values, a crash can leave many gigabytes of WAL to replay. - Torn pages with
full_page_writes = off. Replay assumes pages on disk are either old or new. A half-written page breaks that assumption, and replay may not repair it.
Exercise
A server crashes at 14:00. Its last checkpoint began at 13:55 and finished at 13:58, and its redo LSN was 0/5000000. A table page was flushed to disk at 13:56 with page LSN 0/5200000. During recovery, the startup process meets a record at LSN 0/5100000 for that page. What does it do with the record, and why?
Show answer
It skips the record. The page LSN (0/5200000) is greater than the record's LSN (0/5100000), so the change is already on the page. Replay is idempotent because of this LSN comparison. The one exception is a full-page image in the record, which would be restored unconditionally.
Exercise
Why does PostgreSQL not need an undo pass after a crash, and what happens to the rows written by a transaction that had not committed?
Show answer
Updates create new row versions instead of overwriting old ones, and visibility depends on the commit status of each transaction. A transaction that crashed before its commit record reached WAL is not marked committed, so it counts as aborted. Its tuples remain on the pages but are invisible, and a later VACUUM removes them.
Exercise
The redo point is set when a checkpoint starts. How does this affect the choice of checkpointcompletiontarget with respect to crash recovery time?
Show answer
It has no direct effect. Replay always starts at the redo point recorded at checkpoint start, no matter how long the checkpoint takes to finish writing pages. Recovery time is governed by how much WAL accumulates after that redo point, which checkpointtimeout and maxwal_size bound.