34.7. Testing and Maintaining Automated Database Failover
An automated cluster earns trust only through rehearsed failure: until you have watched the quorum lose a member, a leader lose its lease, and a former primary rejoin, you own a hypothesis rather than a service. This section drives those events against the running cluster while an independent client records what the server actually acknowledged, then covers the maintenance that follows failures - rejoining and replacing members, backing up the consensus store and the database independently, and rebuilding both without ever letting a stale leader vote itself back into power.
34.7.1. Planned Switchover and Leader Loss During Independently Recorded Client Transactions
A failover test that only reads cluster status proves that the cluster
moved; it does not prove that applications kept a consistent view of
their own writes. The tests in this section therefore run a small
recorder on client1 that behaves like an application: it writes one
row per attempt through HAProxy, records the name of every attempt
the server acknowledged, and leaves failures in a separate log.
Save it as ~/debian-handbook/databases/client-writes.sh on client1
and make it executable:
$ chmod +x ~/debian-handbook/databases/client-writes.sh
The command prints nothing. The script itself:
#!/usr/bin/env bash
set -u
run=${1:-run}
cd /home/john/debian-handbook/databases
rm -f "client-committed-$run.log" "client-failed-$run.log" "client-rows-$run.log" "client-finished-$run"
for i in $(seq 1 30); do
name="client-$run-$i"
if PGOPTIONS='-c statement_timeout=5000' PGPASSWORD=owner-secret psql "host=192.168.236.14 port=5432 dbname=inventory user=app_owner sslmode=verify-full sslrootcert=/etc/ssl/handbook/ca.crt connect_timeout=3" \
-Atc "INSERT INTO app.items (name, quantity) VALUES ('$name', 1) RETURNING id" >>"client-rows-$run.log" 2>>"client-failed-$run.log"; then
echo "$name" >>"client-committed-$run.log"
else
echo "$name" >>"client-failed-$run.log"
fi
sleep 1
done
touch "client-finished-$run"
The argument names the run so each exercise gets clean logs. Each
attempt is one transaction with a unique name and a 5-second statement
timeout on top of the 3-second connect timeout - every wait in the
path is bounded, as section 34.6.8 requires. An attempt lands in the
committed log only if psql exited zero, which for this statement
means the server acknowledged the commit; failures append the
client-side error text and the attempt's name to the failure log.
The script is deliberately dumb - it does not retry a name, so a
name in the committed log means exactly one acknowledged insert.
The first exercise is the controlled one: move leadership to db2 while the recorder runs. In a second window on client1, start the recorder; it prints nothing while it runs and finishes by itself after about half a minute:
$ ~/debian-handbook/databases/client-writes.sh baseline
While it runs, perform the switchover from the first window, on db1:
$ sudo patronictl -c /etc/patroni/config.yml switchover --leader db1 --candidate db2 --force
Current cluster topology
+ Cluster: handbook (7712536661967524420) ------+----+-----------+
| Member | Host | Role | State | TL | Lag in MB |
+--------+----------------+---------+-----------+----+-----------+
| db1 | 192.168.237.11 | Leader | running | 1 | |
| db2 | 192.168.237.12 | Replica | streaming | 1 | 0 |
| db3 | 192.168.237.13 | Replica | streaming | 1 | 0 |
+--------+----------------+---------+-----------+----+-----------+
2026-11-26 17:42:26.57240 Successfully switched over to "db2"
+ Cluster: handbook (7712536661967524420) ----+----+-----------+
| Member | Host | Role | State | TL | Lag in MB |
+--------+----------------+---------+---------+----+-----------+
| db1 | 192.168.237.11 | Replica | stopped | | unknown |
| db2 | 192.168.237.12 | Leader | running | | |
| db3 | 192.168.237.13 | Replica | running | | 0 |
Read the two snapshots. The command first printed the topology it was
about to change, then confirmed the switch, then showed the moment in
between: db2 already leader, db1 already stopped - Patroni demotes
and stops the old leader before granting the new one the lease, which
is the single-writer discipline of section 34.5.3 executed in
software. The blank timeline and unknown lag on db1 are what a
stopped member looks like. Moments later the picture completes, on
db1:
$ sudo patronictl -c /etc/patroni/config.yml list
+ Cluster: handbook (7712536661967524420) ------+----+-----------+
| Member | Host | Role | State | TL | Lag in MB |
+--------+----------------+---------+-----------+----+-----------+
| db1 | 192.168.237.11 | Replica | streaming | 2 | 0 |
| db2 | 192.168.237.12 | Leader | running | 2 | |
| db3 | 192.168.237.13 | Replica | streaming | 2 | 0 |
+--------+----------------+---------+-----------+----+-----------+
db1 rejoined as a replica on its own - the automatic pg_rewind path
from section 34.5.4, with no operator in the loop - and db2 leads on
timeline 2, already adopted by both replicas. Let the recorder finish, then reconcile its ledger on
client1:
$ echo "committed=$(wc -l < client-committed-baseline.log) failed=$(wc -l < client-failed-baseline.log)"
committed=27 failed=8
27 of the 30 attempts committed; the failure log carries the error text and names of the rest, which is why its line count is not an attempt count. The critical check is whether every acknowledged transaction actually exists exactly once in the database - count each committed name:
$ while read -r name; do PGPASSWORD=owner-secret psql "host=192.168.236.14 dbname=inventory user=app_owner sslmode=verify-full sslrootcert=/etc/ssl/handbook/ca.crt connect_timeout=3" -Atc "SELECT count(*) FROM app.items WHERE name = '$name';"; done < client-committed-baseline.log | sort | uniq -c
27 1
The loop re-queries each of the 27 committed names through the
proxy; sort | uniq -c summarizes: 27 names, each found exactly once.
Every transaction the server acknowledged survived the switchover -
the application's truth and the database's truth agree. And the
client lands on the new leader, on client1:
$ PGPASSWORD=owner-secret psql "host=192.168.236.14 dbname=inventory user=app_owner sslmode=verify-full sslrootcert=/etc/ssl/handbook/ca.crt connect_timeout=3" -c "SELECT inet_server_addr();"
inet_server_addr
------------------
192.168.237.12
(1 row)
HAProxy's role check found db2 and routed the session there - no client configuration changed anywhere.
The unplanned exercise repeats the shape with real failure: the recorder runs, and this time the leader dies. Start a fresh run in the second window on client1:
$ ~/debian-handbook/databases/client-writes.sh loss
While it runs, stop the leader's agent hard, on db2:
$ sudo systemctl stop patroni
The stop is silent. Confirm it stopped:
$ systemctl is-active patroni
inactive
inactive - the agent, and with it the primary, are gone. The
cluster does the rest: db2's lease expires, db3 acquires the key,
promotes, and HAProxy re-routes. On db1, after the transition:
$ sudo patronictl -c /etc/patroni/config.yml list
+ Cluster: handbook (7712462019495145392) ------+----+-----------+
| Member | Host | Role | State | TL | Lag in MB |
+--------+----------------+---------+-----------+----+-----------+
| db1 | 192.168.237.11 | Replica | streaming | 3 | 0 |
| db2 | 192.168.237.12 | Replica | stopped | | unknown |
| db3 | 192.168.237.13 | Leader | running | 3 | |
+--------+----------------+---------+-----------+----+-----------+
db3 is the new leader on timeline 3; db2 is stopped because its machine was stopped. Confirm from db1's own server that it followed the new timeline and stayed read-only, on db1:
$ sudo -u postgres psql -Atc "select pg_is_in_recovery();"
t
The single t says db1 is in recovery - a replica of the new
leader.
Reconcile the ledger, on client1:
$ echo "committed=$(wc -l < client-committed-loss.log) failed=$(wc -l < client-failed-loss.log)"
committed=27 failed=8
$ while read -r name; do PGPASSWORD=owner-secret psql "host=192.168.236.14 dbname=inventory user=app_owner sslmode=verify-full sslrootcert=/etc/ssl/handbook/ca.crt connect_timeout=3" -Atc "SELECT count(*) FROM app.items WHERE name = '$name';"; done < client-committed-loss.log | sort | uniq -c
27 1
Every acknowledged transaction again survived exactly once. One more query makes the single-writer property explicit - no attempt committed twice anywhere in the table:
$ PGPASSWORD=owner-secret psql "host=192.168.236.14 dbname=inventory user=app_owner sslmode=verify-full sslrootcert=/etc/ssl/handbook/ca.crt connect_timeout=3" -Atc "SELECT 'duplicate_names=' || (count(*) - count(DISTINCT name)) FROM app.items WHERE name LIKE 'client-%';"
duplicate_names=0
duplicate_names=0: every recorded name exists at most once, so at
no point in the failover did two servers both accept the same write
- the property this whole chapter has been driving toward, measured
from the only vantage point that matters, the client's. Bring db2
back, on db2:
$ sudo systemctl start patroni
Silent. Confirm the agent is back, on db2:
$ systemctl is-active patroni
active
The agent now finds the DCS, sees another leader, rewinds or re-copies as needed, and joins as a replica. On db1:
$ sudo patronictl -c /etc/patroni/config.yml list
+ Cluster: handbook (7712462019495145392) ------+----+-----------+
| Member | Host | Role | State | TL | Lag in MB |
+--------+----------------+---------+-----------+----+-----------+
| db1 | 192.168.237.11 | Replica | streaming | 3 | 0 |
| db2 | 192.168.237.12 | Replica | streaming | 3 | 0 |
| db3 | 192.168.237.13 | Leader | running | 3 | |
+--------+----------------+---------+-----------+----+-----------+
Three members again, one leader, two streaming replicas at zero lag.
34.7.2. Etcd Quorum Loss, Network Partitions, Paused Processes, and Unreachable Former Primaries
Automatic failover depends on the consensus store, on the network, and on the agent being alive; the next three tests break each in turn - the paused-agent test first, because it sets up the leadership the other two assume.
Paused processes - the stale primary. The sharpest test pauses the leader's agent while the database keeps running, which is the smallest possible version of "the controller is dead but the writable server is not". Start a recorder run in the second window on client1:
$ ~/debian-handbook/databases/client-writes.sh stale
Then freeze the agent on the current leader - the walkthrough's sequence left db3 leading, so on db3:
$ sudo kill -STOP $(pgrep -x patroni)
The command prints nothing on success. Confirm the state of the frozen agent, on db3:
$ systemctl is-active patroni
active
kill -STOP suspends the Patroni process without killing it, and
systemctl is-active still reports active because the process
exists - systemd cannot see a suspended process. This is precisely
the case the watchdog of section 34.6.7 exists for: the agent cannot
demote PostgreSQL, and nothing else will. The sequence that follows
is fully automatic:
- The leader's lease expires in etcd 40 seconds after its last renewal; a replica acquires the key and promotes.
- HAProxy's
/primarychecks mark the old leader down within theirfall 3window and kill its client sessions (on-marked-down shutdown-sessions), so no new client writes arrive at the stale primary. - The watchdog, unpetted since the pause, reboots the node - the softdog backstop firing exactly as configured.
- After the reboot, systemd starts Patroni, which finds another leader, rewinds or re-copies, and rejoins as a replica.
The node itself reports the middle of that story when it comes back, on db3:
$ uptime -p
up 0 minutes
The machine rebooted - only the watchdog could have done it. Its agent, restarted by systemd at boot:
$ systemctl is-active patroni
active
And its role in the cluster, on db3:
$ sudo patronictl -c /etc/patroni/config.yml list
+ Cluster: handbook (7712448575041428642) ------+----+-----------+
| Member | Host | Role | State | TL | Lag in MB |
+--------+----------------+---------+-----------+----+-----------+
| db1 | 192.168.237.11 | Replica | streaming | 4 | 0 |
| db2 | 192.168.237.12 | Leader | running | 4 | |
| db3 | 192.168.237.13 | Replica | streaming | 4 | 0 |
+--------+----------------+---------+-----------+----+-----------+
db3 - the paused, once-writable, briefly-stale former leader - is
back as a streaming replica on the new timeline, with db2 leading.
The rejoin used the same machinery as section 34.7.1: pg_rewind
against the new leader, automatic, because the rewind_user and
data checksums were arranged at bootstrap. (The numeric cluster ID
in the title line differs from the earlier exercises' listings; it
is the DCS key-space identifier allocated when etcd was first
initialized, carries no configuration, and a lab rebuilt from
scratch gets a new one.)
Finish with the ledger, on client1, once the recorder completes:
$ echo "committed=$(wc -l < client-committed-stale.log) failed=$(wc -l < client-failed-stale.log)"
committed=15 failed=60
$ PGPASSWORD=owner-secret psql "host=192.168.236.14 dbname=inventory user=app_owner sslmode=verify-full sslrootcert=/etc/ssl/handbook/ca.crt connect_timeout=3" -Atc "SELECT 'duplicate_names=' || (count(*) - count(DISTINCT name)) FROM app.items WHERE name LIKE 'client-%';"
duplicate_names=0
duplicate_names=0 - through a leader freeze, a promotion, and a
watchdog reboot, no transaction ever committed twice. The failure
log is long (60 lines of error text and names across 15 failed
attempts) because the outage window covered much of the run's 30
attempts: writes were impossible for tens of seconds, never
duplicated, and every write the server acknowledged exists exactly
once. A fresh client session confirms where writes now land, on
client1:
$ PGPASSWORD=owner-secret psql "host=192.168.236.14 dbname=inventory user=app_owner sslmode=verify-full sslrootcert=/etc/ssl/handbook/ca.crt connect_timeout=3" -c "SELECT inet_server_addr();"
inet_server_addr
------------------
192.168.237.12
(1 row)
The unreachable-former-primary risk from section 34.6.7 was handled by the two components designed for it: the promotion gate waited for the lease, and the proxy's role checks kept clients off the stale node for the whole window.
Quorum loss. With db2 now leading, stop etcd on the two members that do not host the leader's database - db1 and db3 - so the store loses majority while a primary keeps serving:
$ sudo systemctl stop etcd
Run this on db1 and on db3; both stops are silent. Then try to use the store, on db1:
$ sudo ETCDCTL_API=3 etcdctl --endpoints=https://192.168.237.11:2379,https://192.168.237.12:2379,https://192.168.237.13:2379 --cacert=/etc/ssl/handbook/ca.crt --cert=/etc/ssl/handbook/etcd-client.crt --key=/etc/ssl/handbook/etcd-client.key endpoint health --command-timeout=2s 2>&1 | tail -4
https://192.168.237.12:2379 is unhealthy: failed to commit proposal: context deadline exceeded
https://192.168.237.13:2379 is unhealthy: failed to commit proposal: context deadline exceeded
https://192.168.237.11:2379 is unhealthy: failed to commit proposal: context deadline exceeded
Error: unhealthy cluster
Every endpoint reports unhealthy: failed to commit proposal - even
db2's member, which is running: a lone member can answer reads but
cannot commit anything, and Error: unhealthy cluster is etcd
saying quorum is gone. Patroni sees the same thing its own way, on
db1:
$ sudo patronictl -c /etc/patroni/config.yml list 2>&1 | tail -3
File "/usr/lib/python3/dist-packages/patroni/dcs/etcd.py", line 567, in _handle_exception
raise raise_ex
patroni.dcs.etcd3.Etcd3Error: Etcd is not responding properly
The tail -3 keeps the last lines of the failure - the decisive
one being Etcd is not responding properly: no store, no cluster
status, and correctly so, because the store is where status lives.
Now the important question: what does the database do? Write
through the proxy while the quorum is down, on client1:
$ PGPASSWORD=owner-secret psql "host=192.168.236.14 dbname=inventory user=app_owner sslmode=verify-full sslrootcert=/etc/ssl/handbook/ca.crt" -c "INSERT INTO app.items (name, quantity) VALUES ('quorum-loss-write', 1) RETURNING id;"
id
-----
143
(1 row)
INSERT 0 1
The write succeeds - and that is the correct behavior, not a failure of the design. The leader still holds a valid lease (renewed before the quorum went away), PostgreSQL is healthy, and Patroni's rule is conservative: without the store it can neither promote anyone nor demote the incumbent, so it does neither. The cost of quorum loss is failover capability, not service. The leader's lease is on a clock, though: it cannot be renewed without a store to renew it in, and when the 40-second window closes, the leader demotes itself - no one else can promote - so writes stop until the store returns. Bring the two members back, on db1 and db3:
$ sudo systemctl start etcd
Silent on both. Once the members rejoin and catch up, on db1:
$ sudo ETCDCTL_API=3 etcdctl --endpoints=https://192.168.237.11:2379,https://192.168.237.12:2379,https://192.168.237.13:2379 --cacert=/etc/ssl/handbook/ca.crt --cert=/etc/ssl/handbook/etcd-client.crt --key=/etc/ssl/handbook/etcd-client.key endpoint health --write-out=table
+-----------------------------+--------+-------------+-------+
| ENDPOINT | HEALTH | TOOK | ERROR |
+-----------------------------+--------+-------------+-------+
| https://192.168.237.11:2379 | true | 27.017519ms | |
| https://192.168.237.12:2379 | true | 31.506177ms | |
| https://192.168.237.13:2379 | true | 37.613702ms | |
+-----------------------------+--------+-------------+-------+
Quorum restored, all three members healthy. And the cluster's own state, on db1:
$ sudo patronictl -c /etc/patroni/config.yml list
+ Cluster: handbook (7712448575041428642) ------+----+-----------+
| Member | Host | Role | State | TL | Lag in MB |
+--------+----------------+---------+-----------+----+-----------+
| db1 | 192.168.237.11 | Replica | streaming | 5 | 0 |
| db2 | 192.168.237.12 | Leader | running | 5 | |
| db3 | 192.168.237.13 | Replica | streaming | 5 | 0 |
+--------+----------------+---------+-----------+----+-----------+
db2 leads again - but read the timeline closely: it is 5, not the 4 the fencing exercise left. That number records the whole story: the lease expired unrenewed while the store was down, db2 demoted itself when the renewal window closed, and when quorum returned the most-advanced node re-acquired the key and promoted, which is exactly the timeline bump a promotion always makes. No split brain was possible at any point - there was never a quorum to grant a second lease - and the cost of the outage was a bounded write pause plus one promotion cycle, not data divergence.
Network partition. Now isolate one replica from the replication network without stopping anything, on db3 (a replica at this point):
$ sudo iptables -I INPUT -i eth2 -s 192.168.237.0/24 -j DROP && sudo iptables -I OUTPUT -o eth2 -d 192.168.237.0/24 -j DROP
Both rules insert silently. Inbound and outbound traffic on eth2
to the 192.168.237.0/24 network is dropped - db3 can no longer see
the DCS, the leader, or anything else on that network. Moments
later, look at what the isolated node logs, on db3:
$ tail -5 /var/log/patroni/patroni.log | grep -Ei "dcs|etcd|error|following" | tail -3
2026-11-26 12:06:05,444 ERROR: Request to server https://192.168.237.11:2379 failed: MaxRetryError("HTTPSConnectionPool(host='192.168.237.11', port=2379): Max retries exceeded with url: /v3/lease/keepalive (Caused by ConnectTimeoutError(<urllib3.connection.HTTPSConnection object at 0x7f0ba21d3250>, 'Connection to 192.168.237.11 timed out. (connect timeout=3.1666666666666665)'))")
Patroni is logging exactly the right thing - it cannot reach the store, and every DCS request times out and retries. Check what the services on the isolated node decided to be, on db3:
$ systemctl is-active patroni
active
$ sudo -u postgres psql -Atc "SELECT CASE WHEN pg_is_in_recovery() THEN 'replica' ELSE 'primary' END;"
replica
Patroni is active and PostgreSQL is still replica, read-only,
because that is what it was when the partition began, and a cut-off
agent never promotes. The rest of the cluster, meanwhile, saw one
replica vanish: it will not promote anyone (the leader is fine), but
it keeps that replica's slot - WAL accumulates on the leader for
as long as the replica is unreachable, which is the section 34.4.3
retention risk in its live form. Heal the partition, on db3:
$ sudo iptables -D INPUT -i eth2 -s 192.168.237.0/24 -j DROP && sudo iptables -D OUTPUT -o eth2 -d 192.168.237.0/24 -j DROP
Silent. The node's Patroni reaches the store again, its replica resumes streaming from the retained WAL, and the cluster listing on db1 shows the full membership again:
$ sudo patronictl -c /etc/patroni/config.yml list
+ Cluster: handbook (7712448575041428642) ------+----+-----------+
| Member | Host | Role | State | TL | Lag in MB |
+--------+----------------+---------+-----------+----+-----------+
| db1 | 192.168.237.11 | Replica | streaming | 5 | 0 |
| db2 | 192.168.237.12 | Leader | running | 5 | |
| db3 | 192.168.237.13 | Replica | streaming | 5 | 0 |
+--------+----------------+---------+-----------+----+-----------+
The partition cost lag and retained WAL, not ownership - the correct outcome for a partitioned replica. The three failures together map the guarantees: a dead agent with a live database is fenced by the watchdog; a live agent with a dead store freezes leadership instead of inventing it; a live agent with a dead network stays exactly what it was. In every case the invariant is the same one - no component promotes itself without the quorum's permission.
34.7.3. Checking Single-Writer Ownership, Acknowledged Transactions, Ambiguous Commits, and Measured Recovery Time
The three runs together form one report, and each line of it answers
a specific question. Single-writer ownership:
duplicate_names=0 in every run - before, during, and after every
transition, exactly one server accepted writes, verified by
application data rather than by cluster status. Acknowledged
transactions: all 27 committed names in both the switchover and
leader-loss runs were found exactly once - nothing the server
acknowledged was lost to the failover. Ambiguous commits are the
honest edge of asynchronous replication: a transaction acknowledged
by the old primary in its final instant may not yet have reached the
promoted replica, and for that one transaction the client's
"committed" and the new primary's "absent" are both true. The
recorder cannot always distinguish that case from an ordinary
failure, which is why the check is "every acknowledged name
survives" and the bound on the ambiguous window is the cluster's
lag - 1 MB of WAL in this configuration, enforced as a promotion
veto by maximum_lag_on_failover. When the application cannot
tolerate even that window, the dial is synchronous_mode from
section 34.6.6, with the availability price stated there.
Recovery time was measured during the same exercises, from the transcript timestamps of the two runs, on the one-vCPU practice guests:
| Transition | Measured (lab) | Bounded by |
|---|---|---|
| Planned switchover to client-visible writes on the new leader | about 34 s | Patroni's ordered demote/promote plus the proxy's fall 3 at 2 s intervals |
| Leader loss to client-visible writes on the new leader | about 37 s | Lease expiry: up to ttl 40 s, plus one loop_wait 10 s pass and the proxy check |
Both numbers sit inside the arithmetic the configuration predicts -
detection cannot beat the lease, and the switchover is faster than
the loss because it skips the expiry wait. They are one lab's
wall-clock measurements, not service objectives; what transfers to
production is the method (an independent client, a transaction
ledger, timestamps) and the knowledge that the two knobs - ttl and
loop_wait - are where you trade detection speed for store
stability.
34.7.4. Rejoining a Former Primary with pg_rewind or a Fresh Base Backup
Every exercise in this section ended with a former writer rejoining
as a replica, and no operator ran pg_rewind in any of them. The
automation's rejoin path is exactly section 34.5.4's, with the
prerequisites pre-arranged: the rewind user exists
(rewind_user, created by the bootstrap), data checksums are on
(the initdb option), and the new leader's pg_hba.conf admits the
rewind connection (Patroni's template). When a former leader
restarts, its agent asks the DCS who leads, and then:
- If the local data directory is a prefix of the new leader's
history - the clean-shutdown case recorded in section 34.5.4 -
no pages need reverting; the agent writes
standby.signalandprimary_conninfo, and the node streams from the fork point onward. - If the directory diverged - writes happened after the fork -
the agent runs
pg_rewindthrough therewinduser, reverting the divergence, then joins as above. The recorded stale-primary exercise followed this path: the paused leader accepted no writes after the fork, but its shutdown was a reboot, and the rewind machinery handled whatever the interruption left behind. - If rewinding is impossible or pointless - divergence larger
than the data set, or a directory the tool cannot process -
Patroni falls back to its
create_replica_methods: wipe the local directory and take a fresh base backup from the new leader, exactly the manual recovery of last resort, automated.
The choice matters operationally because it sets your expectations
for time and load: a rewind is seconds and copies only changed
pages; a fresh base backup is the size of the database streaming
across the replication network - on a large cluster, the difference
between a blip and an event to schedule. The mechanism to watch is
the same in all three cases: the rejoining node must appear as
streaming in patronictl list with lag falling to zero, and the
node must report t from pg_is_in_recovery() before you trust
it. A node that reappears writable after a failure is not
rejoined - it is a split brain, and the response is to stop it
immediately and investigate what promoted while it was unreachable.
34.7.5. Replacing Database and Etcd Members and Performing Version-Compatible Rolling Maintenance
Components fail permanently sometimes, and maintenance replaces them deliberately; a three-member design expects both.
Replacing a database node is the bootstrap procedure with an
empty machine: install the same packages, copy
/etc/patroni/config.yml with the new node's five identity lines,
install the node's certificates and permissions, unmask nothing
(systemd stays out of it), and start Patroni - the agent clones the
leader with a base backup and joins. The old node's DCS record
should be removed once you are sure it is not coming back, and
Patroni's own maintenance commands are the interface:
patronictl remove <member> retires a member's registration. Order
matters in the other direction too: never remove a member's DCS
record while its agent is still running, or the cluster will spend
its attention reacquiring it.
Replacing an etcd member follows etcd's documented membership
workflow, and the discipline is one at a time: add the new member
with etcdctl member add <name> --peer-urls ..., start etcd on the
new node configured for the existing cluster
(ETCD_INITIAL_CLUSTER_STATE=existing, the full peer list including
the new member), verify endpoint health shows it caught up, and
only then etcdctl member remove <old-id> and decommission the old
node. Between each step the quorum must be intact - two members
running while the third is in transit. The failure that bites
everyone once: adding a fourth member before removing the third
does not help unless the old one is removed promptly, because
quorum grows with membership (three members need two, four need
three); replace strictly one for one, or grow the whole set
deliberately with the quorum math done in advance.
Rolling maintenance is the same procedures done politely, in an order that never drops below quorum or leaves the cluster single-replica longer than necessary:
- Switch the leader away from the node to maintain -
patronictl switchoveras in section 34.7.1 - and wait for the node to showstreaming. - Stop the node's Patroni agent, apply the package updates, and start it again; it rejoins by the rejoin paths of section 34.7.4.
- Repeat per node, leader last or first by your preference, but never maintain two nodes concurrently in a three-member cluster.
- For etcd, restart members one at a time with
endpoint healthverified between restarts.
The version compatibility rule from section 34.3.3 binds every step: PostgreSQL minor updates roll through the cluster node by node (the replication protocol is stable within a major version); PostgreSQL major versions cannot roll - physical replication refuses across majors, so the whole cluster moves together via the rebuild paths (logical copy or backup-into-new-version), never in place. Etcd and Patroni updates roll the same one-at-a-time way etcd restarts do, with Patroni's own compatibility requirement - the DCS client library - already satisfied by the distribution's matching packages.
34.7.6. Backing Up Etcd and Patroni State and Restoring PostgreSQL from Independent Backups
The Patroni cluster's control plane is data too: the leader key, the cluster configuration, the member records all live in etcd, and losing every etcd member's storage means losing the cluster's identity even if all three PostgreSQL data directories survive. Etcd has a first-class backup for exactly this, and it is a single atomic snapshot, safe to take on a live cluster. Save it outside the database hosts' failure domain - the walkthrough's copy lands in john's workspace on db1:
$ sudo install -d -o john -g john ~/debian-handbook/databases/backups
The directory creation is silent. Then take the snapshot, from db1:
$ sudo ETCDCTL_API=3 etcdctl --endpoints=https://192.168.237.11:2379 --cacert=/etc/ssl/handbook/ca.crt --cert=/etc/ssl/handbook/etcd-client.crt --key=/etc/ssl/handbook/etcd-client.key snapshot save /home/john/debian-handbook/databases/backups/etcd-snapshot.db
{"level":"info","ts":"2026-11-26T12:34:22.543526Z","caller":"snapshot/v3_snapshot.go:65","msg":"created temporary db file","path":"/home/john/debian-handbook/databases/backups/etcd-snapshot.db.part"}
{"level":"info","ts":"2026-11-26T12:34:22.558401Z","logger":"client","caller":"v3/maintenance.go:212","msg":"opened snapshot stream; downloading"}
{"level":"info","ts":"2026-11-26T12:34:22.558604Z","caller":"snapshot/v3_snapshot.go:73","msg":"fetching snapshot","endpoint":"https://192.168.237.11:2379"}
{"level":"info","ts":"2026-11-26T12:34:22.567728Z","logger":"client","caller":"v3/maintenance.go:220","msg":"completed snapshot read; closing"}
{"level":"info","ts":"2026-11-26T12:34:22.689546Z","caller":"snapshot/v3_snapshot.go:88","msg":"fetched snapshot","endpoint":"https://192.168.237.11:2379","size":"168 kB","took":"now"}
{"level":"info","ts":"2026-11-26T12:34:22.690058Z","caller":"snapshot/v3_snapshot.go:97","msg":"saved","path":"/home/john/debian-handbook/databases/backups/etcd-snapshot.db"}
Snapshot saved at /home/john/debian-handbook/databases/backups/etcd-snapshot.db
The JSON lines are etcdctl's own progress reporting, streaming as the snapshot downloads, and the plain final line is the confirmation. Note the single endpoint: a snapshot is requested from one member, and requesting it from several at once is the error the command correctly refuses. Verify the artifact before trusting it, still on db1:
$ sudo etcdutl snapshot status /home/john/debian-handbook/databases/backups/etcd-snapshot.db -w table
+----------+----------+------------+------------+
| HASH | REVISION | TOTAL KEYS | TOTAL SIZE |
+----------+----------+------------+------------+
| 1873a4f1 | 390 | 401 | 168 kB |
+----------+----------+------------+------------+
etcdutl (the dedicated utility; etcdctl no longer restores) reads
the snapshot's integrity hash, the revision it captures, the key
count, and the size - 401 keys and 168 kB, which is the Patroni
state, the member records, and the store's own bookkeeping. A
snapshot this cheap belongs in a scheduled job; its restore
mechanics are worth exercising once, into a scratch directory, on
db1:
$ sudo rm -rf /var/lib/etcd/restore-test && sudo etcdutl snapshot restore /home/john/debian-handbook/databases/backups/etcd-snapshot.db --data-dir /var/lib/etcd/restore-test
2026-11-26T12:34:25Z info snapshot/v3_snapshot.go:265 restoring snapshot {"path": "/home/john/debian-handbook/databases/backups/etcd-snapshot.db", "wal-dir": "/var/lib/etcd/restore-test/member/wal", "data-dir": "/var/lib/etcd/restore-test", "snap-dir": "/var/lib/etcd/restore-test/member/snap", "initial-memory-map-size": 10737418240}
2026-11-26T12:34:26Z info membership/store.go:141 Trimming membership information from the backend...
2026-11-26T12:34:26Z info membership/cluster.go:421 added member {"cluster-id": "cdf818194e3a8c32", "local-member-id": "0", "added-peer-id": "8e9e05c52164694d", "added-peer-peer-urls": ["http://localhost:2380"]}
2026-11-26T12:34:26Z info snapshot/v3_snapshot.go:293 restored snapshot {"path": "/home/john/debian-handbook/databases/backups/etcd-snapshot.db", "wal-dir": "/var/lib/etcd/restore-test", "data-dir": "/var/lib/etcd/restore-test", "snap-dir": "/var/lib/etcd/restore-test/member/snap", "initial-memory-map-size": 10737418240}
The log tells you two things that matter for a real recovery: the
snapshot restored into a working etcd directory layout, and
Trimming membership information from the backend - a restored
snapshot deliberately carries the data but not the old cluster's
membership, because a recovery forms a new cluster seeded with the
old contents. Confirm the directory structure exists, then clean up
the scratch copy, on db1:
$ sudo ls /var/lib/etcd/restore-test/member/snap && sudo rm -rf /var/lib/etcd/restore-test
0000000000000001-0000000000000001.snap
db
The ls prints the snapshot and database files etcd would start
from; the rm removes the scratch copy. The exercise proves the
artifact is restorable - an unverified backup being the
Chapter 15 antipattern.
The data side needs its own independent copy, taken the way
section 34.4.2 established, from whichever node currently leads.
The managed cluster does not archive WAL in this walkthrough's
configuration (the standalone cluster of section 34.4 did); give it
the same capability by adding archive_mode, archive_command,
and archive_timeout to the DCS PostgreSQL parameters
(patronictl edit-config, then a rolling restart per section
34.7.5), after which the archive of section 34.4.3 applies
unchanged. The base backup itself does not wait for that, on db1:
$ sudo install -d -o postgres -g postgres /srv/pgarchive/patroni-base && sudo -u postgres env PGPASSWORD=repl-secret pg_basebackup -d "host=192.168.237.12 port=5432 user=replicator sslmode=verify-full sslrootcert=/etc/ssl/handbook/ca.crt" -D /srv/pgarchive/patroni-base -Fp -Xs -P 2>&1 | tail -3
1592/31074 kB (5%), 0/1 tablespace
31085/31085 kB (100%), 0/1 tablespace
31085/31085 kB (100%), 1/1 tablespace
Thirty-one MB copied from the live leader over the replication network with verified TLS. Verify what the copy is, on db1:
$ sudo /usr/lib/postgresql/17/bin/pg_controldata /srv/pgarchive/patroni-base | grep -E "Database cluster state|Latest checkpoint.s TimeLineID"
Database cluster state: in production
Latest checkpoint's TimeLineID: 5
The control data reports in production - the copy was taken from
a running primary, which is what pg_basebackup guarantees it
produces - on timeline 5, the timeline the exercises of this
section created. The backup's own label names its starting WAL
position, on db1:
$ sudo ls -lh /srv/pgarchive/patroni-base/backup_label
-rw------- 1 postgres postgres 225 Nov 26 12:34 /srv/pgarchive/patroni-base/backup_label
Together the two artifacts answer the two questions disaster recovery will ask: etcd's snapshot answers "what did the cluster believe", and this base backup answers "what did the data contain" - independent copies, independently restorable, exactly the separation Chapter 15 insisted on between replication and recovery.
34.7.7. Recovering a Lost Consensus Store Without Resurrecting a Stale Database Leader
The scenario that makes etcd recovery subtle is not the mechanics - they are the restore exercise above - but the timing: the snapshot records who led when it was taken, and the database nodes have kept living since. If the store is lost and every database host survives, the hosts know more than any snapshot does, and the recovery must be sequenced so that the data's truth wins over the record's truth.
The full procedure, for the case where all three etcd members' state is gone but the snapshot of section 34.7.6 exists:
- Stop the Patroni agents everywhere (leave PostgreSQL running or stop it, but leave systemd masked as always). Nothing may act on consensus state while you rebuild the store.
- Inventory the actual database state node by node: on each,
sudo -u postgres psql -Atc "select pg_is_in_recovery();"pluspg_controldata's timeline and LSN. This tells you which node holds the most advanced copy - your candidate primary. - Restore the snapshot into fresh data directories on all three
etcd members with
etcdutl snapshot restore, one--data-dirper member, passing each member's--initial-clusterand--initial-advertise-peer-urlsflags - the restore trims membership, and you supply the new cluster's shape. - Start etcd on all three, verify
endpoint healthandmember listas in section 34.6.4. - Start Patroni on the most-advanced node first, and watch it re-acquire leadership: the restored leader key points at the name that led when the snapshot was taken, but the key carries a TTL, and Patroni verifies the local node against the recorded state before acting on it. Then start the other agents, which rejoin by the rewind/base-backup paths of section 34.7.4.
- Reconcile before serving:
patronictl listshows one leader and streaming replicas;pg_is_in_recovery()isteverywhere except the leader; the duplicate-name check of section 34.7.1 passes against application data.
The stale-leader rule that makes step 5 safe is the same one the watchdog enforces: never let a restored record promote a node whose data you have not verified. If the inventory in step 2 shows a former primary with data past what the snapshot knew - writes it accepted while the store was already gone, inside its last lease - then treat that node's extra data as the truth and rejoin the others to it, snapshot or no snapshot; if instead you cannot trust any node's directory, rebuild the cluster from the independent base backup of section 34.7.6 (and the WAL archive, if the managed cluster has archiving enabled), forming a new Patroni cluster over the restored data. The snapshot restore mechanics were verified above against a scratch directory; the member-by-member rebuild follows etcd's documented recovery path for a lost cluster, and the principle it must preserve is the chapter's whole argument: ownership decisions belong to a live quorum, never to a stale record.