34.5. PostgreSQL Replication and Failover
Physical streaming replication ships the primary's write-ahead log to standbys, which replay it into identical copies of the cluster. The standby is a real server - it serves reads, it can back up the primary without loading it, and it can be promoted to primary in seconds because its copy is already current. This section builds the arrangement by hand on two nodes so that every piece the automation later hides is visible once:
| Role | Host | Client address | Replication address |
|---|---|---|---|
| Primary (to start) | db1 |
192.168.236.11 | 192.168.237.11 |
| Standby, later promoted | db2 |
192.168.236.12 | 192.168.237.12 |
Replication traffic uses the 192.168.237.0/24 network on purpose: it
is the network whose loss means "the replica is cut off", and you want
that fact visible in pg_stat_replication rather than entangled with
client traffic.
Figure 34.3. The two mechanisms this section exercises. Above: a
committed transaction travels from the primary's WAL to the standby's
disk and then into its visible state, each step named by an LSN that
pg_stat_replication exposes. Below: promotion forks the WAL history
into a new timeline; anything the old primary wrote after the fork must
be rewound or discarded before it can rejoin.
34.5.1. Streaming Replication, Replication Slots, and Standby Setup
The primary needs four things: a listener on the replication network,
a replication login, room in its WAL retention for a lagging standby,
and a pg_hba.conf line admitting the replication connection. On db1:
$ sudo -u postgres psql -v ON_ERROR_STOP=1 -c "ALTER SYSTEM SET listen_addresses = 'localhost,192.168.236.11,192.168.237.11';" -c "ALTER SYSTEM SET wal_log_hints = 'on';" -c "ALTER SYSTEM SET max_wal_senders = 10;" -c "ALTER SYSTEM SET wal_keep_size = '256MB';" -c "CREATE ROLE replicator WITH REPLICATION LOGIN PASSWORD 'repl-secret';"
ALTER SYSTEM
ALTER SYSTEM
ALTER SYSTEM
ALTER SYSTEM
CREATE ROLE
Read each setting against its job. listen_addresses grows to the
replication network. wal_log_hints = on full-page-logs hint-bit
changes, which costs a little WAL and buys the ability to run
pg_rewind later (section 34.5.4) on a cluster created without data
checksums. max_wal_senders reserves room for WAL-streaming
connections. wal_keep_size keeps at least 256 MB of WAL on the
primary beyond what it needs for itself, so a standby that falls
behind - or restarts - can catch up from the primary instead of
needing a fresh base backup. And replicator is a dedicated role with
exactly one privilege, REPLICATION, plus a login password: the
standby will connect as this role and nothing else.
The authentication line for replication is separate from ordinary client access. On db1:
$ echo "hostssl replication replicator 192.168.237.0/24 scram-sha-256" | sudo tee -a /etc/postgresql/17/main/pg_hba.conf
hostssl replication replicator 192.168.237.0/24 scram-sha-256
tee -a appends and echoes the line back. The special database name
replication matches only the physical replication protocol, so this
line admits standbys and admits nothing else. Restart to apply the
listener, then confirm both settings:
$ sudo pg_ctlcluster 17 main restart
The restart is silent. Then:
$ sudo -u postgres psql -Atc "show listen_addresses; show wal_log_hints;"
localhost,192.168.236.11,192.168.237.11
on
Both took. The standby's copy comes from pg_basebackup, run over
that network with the same TLS verification the application uses. On
db2, first stop and clear the cluster the package install created -
this destroys db2's data directory; in the walkthrough it is an
empty cluster, but the pattern must never be applied to a server with
data you want:
$ sudo pg_ctlcluster 17 main stop
The stop is silent. Then clear the directory:
$ sudo rm -rf /var/lib/postgresql/17/main && sudo install -d -o postgres -g postgres -m 700 /var/lib/postgresql/17/main
Also silent - one command that removes the old directory and
recreates it empty and postgres-owned. Then clone the primary, on
db2:
$ sudo -u postgres env PGPASSWORD=repl-secret pg_basebackup -d "host=192.168.237.11 port=5432 user=replicator sslmode=verify-full sslrootcert=/etc/ssl/handbook/ca.crt" -D /var/lib/postgresql/17/main -Fp -Xs -P -R 2>&1 | tail -3
22186/39861 kB (55%), 0/1 tablespace
39871/39871 kB (100%), 0/1 tablespace
39871/39871 kB (100%), 1/1 tablespace
The same options as section 34.4.2 plus one that matters here:
| Option | Description |
|---|---|
-R |
Write standby.signal and a primary_conninfo line into the copy, so it starts as a standby of its source |
-d <connstring> |
Source server; the replication network address, the replicator role, and verify-full TLS |
-Xs |
Stream WAL during the backup so the copy is consistent without touching the archive |
The tail of the progress report is shown; the command prints one such
line at each tablespace as it completes. The copy that lands in
/var/lib/postgresql/17/main is db1's cluster at one LSN, marked as a
standby by -R. Two adjustments make it db2's own rather than a
carbon copy of db1: the copied postgresql.auto.conf still carries
db1's archive and recovery-target settings from section 34.4, and the
primary_conninfo that -R wrote does not verify the primary's
certificate. The file on db2,
/var/lib/postgresql/17/main/postgresql.auto.conf, needs these lines
in place of what it inherited:
listen_addresses = 'localhost,192.168.236.12,192.168.237.12'
archive_mode = 'off'
ssl = 'on'
ssl_cert_file = '/etc/ssl/handbook/pg-db2.crt'
ssl_key_file = '/etc/ssl/handbook/pg-db2.key'
ssl_ca_file = '/etc/ssl/handbook/ca.crt'
primary_conninfo = 'user=replicator host=192.168.237.11 port=5432 sslmode=verify-full sslrootcert=/etc/ssl/handbook/ca.crt'
The inherited archive_command, restore_command,
recovery_target_time, and recovery_target_action lines must be
deleted rather than kept: the standby must not re-archive db1's
segments, and a stray recovery target would confuse any future
recovery. listen_addresses and the certificate files are db2's own -
a standby serves its own TLS identity, which is what lets a promoted
standby keep the same client-facing verification story. Finally, put
the replication password where the standby's restart can find it
without help, on db2:
$ sudo install -o postgres -g postgres -m 600 /dev/null /var/lib/postgresql/.pgpass
The command creates an empty postgres-owned file and prints nothing;
put the connection line in it with an editor:
192.168.237.11:5432:replication:replicator:repl-secret
A .pgpass line has the form host:port:database:user:password, and
replication as the database field matches replication connections;
with the file in place, primary_conninfo needs no password and the
standby can reconnect after any restart. Start the standby, on db2:
$ sudo pg_ctlcluster 17 main start
Silent on success. Ask the cluster what it now is, on db2:
$ sudo -u postgres psql -c "SELECT pg_is_in_recovery() AS in_recovery;"
in_recovery
-------------
t
(1 row)
t - the standby signal and primary_conninfo did their job; the
server came up in recovery, replaying db1's WAL. The cluster listing
shows the same fact in Debian's terms:
$ pg_lsclusters
Ver Cluster Port Status Owner Data directory Log file
17 main 5432 online,recovery postgres /var/lib/postgresql/17/main /var/log/postgresql/postgresql-17-main.log
online,recovery - running, and in recovery rather than in
production. From the primary's side the connection is visible with
everything an administrator needs to know about it, on db1:
$ sudo -u postgres psql -x -c "SELECT client_addr, state, sync_state, sent_lsn, replay_lsn FROM pg_stat_replication;"
-[ RECORD 1 ]---------------+-------------------------
client_addr | 192.168.237.12
state | streaming
sync_state | async
sent_lsn | 0/7000060
replay_lsn | 0/7000060
One row per connected WAL receiver. client_addr is the standby;
state is streaming; sync_state is async, the default this
section keeps until 34.5.2. The two LSNs are the health check:
sent_lsn is how far the primary has shipped, replay_lsn how far the
standby has made visible, and the gap between them - measured in
bytes of WAL - is the replication lag. Equal values mean the standby
is current. Prove the pipeline end to end: write on the primary, on
db1:
$ sudo -u postgres psql -d inventory -c "INSERT INTO app.items (name, quantity) VALUES ('replicated-row', 42);"
INSERT 0 1
Read it back on the standby, on db2:
$ sudo -u postgres psql -d inventory -c "SELECT count(*) FROM app.items WHERE name = 'replicated-row';"
count
-------
1
(1 row)
The row crossed the network as WAL, replayed into db2's copy within the moment between the two commands. Every read a standby serves is read from this replayed state; every write still goes to the primary.
wal_keep_size, used above, is the simple retention model: keep the
last 256 MB and hope a lagging standby needs less. The precise model
is the replication slot - pg_create_physical_replication_slot()
on the primary, the standby connecting with
primary_slot_name set in its primary_conninfo - which pins WAL
per-standby for exactly as long as that standby is behind, no more
and no less. The trade is the one from section 34.4.3: a slot whose
standby never returns keeps WAL forever and fills the data directory,
so slots come with monitoring or with the watchdog-managed automation
of section 34.6, which creates and drops them as replicas come and go.
Patroni, when it arrives, will manage slots for you
(use_slots: true in its configuration).
34.5.2. Synchronous and Asynchronous Commit and Replication Lag
Asynchronous replication, the default, answers the application as soon as the primary has made the commit durable locally. If the primary's machine dies before the standby receives a transaction, that transaction is lost - the RPO discussion of section 34.1.3 made concrete. Synchronous replication removes that window: the primary waits until a named standby has made the commit durable there before acknowledging. The price is the mirror image: every write now costs a round trip to the standby, and a missing standby stalls writes entirely. It is a durability dial, not an optimization.
Turn it on for the single standby, on db1:
$ sudo -u postgres psql -c "ALTER SYSTEM SET synchronous_standby_names = '*';"
ALTER SYSTEM
synchronous_standby_names = '*' names every connected standby as a
sync candidate; pg_reload_conf() applies it without a restart
because commit policy is per-transaction, not a startup parameter.
Apply the reload, on db1:
$ sudo -u postgres psql -c "SELECT pg_reload_conf();"
pg_reload_conf
----------------
t
(1 row)
The t confirms the server re-read its configuration. Confirm the
standby is now in sync mode, on db1:
$ sudo -u postgres psql -c "SELECT application_name, sync_state FROM pg_stat_replication;"
application_name | sync_state
------------------+------------
17/main | sync
(1 row)
sync_state changed from async to sync; the standby reports as
17/main because Debian's cluster_name is what a standby sends
unless primary_conninfo sets application_name. From this moment
every commit on db1 waits for db2's flush acknowledgment.
Now the failure the trade buys. Stop the standby, on db2:
$ sudo pg_ctlcluster 17 main stop
The stop is silent. The cluster listing shows what was lost, on db2:
$ pg_lsclusters
Ver Cluster Port Status Owner Data directory Log file
17 main 5432 down,recovery postgres /var/lib/postgresql/17/main /var/log/postgresql/postgresql-17-main.log
down,recovery - the standby is gone, and with it the only sync
candidate. Back on db1, attempt a write in a second window and watch
it not return:
$ sudo -u postgres psql -d inventory -c "INSERT INTO app.items (name, quantity) VALUES ('sync-blocked', 1);"
The session produces no output and does not return - the commit is durable on the primary but the sync policy is waiting for a standby flush that can never arrive. Prove where it is waiting, from the first window on db1:
$ sudo -u postgres psql -d inventory -Atc "SELECT pid, wait_event_type, wait_event FROM pg_stat_activity WHERE query LIKE '%sync-blocked%';"
15400|IPC|SyncRep
15401||
wait_event_type IPC, wait_event SyncRep - the same
pg_stat_activity diagnosis as the lock exercise, one row per
session: the blocked insert, and the querying session itself (its own
query text contains the search string, which is why it matches).
SyncRep is the synchronous-replication wait point; a session parked
there is not deadlocked, it is waiting for commit policy.
Two ways out. Bringing a sync standby back releases the wait
immediately; abandoning the durability level does too. Take the
second path deliberately: in the second window, cancel the blocked
session the usual way - Ctrl+C sends the same cancellation request
pg_cancel_backend sends - and it returns with
ERROR: canceling statement due to user request. Then, from the
first window on db1, drop the policy so writes no longer wait for a
standby:
$ sudo -u postgres psql -c "ALTER SYSTEM SET synchronous_standby_names = '';"
ALTER SYSTEM
The empty string clears the sync list. Reload to apply it, on db1:
$ sudo -u postgres psql -c "SELECT pg_reload_conf();"
pg_reload_conf
----------------
t
(1 row)
The reload applies the cleared policy immediately: the next commit that arrives is acknowledged as soon as the primary flushes locally, with no standby wait. Confirm writes flow again, on db1:
$ sudo -u postgres psql -d inventory -c "INSERT INTO app.items (name, quantity) VALUES ('async-ok', 1);"
INSERT 0 1
Asynchronous commit is back, and the cancelled write is fully rolled
back - a SyncRep wait is a commit in flight, so its cancellation
leaves nothing half-committed. A session left waiting instead of
cancelled would complete on its own the moment the policy clears or
a standby returns; cancelling is the operator's choice to abandon
that one transaction rather than wait. The case to treat with
respect in production is the one the experiment cannot show here: a
commit that was acknowledged just before the standby vanished is
safe, and the interesting ambiguity is a transaction in flight at
the moment of failure - which section 34.7.3 examines under
automated failover. Bring the standby back, on db2:
$ sudo pg_ctlcluster 17 main start
Silent; db2 resumes streaming from where it stopped - the WAL was
waiting in db1's pg_wal, retained by wal_keep_size. Lag, measured
between sent_lsn and replay_lsn (or by the replay_lag column
when timestamps are wanted), is the number to watch under load: it is
the RPO of an asynchronous cluster at any given moment, and it is
what maximum_lag_on_failover in the Patroni configuration will
later convert into a promotion veto.
34.5.3. Controlled Promotion, Fencing, and Preventing Two Writable Primaries
Promotion converts a standby into a primary: it stops replay, opens for writes, and forks WAL history onto a new timeline. Controlled means the old primary is known to be not writing before the new one starts. The exercise stops db1 first, then promotes db2.
Know which timeline history you are forking from while db1 is still running, on db1:
$ sudo -u postgres psql -Atc "select timeline_id from pg_control_checkpoint();"
2
Timeline 2 - inherited from the PITR promotion in section 34.4.4. Now stop the primary, on db1:
$ sudo pg_ctlcluster 17 main stop
The command prints nothing on success; the cluster is down, and
nothing anywhere is accepting writes for this application. Promote the
standby, on db2:
$ sudo -u postgres psql -Atc "select pg_promote(wait => true);"
t
pg_promote() is the in-band way to promote - no restart, no file
tricks, and wait => true blocks until the promotion completes. The
single t is its return. Confirm the new state, on db2:
$ sudo -u postgres psql -c "select pg_is_in_recovery();"
pg_is_in_recovery
-------------------
f
(1 row)
f - db2 is a primary. Its timeline confirms the fork, on db2:
$ sudo -u postgres psql -Atc "select timeline_id from pg_control_checkpoint();"
3
Timeline 3, one past db1's 2 - the fork happened exactly at promotion. And the application can write, on db2:
$ sudo -u postgres psql -d inventory -c "INSERT INTO app.items (name, quantity) VALUES ('after-promotion', 5);"
INSERT 0 1
The insert commits on the promoted server. The timeline is even visible in WAL file names, on db2:
$ sudo -u postgres psql -Atc "select pg_walfile_name(pg_current_wal_lsn());"
000000030000000000000008
The first eight hex digits - 00000003 - are the timeline ID. Every
segment db2 writes from now on is on timeline 3, and db1's copy is
stuck at the end of timeline 2.
The dangerous sentence in this whole section is "db1 will come back". When a former primary restarts with its own data directory, it believes it is the primary on timeline 2 with the last write authority it ever had. Start it as-is and you have two writable primaries: db1 answering on its listener for any client that still points at it, and db2 with the promoted history - each happily accepting writes that the other will never see. PostgreSQL will not stop you. The defenses, in order of strength:
- Fencing: the old primary's machine is provably stopped or cut off - powered off, its network dropped, its storage detached. This is the Chapter 32 guarantee, and it is the only one that covers a crashed or wedged machine.
- Startup state: a cleanly shut-down primary restarts in recovery
only if
standby.signalexists in its data directory - the mechanism the rejoin procedure in section 34.5.4 deliberately installs. Without it, a restarted primary resumes as a primary. recovery.signal/standby.signalby hand: the operator who moves a data directory decides its role by creating one file or the other before the first start.
Manual promotion is exactly as safe as the operator's discipline: stop the old primary, keep it stopped until it has been rewound and re-signaled, and only then let it run again. Everything Patroni does in section 34.6 is this discipline executed by software, with a lease and a watchdog replacing the operator's alertness.
34.5.4. Rejoining a Former Primary and Checking Timeline Divergence
The old primary's data directory is nearly right: it contains every
transaction up to the fork point, and then either nothing (it was
stopped cleanly before the standby promoted - the recorded case) or a
few divergent transactions it accepted after the promotion. Rejoining
means discarding the divergence and resuming as a standby of timeline
3. pg_rewind is the tool that does the discarding cheaply: it
compares the two timelines, works out the fork, and reverts the old
primary's pages back to that fork point - copying only what changed -
so the directory can follow the new timeline forward instead of
starting over. The prerequisites were arranged earlier:
wal_log_hints = on (set in section 34.5.1) or data checksums, and a
superuser connection from the old primary to the new one.
Admission first. The promoted db2 must accept db1's rewind connection
- a replication-network pg_hba.conf entry and a password for the
postgres role, on db2:
$ echo -e "host all all 192.168.237.0/24 scram-sha-256\nhostssl replication replicator 192.168.237.0/24 scram-sha-256" | sudo tee -a /etc/postgresql/17/main/pg_hba.conf
host all all 192.168.237.0/24 scram-sha-256
hostssl replication replicator 192.168.237.0/24 scram-sha-256
tee -a echoes both lines as it appends them. The first admits
database connections from the replication network - pg_rewind
connects as a superuser over an ordinary connection, which is why it
is needed; the second re-states the replication entry db2 inherited,
making the file self-contained now that db2 is the primary. Give the
rewind channel a password, on db2:
$ sudo -u postgres psql -c "ALTER ROLE postgres PASSWORD 'postgres-secret';"
ALTER ROLE
The postgres password exists for this maintenance channel only -
local administration on db2 still goes through sudo -u postgres,
and the password can be cleared again after the rejoin. Apply the
authentication lines, on db2:
$ sudo -u postgres psql -c "SELECT pg_reload_conf();"
pg_reload_conf
----------------
t
(1 row)
The reload applies the pg_hba.conf change without dropping
sessions.
Run the rewind, on db1, with the cluster stopped:
$ sudo -u postgres env PGPASSWORD=postgres-secret /usr/lib/postgresql/17/bin/pg_rewind --target-pgdata=/var/lib/postgresql/17/main --source-server="host=192.168.237.12 port=5432 user=postgres dbname=postgres" 2>&1 | tail -2
pg_rewind: servers diverged at WAL location 0/80000A0 on timeline 2
pg_rewind: no rewind required
The two lines are pg_rewind's verdict, and they are worth reading
slowly. The first is the analysis: db2 (the source) and db1 (the
target) share history up to WAL location 0/80000A0 on timeline 2 -
the fork point. The second is the outcome: no rewind required,
because db1 wrote nothing after the fork - it was stopped cleanly
in section 34.5.3 before db2 promoted, so there are no divergent pages
to revert. This is the good case, and it is not the common one: an
old primary that crashed mid-write, or that kept serving for seconds
after a network cut, has divergence, and pg_rewind then reports the
same first line and follows it by actually copying pages back. Either
way the directory is now safe to point at timeline 3.
The rewind aligned the data; the operator still has to install the
role: db1 must restart as a standby of db2, not as a primary. Three
edits on db1 do it - /var/lib/postgresql/17/main/postgresql.auto.conf
needs the recovery leftovers from section 34.4.4 removed
(restore_command, recovery_target_time, recovery_target_action),
archive_mode turned off for the manual exercise, and
primary_conninfo aimed at db2:
archive_mode = 'off'
listen_addresses = 'localhost,192.168.236.11,192.168.237.11'
primary_conninfo = 'user=replicator host=192.168.237.12 port=5432 sslmode=verify-full sslrootcert=/etc/ssl/handbook/ca.crt'
Update /var/lib/postgresql/.pgpass on db1 to db2's address:
192.168.237.12:5432:replication:replicator:repl-secret
And create the standby signal:
$ sudo -u postgres touch /var/lib/postgresql/17/main/standby.signal
The empty file is the whole instruction: start in recovery, connect
per primary_conninfo, follow the source's timeline. Start db1 and
verify what it became:
$ sudo pg_ctlcluster 17 main start
Silent. Then, on db1:
$ sudo -u postgres psql -Atc "select pg_is_in_recovery();"
t
The single t says db1 came up in recovery. The control file's view,
on db1:
$ sudo /usr/lib/postgresql/17/bin/pg_controldata /var/lib/postgresql/17/main | grep -E "Latest checkpoint.s TimeLineID|Database cluster state"
Database cluster state: in archive recovery
Latest checkpoint's TimeLineID: 2
The output decodes precisely: the cluster state is
in archive recovery - a standby, replaying; and the
latest checkpoint is still on timeline 2 at this moment because
recovery begins where db1's history ended and follows db2's timeline
history file forward from there. Check the replication from the new
primary, on db2:
$ sudo -u postgres psql -x -c "SELECT client_addr, state, sent_lsn, replay_lsn FROM pg_stat_replication;"
-[ RECORD 1 ]---------------+-------------------------
client_addr | 192.168.237.11
state | streaming
sent_lsn | 0/80048F0
replay_lsn | 0/80048F0
The roles have fully swapped: db2, the former standby, is streaming
WAL to db1, the former primary, and the LSNs match - db1 is current
on timeline 3's history. The divergence check that matters before
trusting the pair: on db1, pg_is_in_recovery() must be t and stay
t; on db2 it must be f; and any transaction committed on db2 after
the fork must appear on db1 while nothing db1 ever wrote after the
fork exists anywhere. The rejoin is complete when all three hold - and
that is the state the automation in section 34.6 reaches by itself,
with the same two tools: pg_rewind for divergence, standby.signal
plus primary_conninfo for the role.
34.5.5. Logical Replication and Migration Boundaries
Physical replication ships pages of WAL and therefore requires the same major version, the same architecture, and the same entire cluster - it replicates everything and joins nothing. Logical replication is the other family: the source decodes committed row changes from a publication and the subscriber applies them as ordinary inserts, updates, and deletes. Because the payload is rows, not pages, the two sides may differ in PostgreSQL major version, database, schema layout, or even run on different hosts with different roles - the boundaries are what make it useful:
- Selective replication. A publication names specific tables:
CREATE PUBLICATION app_public FOR TABLE app.items, app.pitr_log;on the source; the subscriber creates matching tables and runsCREATE SUBSCRIPTION app_sub CONNECTION '...' PUBLICATION app_public;. One service's tables can feed a reporting server without shipping the whole cluster. - Major-version migration. A subscription from a new-version cluster to the old one keeps the new one current while applications are moved; this is the rolling-upgrade path that physical replication cannot offer (section 34.3.3).
- Row-level shaping. Publications can filter rows (list columns,
restrict with a
WHEREclause), so the subscriber can receive a subset - something no page-level copy can do.
The boundaries are equally concrete. Logical replication requires
wal_level = logical on the source (a restart, and more WAL retained
than replica), and it carries DML only: DDL changes - new
tables, new columns, type changes - must be applied to both sides by
the operator, in an order that keeps the subscriber's tables compatible
with what arrives. Sequences are not replicated, so identity columns
on the subscriber do not advance from replication and must be
re-synchronized before the subscriber could ever become a writer.
Large objects are not carried. And conflicts - a row changed on the
subscriber in a way the incoming change contradicts - stop the
subscription's apply worker until an operator resolves them, which is
why subscribers are kept read-only by discipline rather than by
mechanism.
For failover, logical replication is the wrong tool and physical replication is the right one; for migration and selective delivery, the reverse. This chapter exercises the physical family end to end; the logical family appears again only where its boundaries justify it - a version upgrade or a partial copy - and its configuration surface is exactly the two statements above plus the connection string discipline already covered.