Sub topic 2
How the write-ahead log makes replay possible
This chapter assumes you can edit postgresql.conf, use psql and the Linux shell, and know roughly what the data directory contains. It also assumes you know what a transaction and durability are. By the end you will understand what the write-ahead log (WAL) holds, how it is split into files, and why replaying it can rebuild a database at a past moment. Later chapters depend on all three.
The write-ahead rule
PostgreSQL does not write every change to the table and index files at commit time. Those files are large, and writing to scattered places is slow. Instead it follows one rule: a change must be described in the WAL, and that description must reach durable storage, before the changed data page can be written to disk and before the commit is reported as successful.
The WAL is a sequential, append-only stream of records. Appending to one file is fast. The data files can be updated later, in the background, by the checkpointer and the background writer.
This gives two properties:
- Durability. After a commit, the changes are safe on disk in the WAL even if the data files are stale.
- Replayability. The WAL is a complete, ordered history of every change. Applying the records in order to a copy of the data files brings that copy forward in time.
Crash recovery and point-in-time recovery (PITR) use the same replay mechanism. After a crash, PostgreSQL replays WAL from the last checkpoint to the end of the local WAL. In PITR you give it an old copy of the files (a base backup) and a supply of older WAL. Replay then runs until a stop condition you choose.
What a WAL record contains
Each record belongs to a resource manager, which is the part of the server that knows how to redo it. Examples are Heap (table rows), Btree (indexes), Transaction (commit and abort) and XLOG (checkpoints and housekeeping). A record holds the changed block references and the data needed to redo the change. It never holds the original SQL text. Replay is therefore physical: "put these bytes in this block of this relation file."
Two details matter for PITR:
- Commit records carry a timestamp. When a transaction commits, the Transaction record stores the commit time. This is what lets recovery stop at
recovery_target_time. The server reads commit records, compares their timestamps with your target, and stops at the right place. - Full-page images. With
full_page_writes = on(the default), the first change to a page after a checkpoint writes the whole 8 kB page into the WAL. This protects against torn pages, where a crash leaves a page half-written. Replay can overwrite a damaged page with a known-good image and then apply later changes. It also means WAL volume spikes just after each checkpoint.
Log sequence numbers
Every position in the WAL has an address called a log sequence number (LSN). It is a 64-bit byte offset into the WAL stream, printed as two hexadecimal halves, such as 16/B374D848. LSNs only increase. Many recovery tools and settings use them: recovery_target_lsn, the start and end positions of a base backup, and replication progress.
You can read the current write position and ask which file holds it:
SELECT pg_current_wal_lsn() AS lsn,
pg_walfile_name(pg_current_wal_lsn()) AS wal_file;
SHOW wal_level;
SHOW wal_segment_size;pg_current_wal_lsn() works on a primary. On a standby, use pg_last_wal_replay_lsn().
Segments and file names
The WAL is stored in the pg_wal directory as fixed-size files called segments. The default size is 16 MB. It can be changed only when the cluster is created (initdb --wal-segsize), and wal_segment_size reports the value.
Each segment name is 24 hexadecimal characters in three groups of eight:
| Part | Width | Meaning |
|---|---|---|
| Timeline ID | 8 hex digits | Which history branch the file belongs to |
| Log number | 8 hex digits | High 32 bits of the LSN |
| Segment number | 8 hex digits | Which segment inside that log number |
With 16 MB segments, the last group is the top byte of the LSN's low 32 bits, shown in eight digits. For LSN 16/B374D848 on timeline 1, the file is 0000000100000016000000B3. The offset inside the file is the remaining 24 bits, 74D848.
The names sort in the order the WAL was produced, so a tool can find "all segments needed after this point" by comparing names. The %f placeholder that you will use in archive_command and restore_command stands for exactly this file name. The %p placeholder stands for its path.
Checkpoints and where replay starts
A checkpoint is a point where PostgreSQL guarantees that all changes logged before it have been written to the data files. The checkpoint record in the WAL stores a redo pointer, the LSN where replay must start if a crash happens later.
This is important for backups. A base backup copies data files while the server keeps running, so the copied files are a blend of states from different moments. The backup is made usable by two facts:
- The backup starts with a checkpoint, so replay has a known starting LSN.
- WAL from that start LSN through the end of the copy is kept with the backup.
Replaying that range corrects every page that changed during the copy. This is why the pg_basebackup example in this tutorial uses -X stream. Without the WAL from the backup window, the copy cannot be made consistent.
Recycling: why archiving is needed
PostgreSQL does not keep WAL forever. After a checkpoint, segments older than the redo pointer are no longer needed for crash recovery. They are renamed and reused or removed, which keeps pg_wal small. Exceptions are segments held for replication slots, wal_keep_size, or segments that have not yet been archived.
On its own, then, pg_wal cannot supply history from yesterday. Continuous archiving fills the gap. When archive_mode is on, PostgreSQL will not recycle a completed segment until archive_command has reported success for it. The archive becomes the long-term store, and pg_wal stays a short-term working area. The next chapter turns this on.
Choosing `wal_level`
The wal_level setting controls how much information goes into each record:
| Value | Use |
|---|---|
| `minimal` | Crash recovery only. Cannot be used for archiving or replication. |
| `replica` | Adds what is needed for WAL archiving, base backups and physical replication. Default since PostgreSQL 10. |
| `logical` | Adds what logical decoding needs. Also works for PITR but writes more WAL. |
A PITR setup needs at least replica. Changing wal_level requires a restart. If you switch to replica after taking a backup under minimal, the old backup cannot be used for archive recovery. Take a fresh base backup after any such change.
Looking inside the WAL
The pg_waldump tool decodes segment files, which helps you check what the archive contains. Run it as the operating system user that owns the files, and name a segment in pg_wal:
sudo -u postgres pg_waldump -r Transaction -n 5 \
/var/lib/postgresql/16/main/pg_wal/000000010000000000000003The -r Transaction option limits output to commit and abort records, and -n 5 stops after five records. Each line shows the LSN, the previous record's LSN, the transaction ID and, for commits, a timestamp. If the server binaries are not on your PATH, give the full path to pg_waldump, which on Debian-based systems is under /usr/lib/postgresql/16/bin/.
Summary of the mechanism
A base backup gives a starting state plus a start LSN. The archive supplies every WAL segment from that LSN onward, in file-name order. Recovery applies records one after another, checking commit timestamps, transaction IDs, LSNs or restore point names against your target. When the target is reached, replay stops. The state of the cluster is then exactly what it was at that point, and any later change in the archive is ignored.
Exercise
A server on timeline 1 uses the default 16 MB segment size. Its current LSN is 2A/7F001234. What is the name of the WAL segment file that holds this LSN, and why must a commit record, not the SQL text, be what lets recovery stop at a time target?
Show answer
The file is 000000010000002A0000007F. The timeline is 00000001, the high half of the LSN is 0000002A, and the segment number is the top byte of the low half, 7F, written as 0000007F. Recovery cannot read SQL because the WAL stores physical block changes, not statements. The commit record of each transaction stores its commit timestamp, so recovery compares that timestamp to recoverytargettime and stops at the right commit.