skip to content

crash recovery

kill the server, restart, replay from the redo pointer. pages newer than a record get skipped.

address
everything.wal.crash_recovery
part
part 16, WAL and recovery
chapter
chapter 6 of 11
reading time
12 min

when postgres starts after a crash, it reads pg_control, finds the last checkpoint's redo pointer, and replays the WAL from there to the end, record by record. a page whose LSN says it already has a change gets skipped. there is no undo: a transaction with no commit record in the log just counts as aborted, and its rows stay on the page, invisible.

the picture

you know how postgres promises your COMMIT survives a crash, even though the table's files hadn't been touched when COMMIT returned? that only works if something puts the pages back afterwards. that something is recovery, and it runs every time the server starts after not shutting down cleanly.

think of a restaurant where the cook writes every order on the rail before cooking it (the WAL), and the dining room only gets a full inventory count once an hour (a checkpoint). the power goes out mid-service. nobody remembers what was on the stove. but the rail survives, so the next morning the cook finds the last inventory count, and re-cooks every ticket after it, skipping any plate that's already on a table (a page that already has the change). tickets nobody paid for get thrown out by the cashier (the commit log), not un-cooked.

hover a stage.

what a restart after a crash does, in order. hover a stage. only the middle one takes real time, and how long depends on how much WAL there is since the last checkpoint.

kill it mid-sentence

the browser engine can't crash and restart, so this is a real postgres 18.6 server, killed with pg_ctl stop -m immediate (every process dies, no checkpoint, nothing flushed on the way out) and started again. the table is notes, one page. after a CHECKPOINT, T2 inserts a row and never commits. T1 inserts a row and commits. then the kill.

capture =
obsCHECKPOINT
pagesnotes·0pd_lsn+0x15FE980

runninga checkpoint writes every dirty page to disk. if we crash now, redo starts from here.

flush line: on disk from here backin wal_buffers, not on diskbeing replayedlost in the crashpage newer in memory than on disk
step 1/17
real output, a postgres 18.6 server · crash-recovery
step through. before the crash, records past the flush line are only in memory (dashed), and the page's pd_lsn in memory runs ahead of the one on disk (the dirty corner). at the crash, everything in memory is gone. then redo replays the WAL that was on disk, one record at a time (hot), while the page's LSN climbs back. switch captures for a lost asynchronous commit and for a record that redo skips.

three things to notice in the first capture.

the WAL went first. T2's insert is the first change to the page since the checkpoint, so its record is 198 bytes, 144 of them a copy of the page (full-page writes explains why). T1's insert into the same page is 69 bytes, just the new tuple. neither touched the table's file. at T1's COMMIT, postgres flushed the WAL up to the end of T1's commit record, which drags T2's records to disk with it: the log is one sequence, and you can only flush a prefix of it (the write-ahead rule).

the file was stale and that was fine. at the crash, the page on disk still said pd_lsn 0/15FE980, from before the checkpoint. the 8 records on disk from the redo pointer are everything recovery needs to bring it forward.

redo restored the page from its image. the first record for the page carries a full-page image, so redo overwrites the page with it and never even looks at what the file said. the next record lands on top. then T1's commit record marks its xid committed in pg_xact.

here's what the server said about it. postgres 18.6's own words, from the restart:

server log
  1. LOG: database system was interrupted; last known up at …
  2. LOG: database system was not properly shut down; automatic recovery in progress
  3. LOG: redo starts at 0/161FFE8
  4. LOG: invalid record length at 0/16202D0: expected at least 24, got 0
  5. LOG: redo done at 0/16202A8
  6. LOG: checkpoint starting: end-of-recovery immediate wait
  7. LOG: checkpoint complete: wrote 2 buffers (0.0%), wrote 3 SLRU buffers; 0 WAL file(s) added, 0 removed, 0 recycled; write=<t> s, sync=<t> s, total=<t> s; sync files=4, longest=<t> s, average=<t> s; distance=0 kB, estimate=0 kB; lsn=0/16202D0, redo lsn=0/16202D0
  8. LOG: database system is ready to accept connections
real output, a postgres 18.6 server · crash-recovery
the restart's log. "invalid record length ... got 0" is how the end of the WAL looks: the next record slot is zeros. it is not an error.

where redo starts

recovery doesn't scan the whole log. it reads global/pg_control, a small file the checkpointer rewrites at the end of every checkpoint, and starts from the redo pointer it names. this is pg_control as pg_controldata read it, a moment after the kill:

fieldtextvaluetext
Database cluster statein production
Latest checkpoint location0/1620058
Latest checkpoint's REDO location0/161FFE8
Latest checkpoint's TimeLineID1
Latest checkpoint's full_page_writeson
Latest checkpoint's NextXID0:759
(6 rows)
real output, a postgres 18.6 server · crash-recovery
pg_control at the crash. "in production" means nobody shut it down cleanly, so the next start runs recovery. the redo location is where it will start reading.

