Sub topic 14
Timelines and Rejoining the Old Primary with pg_rewind
Prerequisites
This chapter assumes you have built a primary and a hot standby as in the earlier chapters. You should know what promotion does and how to read a WAL file name. You should also be comfortable stopping and starting a server and editing postgresql.conf.
Why timelines exist
When you promote a standby, it stops replaying WAL from the old primary and starts writing its own. From that moment two histories exist: the one the old primary may still be writing, and the one the new primary is writing. PostgreSQL labels each history with a timeline ID, a number that starts at 1 and goes up by one each time a server is promoted or recovers to a point in time.
The timeline ID keeps WAL from different histories apart. Without it, two servers could write different WAL under the same file name and the same LSN range, and a standby could not tell which one to trust.
You can see the timeline in three places:
- The first 8 hex digits of a WAL file name.
000000020000000000000005is the fifth segment on timeline 2. - A
.historyfile inpg_wal, for example00000002.history. - SQL functions and views.
-- On any server: the timeline of the latest checkpoint
SELECT timeline_id, checkpoint_lsn FROM pg_control_checkpoint();
-- On a standby: the timeline it is currently receiving
SELECT received_tli, status FROM pg_stat_wal_receiver;Reading a history file
When a standby is promoted from timeline 1 to timeline 2, it writes 00000002.history. The file records where the new timeline branched off:
cat /var/lib/postgresql/data/pg_wal/00000002.history1 0/3000060 no recovery target specifiedEach line has the parent timeline ID, the LSN where the switch happened (0/3000060), and the reason. Timeline 2 contains everything from timeline 1 up to that LSN, then its own WAL after it. The LSN is the divergence point.
Why the old primary cannot simply rejoin
Suppose the old primary was still running, or committed some transactions asynchronously before it failed. Its data directory now contains changes after 0/3000060 that the new primary never received. If you start it as a standby of the new primary, the two copies are already different. Physical replication replays WAL byte for byte on the assumption that the starting point is identical, so it will not repair this. At best the standby refuses to start streaming with an error such as "requested timeline 2 is not a child of this server's history". At worst it silently holds corrupted data.
There are two ways to fix it:
- Rebuild the old primary from a fresh
pg_basebackup. This always works but copies the whole cluster. - Rewind it with
pg_rewind, which copies only what changed since the divergence point. This is much faster on large databases.
How pg_rewind works
pg_rewind compares the old primary (the target) with the new primary (the source). The steps are:
- It finds the last checkpoint on the target that lies before the divergence point, using the timeline history.
- It reads the target's WAL from that checkpoint onward and records every data block the target changed.
- It copies those blocks from the source. It also copies all non-relation files, such as configuration,
pg_xact, and so on, in full. - It writes a
backup_labelso that, when started, the target replays WAL from the source's timeline starting at that earlier checkpoint.
The result is a data directory equivalent to a fresh copy of the source. The old primary's orphaned changes are overwritten, because the blocks they touched are fetched again.
Requirements
- Block change tracking must be possible. Either the cluster was initialized with data checksums (
initdb --data-checksums), orwal_log_hints = onis set. Changingwal_log_hintsneeds a restart, so set it before you need it. It must be on in the old primary's history, not just after the failure. full_page_writes = on, which is the default.- The target must be shut down cleanly. If it crashed, start it and stop it again so it completes crash recovery. Recent versions do this for you unless you pass
--no-ensure-shutdown. - WAL since divergence must still be available on the target. If it was recycled, supply it from an archive with
--restore-target-wal, which uses the target'srestore_command. This is one reason to combine streaming with WAL archiving. - The source must have checkpointed after promotion. If the new primary was just promoted, run
CHECKPOINT;on it first. Otherwise its control file does not yet show the new timeline. - The connecting user needs privileges. A superuser works. A least-privilege role needs execute rights on a few functions.
-- On the new primary: a least-privilege role for pg_rewind
CREATE ROLE rewinder WITH LOGIN PASSWORD 'change-me';
GRANT EXECUTE ON FUNCTION pg_catalog.pg_ls_dir(text, boolean, boolean) TO rewinder;
GRANT EXECUTE ON FUNCTION pg_catalog.pg_stat_file(text, boolean) TO rewinder;
GRANT EXECUTE ON FUNCTION pg_catalog.pg_read_binary_file(text) TO rewinder;
GRANT EXECUTE ON FUNCTION pg_catalog.pg_read_binary_file(text, bigint, bigint, boolean) TO rewinder;The role also needs a pg_hba.conf entry that allows it to connect to the postgres database from the old primary's address.
Running pg_rewind
Run these commands on the old primary's host, as the user that owns the data directory:
# 1. Make sure the old primary is stopped cleanly
pg_ctl -D /var/lib/postgresql/data stop -m fast
# 2. Rewind it against the new primary and prepare it as a standby
pg_rewind \
--target-pgdata=/var/lib/postgresql/data \
--source-server='host=new-primary.example.com port=5432 user=rewinder dbname=postgres password=change-me' \
--write-recovery-conf \
--progress
# 3. Start it; it replays WAL from timeline 2 and follows the new primary
pg_ctl -D /var/lib/postgresql/data start--write-recovery-conf creates standby.signal and adds primary_conninfo to postgresql.auto.conf. It copies the connection string you gave for --source-server, so that string uses the rewinder role. Open the file and replace it with the replicator role and an application_name if you want the old primary to behave like your other standbys. If you use replication slots, create a slot for it on the new primary and set primary_slot_name.
After startup, confirm the result on the old primary and on the new primary:
-- On the rewound server: should be true, with the new timeline
SELECT pg_is_in_recovery();
SELECT received_tli, status FROM pg_stat_wal_receiver;
-- On the new primary: the old primary should appear here
SELECT application_name, state, sync_state, replay_lag
FROM pg_stat_replication;Gotchas
- Data is lost, by design. Transactions that were committed on the old primary after the divergence point and never reached the new primary are discarded.
pg_rewinddoes not merge anything. With asynchronous replication, expect to lose a small window of commits. Synchronous replication narrows that window, but the old primary can still hold changes that never reached the new primary. recovery_target_timeline. Since PostgreSQL 12 it defaults tolatest, so a standby follows the newest timeline in the archive or on the primary. If you have set it tocurrent, a standby stays on its old timeline and will not follow a promotion.- Configuration files are overwritten.
pg_rewindcopies everything outside relation files from the source, includingpostgresql.confif it lives in the data directory. Keep machine-specific settings, such aslisten_addressesor a differentdata_directory, in a file outside the data directory, or save a copy first. - Failed rewinds are not resumable. If
pg_rewindstops halfway, the target is in an inconsistent state. Run it again against the same source, or fall back to a newpg_basebackup. Do not start the server in between. - Do not reuse a diverged server without rewinding. Starting an old primary after another server has been promoted risks a split brain, where two servers accept writes. Fence the old primary by stopping it or blocking client traffic before you promote its replacement.
Choosing between pg_rewind and a rebuild
| Situation | Better choice |
|---|---|
| Large database, `wal_log_hints` or checksums were already on, WAL since divergence is available | `pg_rewind` |
| Small database where a copy takes a few minutes | `pg_basebackup` (simpler, fewer prerequisites) |
| `wal_log_hints` was off and checksums are disabled | `pg_basebackup` |
| Needed WAL has been recycled and there is no archive | `pg_basebackup` |
| Target data may be damaged, not just diverged | `pg_basebackup` |
Exercise
A standby was promoted and now shows timeline 2. The old primary is stopped, but pg_rewind fails with an error saying it cannot work without data checksums or wal_log_hints. What do you do now, and what should you change on the new cluster so this does not happen at the next failover?
Show answer
Rewinding is not possible for this server, because the old primary did not record the hint-bit changes it needs. Rebuild it with pg_basebackup from the new primary and start it as a standby. To prepare for the next failover, set wal_log_hints = on (a restart is required) on every server that could become a primary, or initialize clusters with --data-checksums. Setting it afterwards lets later rewinds work.