Sub topic 11
Promoting a Standby and Planning Failover
This chapter assumes you can run a working primary and a hot standby as set up in earlier chapters. You should also be comfortable with psql, pg_ctl, postgresql.conf, and the idea of WAL positions (LSNs). Here you will learn how to promote a standby, what changes when you do, and how to plan a failover so you lose as little data as possible and avoid two writable servers at once.
Switchover versus failover
Two situations lead to a promotion. They differ in how much control you have.
- Switchover is a planned role swap. The primary is healthy. You stop it cleanly, let the standby catch up, and promote the standby.
- Failover is an unplanned response to a primary that has failed or cannot be reached. You promote a standby and accept that it may be missing the last few transactions.
A clean switchover loses no data. A failover under asynchronous replication can lose the transactions that the standby had not yet received when the primary died.
What promotion does
A standby is a server in recovery. It replays WAL and refuses writes. Promotion ends recovery and makes the server a normal read-write primary. Internally, the server does these things:
- It stops the walreceiver and finishes replaying any WAL it already holds.
- It leaves recovery mode.
- It starts a new timeline, which means it picks the next timeline ID and writes a
.historyfile that records where the new timeline branched off. - It writes a checkpoint (an "end-of-recovery" checkpoint) and begins accepting writes.
The timeline matters. WAL file names and history files carry the timeline ID. Because the promoted server now writes WAL on timeline 2 instead of timeline 1, WAL from the old primary can no longer be mixed with it by accident. The timeline mechanism is covered in more depth in a later chapter.
How to promote
You have three equivalent ways to promote.
-- Run on the standby. Waits up to 60 seconds by default.
SELECT pg_promote();
-- Or choose whether to wait and for how long (seconds)
SELECT pg_promote(wait => true, wait_seconds => 30);# From the shell, as the postgres OS user
pg_ctl promote -D /var/lib/postgresql/datapg_promote() returns true when promotion succeeded (or, with wait => false, when the signal was sent). It requires superuser rights by default, or EXECUTE permission granted on the function. With pg_ctl promote, the command exits once the server has promoted when waiting is enabled, which is the default.
You can confirm the result from SQL:
SELECT pg_is_in_recovery(); -- false after a successful promotion
-- The timeline is also visible in the control data
SELECT timeline_id FROM pg_control_checkpoint();pg_is_in_recovery() returns false on a primary. timeline_id should have increased by one.
A safe switchover procedure
Follow these steps when you control both servers. The goal is that the standby has every WAL record the old primary wrote.
- Stop application writes, or point applications at a maintenance page.
- Stop the old primary cleanly with a fast or smart shutdown. A clean shutdown writes a shutdown checkpoint and sends all remaining WAL to connected standbys before the walsender exits.
``bash pg_ctl stop -D /var/lib/postgresql/data -m fast ``
- On the standby, check that it received and replayed everything. Compare the last replay position with the shutdown checkpoint location reported by
pg_controldataon the old primary.
```bash
On the old primary (server is stopped)
pg_controldata /var/lib/postgresql/data | grep "Latest checkpoint location" ```
``sql -- On the standby SELECT pg_last_wal_receive_lsn(), pg_last_wal_replay_lsn(); ``
The replay LSN should reach at least the position of the shutdown checkpoint record. If the standby is behind, wait. It will keep replaying WAL it already has.
- Promote the standby with
pg_promote()orpg_ctl promote. - Redirect clients to the new primary.
- Reconnect the old primary as a standby of the new one. Because it shut down cleanly after the standby had all its WAL, you can usually do this by creating
standby.signal, settingprimary_conninfoto the new primary, and starting it. If it fails with a timeline error, usepg_rewindor rebuild.
Planning for unplanned failover
When the primary dies, you face decisions that a switchover does not require. Plan them before an outage.
Choose which standby to promote
Promote the standby that has the most WAL. Compare the received and replayed positions on each candidate:
-- On each standby
SELECT pg_last_wal_receive_lsn() AS received,
pg_last_wal_replay_lsn() AS replayed,
pg_last_xact_replay_timestamp() AS last_replayed_commit;The standby with the highest received LSN has the most data. If it has received WAL it has not yet replayed, promotion first replays that WAL, so it is not lost. With synchronous replication, the standby that confirmed commits is the correct choice, because it is guaranteed to hold every acknowledged commit.
Understand the data-loss window
| Replication mode | What can be lost on failover |
|---|---|
| Asynchronous | Transactions committed on the primary but not yet received by the promoted standby. The size of the window is roughly the replication lag at the time of failure. |
| Synchronous (`remote_flush`, `on`) | No acknowledged commit, as long as you promote a standby that was in `synchronous_standby_names`. |
| Synchronous with `remote_write` | Acknowledged commits are in the standby's OS memory, so an OS crash on the standby could still lose them. |
Synchronous replication also changes availability. If the only synchronous standby disappears, commits on the primary wait until it returns or you change synchronous_standby_names. Chapter planning must weigh durability against availability.
Avoid split brain
Split brain means two servers both accept writes as primary. This happens when you promote a standby while the old primary is still alive but unreachable, for example during a network partition. Clients that can still reach the old primary keep writing to it. The two servers then hold different data and cannot be merged automatically.
PostgreSQL does not prevent this on its own. It has no built-in cluster manager or quorum. To avoid split brain:
- Make sure the old primary is truly stopped before you promote. This is called fencing. Examples are powering it off through a management interface, removing its network access, or stopping its service through an out-of-band channel.
- Use a single mechanism to decide who is primary, such as a failover tool with consensus. Patroni, repmgr, and pgautofailover are commonly used for this. They are outside the scope of this chapter, but the same ideas apply to them.
- Do not let applications choose a primary on their own without a rule for what happens when two servers claim the role.
Client routing after promotion
Applications must find the new primary. Common approaches:
- A virtual IP or DNS name that you move to the new primary.
- A proxy or load balancer that health-checks
pg_is_in_recovery(). - Multi-host connection strings with
target_session_attrs, which libpq (the PostgreSQL client library) uses to select a writable server.
psql "host=db1.example.com,db2.example.com dbname=app user=app target_session_attrs=read-write"With target_session_attrs=read-write, the client tries each host in turn and connects to the first one that accepts writes. Use primary instead if you want to match on recovery state only. Both settings need libpq from PostgreSQL 10 or later, and primary as a value arrived in 14.
After promotion: cleanup and follow-up
Checks to run on the new primary:
- Confirm
pg_is_in_recovery()isfalse. - Check
pg_stat_replicationfor the other standbys. They must reconnect to the new primary. Updateprimary_conninfoon each standby and reload or restart if needed. Standbys that follow the promoted server on the new timeline usually continue without a rebuild if they had not replayed past the branch point. - Review
synchronous_standby_names. It is a primary-side setting, so the new primary needs the right value for the surviving standbys, or commits can hang. - Check replication slots with
pg_replication_slots. Physical slots on the old primary do not move to the new one. Create slots on the new primary for standbys that use them, or they cannot retain WAL. - Rebuild or rewind the old primary, and add it back as a standby.
-- On the new primary: recreate a physical slot for a surviving standby
SELECT pg_create_physical_replication_slot('standby2');Common errors
- Promoting the wrong standby. A lagging standby loses more data. Always compare LSNs first.
- Forgetting fencing. Leads to split brain.
- Hanging commits after failover. The new primary still has
synchronous_standby_namesnaming standbys that no longer exist. Change the setting and reload. - Old primary will not follow. Its WAL went past the branch point, so the timelines diverged. Use
pg_rewind(requireswal_log_hintsor data checksums) or take a new base backup. - Standby cannot find the new timeline. Make sure it can read the
.historyfile, either by streaming or from the archive.
Exercise
Your primary has crashed and cannot be reached. You have two asynchronous standbys. Standby A reports received LSN 0/5000200. Standby B reports received LSN 0/50001F0. Which do you promote, what must you do about the old primary, and what is the data-loss risk?
Show answer
Promote standby A, because it has received more WAL (0/5000200 is greater than 0/50001F0). Before promoting, fence the old primary so it cannot accept writes if it comes back, which avoids split brain. Because replication is asynchronous, any transaction committed on the old primary but not received by A is lost. Afterward, point standby B at the new primary, and rebuild or rewind the old primary with pg_rewind before using it as a standby.
Exercise
After a switchover, the new primary accepts reads but every write hangs at COMMIT. Name the most likely cause and the fix.
Show answer
The new primary has synchronousstandbynames set to standbys that are not connected, so each commit waits for an acknowledgement that never arrives. Edit synchronousstandbynames to list only the standbys that are connected (or clear it for asynchronous mode), then reload the configuration with pgreloadconf(). Waiting commits are released once the setting no longer requires a missing standby.