the redo location (0/161FFE8) is not the checkpoint record itself (0/1620058). it's where the checkpoint started: pages dirtied while the checkpoint was writing may not have made it out, so replay begins at the start. checkpoints has the full story. you can read the same fields from SQL. in the browser, CHECKPOINT runs inside your own session (there's no checkpointer process), but pg_control moves the same way:

sqldb=lab
SELECT checkpoint_lsn, redo_lsn, redo_wal_file, timeline_id, full_page_writes
FROM pg_control_checkpoint();
CHECKPOINT;
SELECT checkpoint_lsn, redo_lsn FROM pg_control_checkpoint();
output, from postgres 18.6
#1 · SELECT 1
checkpoint_lsnpg_lsnredo_lsnpg_lsnredo_wal_filetexttimeline_idint4full_page_writesbool
0/17DB8000/17DB8000000000100000000000000011t
(1 row)
#2 · CHECKPOINT
#3 · SELECT 1
checkpoint_lsnpg_lsnredo_lsnpg_lsn
0/17E5D700/17E5D18
(1 row)

pages newer than a record get skipped

replaying a record is not always safe. a heap INSERT says "put this tuple in slot 2". do that to a page that already has slot 2 and you get a corrupt page, or a crash in the middle of recovery. so every page header carries pd_lsn, the end of the last WAL record applied to it, and redo checks it first: if the page's LSN is at or past the record's end, the page already has the change, skip it.

with full-page writes on (the default), you rarely see a skip: the first record for each page after the redo pointer carries the whole page, redo restores it from that image, and every later record is newer by construction. the check earns its keep when there's no image to restore from. so the third capture turns full_page_writes off, inserts row 2, pushes the page out to its file with pg_buffercache_evict(), inserts row 3, and kills the server.

pick full_page_writes = off in the figure above. the file says pd_lsn 0/1577D08. row 2's record starts at 0/1577CB0 and is 84 bytes, so it ends at or before what the page already has: skipped. row 3's record is newer: applied. the query after the restart returns all three rows, once each. if redo had applied row 2's insert again, it would have tried to put a tuple into a slot that was already taken, and postgres would have stopped recovery with a PANIC instead.

predict the output
T2 inserted row 3 but never committed. after the crash and restart, what's on the page?
sql
/* T2 */ BEGIN;
/* T2 */ INSERT INTO notes VALUES (3, 'in flight at the crash');
/* T1 */ INSERT INTO notes VALUES (2, 'committed');   -- autocommit
-- pg_ctl stop -m immediate, pg_ctl start
SELECT id FROM notes ORDER BY id;   -- 1, 2. and on the page?

step the first capture to the end: the page has three tuples. lp 2 is T2's row, with its xmin now reported aborted. postgres doesn't run an undo pass at all, because its old versions live in the table and its rollback is a status change. textbook recovery (ARIES) needs undo because it updates in place.

an async commit, gone

pick synchronous_commit = off. T1 commits normally: its COMMIT waits for the flush. T2 runs with synchronous_commit = off: its COMMIT returns as soon as the commit record is in wal_buffers, and T2's client is told it committed. on a normal server the WAL writer flushes it soon after: the manual puts the window at three times wal_writer_delay, which is 200 ms by default (this capture sets it to 10 s, so the window is easy to hit). the kill comes first. the 120 bytes between the flush pointer and the insert pointer, T2's insert and its commit, were never written, so they are not there to replay. after the restart, row 2 is back and row 3 isn't, even though its client heard "COMMIT".

that is the whole trade of synchronous_commit = off: the database never ends up inconsistent (T2 is cleanly absent, not half there), but a commit that was acknowledged can disappear.

how long it takes

recovery replays every record from the redo pointer to the end of the WAL. so the time it takes is set by how much WAL was written since the last checkpoint started: with the defaults (checkpoint_timeout = 5min, max_wal_size = 1GB) that's at most around a gigabyte, usually much less. the knobs that make checkpoints rarer, and steady-state I/O smoother, make recovery longer. that's the trade checkpoints is about. the same replay loop, never stopping, is what a streaming replica runs all day, and pointed at archived WAL with a stopping point it's point-in-time recovery.

one level deeperwhat recovery doesn't replay
  • unlogged tables write no WAL, so after a crash postgres resets them to empty instead of replaying anything (UNLOGGED tables has the capture). temporary tables are gone with their sessions anyway.
  • the end-of-recovery checkpoint is written as a shutdown checkpoint (XLOG CHECKPOINT_SHUTDOWN in the captures), so the first thing in the log after recovery says "everything before this is on disk".
  • hint bits set after the restart (HEAP_XMIN_INVALID on T2's tuple, once something reads it) are a fresh change, logged or not like any other (commit log and hint bits).

keylines

  • recovery starts at the last checkpoint's redo pointer, from pg_control, and replays to the end of the WAL.
  • a record is applied only if the page's LSN is older than it. full-page images restore the page outright.
  • redo repeats everything, committed or not. commit status in pg_xact decides what's visible.
  • no undo pass: an uncommitted transaction's rows stay on the page, aborted, until VACUUM.
  • synchronous_commit = off can lose an acknowledged commit, never consistency.
  • "invalid record length ... got 0" is just the end of the log.