14
Recovery
Algorithm (simplified)
during server startup after a crash
(the cluster state in pg_control is not “shut down”):
1 For each WAL record:
1.1 Identify the page this record relates to
1.2 Apply the record if its LSN is greater than the LSN stored in the page
2 Overwrite unlogged tables with init files
The server crash is identified at the subsequent server start. If the startup
process spawned by the postmaster at the very beginning checks the
pg_control file and finds out a status other than “shut down”, automatic
recovery will be performed.
The startup process will read the WAL sequentially and apply the records to
pages, if necessary. The need can be determined by comparing LSN of the
page on disk with LSN of the WAL record. During recovery, pages are
changed in the buffer cache, as in normal operation. To do this, the
postmaster launches the necessary background processes.
WAL records are applied to files in a similar way: for example, if it is clear
from a record that the file must exist, but it does not, the file is created.
At the end of the process, all unlogged tables are overwritten using the forks
stored in the init files.
Starting with PostgreSQL 15, the system can prefetch WAL data during
recovery using the mechanism controlled by the recovery_prefetch
parameter. Its default value is try (prefetching is used if supported by the
OS). When prefetch is enabled, the wal_decode_buffer_size parameter
determines how far ahead the server will look into the WAL to identify the
required page numbers.
The algorithm described here is simplified. In particular, we have not
mentioned where to start reading WAL records from (this will be covered in
the Checkpoint lesson).