34.6. Walkthrough: Automated PostgreSQL Failover with Patroni and Etcd

Manual promotion works until the failure happens at 03:00. This walkthrough rebuilds the same three database nodes under Patroni, a supervisor that holds the primary's authority as a lease in an etcd quorum and re-derives every decision section 34.5 made by hand: who owns the write role, which replica may promote, how a deposed primary rejoins, and how clients find the current primary without a human touching them. The walkthrough proceeds one layer at a time - design, topology, packages, security, bootstrap, lease semantics, fencing, routing - so each mechanism can be inspected before the next depends on it.

34.6.1. Comparing Manual Promotion, Patroni, and Cluster-Managed Database Ownership

Section 34.5 made every failover decision by hand: you noticed the failure, you confirmed the old primary was dead, you promoted, you rewound, you rejoined, and you re-pointed the client. Each step was also the place an operator error could split the cluster. Automating the same procedure needs someone - or something - that can answer three questions continuously and safely: who is allowed to accept writes right now, how fast can that answer change when a machine dies, and what stops the deposed owner from writing anyway. The Chapter 32 stack answered them with Corosync quorum, Pacemaker resource ordering, and fencing; Patroni answers them with a consensus store and a lease, purpose-built for PostgreSQL.

Criterion Manual promotion (34.5) Patroni over etcd Pacemaker-style (Chapter 32)
Ownership decided by The operator's procedure A leader key with a TTL in etcd; only the lease-holder runs a writable primary Quorate cluster elects a resource owner
Failure detection You notice etcd lease expiry - bounded by ttl Corosync membership timeout
Promotion eligibility Judged by hand Recorded lag and maximum_lag_on_failover Resource stickiness and ordering constraints
Rejoin of old primary pg_rewind by hand Automatic: pg_rewind, else fresh base backup Fencing + resource restart
Fencing of a wedged owner External discipline Watchdog reboot of the node STONITH device
Application routing Reconfigure clients Role-aware proxy against each node's REST API Virtual IP or proxy
Scope One database pair One PostgreSQL cluster Any resource, database-agnostic

What Patroni adds over manual work is not intelligence - every rule it follows is one this chapter has already stated - but continuity: the loop runs every ten seconds forever, without fatigue, and its decisions are visible in a consensus store that two components can watch independently (the other Patroni agents, and the proxy). What it does not do is equally important: it does not back anything up, it does not archive WAL, and it does not make a two-node cluster safe - three is the minimum that survives one failure without manual intervention, because the tiebreaker is the consensus store's quorum.

34.6.2. Planning Three Database Nodes, Three Etcd Members, HAProxy, and Independent Clients

The walkthrough keeps the four practice hosts and adds the software stack to each:

Host PostgreSQL Patroni agent etcd member Other
db1 (192.168.237.11) yes yes yes archive disk /dev/vdb from section 34.4
db2 (192.168.237.12) yes yes yes -
db3 (192.168.237.13) yes yes yes MariaDB source in section 34.8
client1 (192.168.236.14) client only - - HAProxy, the recorder, MariaDB replica

The numbers come from quorum arithmetic, not taste. Three etcd members tolerate one member's failure: two remaining members hold majority, and the store stays writable. Two members tolerate nothing - either member's death leaves the other unable to prove majority, and Patroni then refuses to change leadership (it cannot safely act without the store), which is correct but is not failover. Three Patroni members matter for the database the same way: one primary plus two replicas means a promotion after a failure still leaves a replica to fail over to. The client runs on client1, deliberately outside the database set, because a failover verified from the failed machine proves nothing.

Patroni ownership stack

Figure 34.4. Who may accept writes, decided by the etcd lease. The leader's agent renews a keyed lease every loop; the other agents watch it and contend when it expires. HAProxy asks each node's REST API which role it holds, and the watchdog is the backstop for the agent that cannot demote itself.

One prerequisite is inherited from the clocks: lease expiry, etcd's elections, and the recovery_target_time of section 34.4 all read them, so the practice guests keep the time synchronization Chapter 10 establishes - a cluster with drifting clocks fails over late and restores to the wrong moment.

One design decision is stated plainly because it is the lab's chief compromise: the etcd members are co-located with the database nodes. That keeps the walkthrough inside four guests, but it means the consensus store and the database share failure domains - whatever kills db1 kills one member of each. Production commonly runs etcd on separate small machines (or uses three members spread across the database hosts' independent failure domains); the Patroni configuration below does not change either way, because the agents address etcd over the network by name.

34.6.3. Checking Debian Package Compatibility, Failure Domains, and a Bounded Lab Resource Plan

The stack is four Debian packages plus one library, and their versions must agree at three seams. On the three database nodes:

$ sudo apt install patroni etcd-server etcd-client python3-etcd3

Answer the prompts normally. patroni (4.0.7 in Debian 13) drives PostgreSQL through the versioned binaries; etcd-server and etcd-client (3.5.16) provide the consensus store and its command-line client; python3-etcd3 is the client library Patroni's etcd3 backend speaks. On client1:

$ sudo apt install haproxy socat postgresql-client-17

haproxy (3.0.11) routes clients; socat speaks to HAProxy's statistics socket; postgresql-client-17 matches the servers exactly.

The seams to verify before committing: Patroni and the DCS library must be API-compatible (they are packaged together in Debian, and mixing a third-party Patroni with the packaged python3-etcd3 is the usual breakage); Patroni and PostgreSQL must agree on the binary directory - all members must run the same major version, because they are physical streaming replicas of one another (section 34.3.3); HAProxy and the REST API need only HTTP, and any HAProxy can check any Patroni. The walkthrough pins PostgreSQL 17.12 and Patroni 4.0.7 from the same archive, so the first two seams are the distribution's problem, which is the argument for using the packages as they ship.

The resource plan is bounded on purpose: one vCPU and 1 GB of memory per database guest, 768 MB on the client, the 2 GB archive disk from section 34.4. That is enough to exercise every mechanism in this section - bootstrap, switchover, leader loss, quorum loss, watchdog reboot - and every number the walkthrough prints (lag, recovery time, segment counts) is a measurement from that hardware, useful for sanity and useless for sizing. A production plan starts where the lab stops: separate failure domains for etcd, archive capacity driven by WAL volume (section 34.4.3), and memory sized to the working set (Chapter 28 has the measurement methods).

34.6.4. Securing Etcd Peer and Client Connections, Patroni APIs, and PostgreSQL Replication

Everything in this stack talks over two networks, and every channel is authenticated: etcd peers verify each other, etcd clients present a client certificate, Patroni's REST API serves TLS with its own certificate and requires a password, and the PostgreSQL replication connections use the verify-full discipline of section 34.2.3. All of it hangs off one small private certificate authority, generated once on db1 and distributed.

Save the generator as ~/debian-handbook/databases/gen-certs.sh on db1 and read it before running it:

#!/bin/bash
set -e
cd /etc/ssl/handbook
rm -f ./*.crt ./*.key ./*.csr ./*.ext ./*.srl
openssl req -x509 -newkey rsa:2048 -nodes -days 365 \
  -subj "/CN=Handbook Lab CA" -keyout ca.key -out ca.crt 2>/dev/null
for n in 1 2 3; do
  ip=192.168.237.1${n}; cip=192.168.236.1${n}; host=db${n}
  cat > etcd-db${n}.ext <<EOF
subjectAltName = DNS:${host}, IP:${ip}, IP:127.0.0.1
extendedKeyUsage = serverAuth, clientAuth
keyUsage = digitalSignature, keyEncipherment
EOF
  openssl req -newkey rsa:2048 -nodes -subj "/CN=${host}-etcd" \
    -keyout etcd-db${n}.key -out etcd-db${n}.csr 2>/dev/null
  openssl x509 -req -in etcd-db${n}.csr -CA ca.crt -CAkey ca.key -CAcreateserial \
    -days 365 -extfile etcd-db${n}.ext -out etcd-db${n}.crt 2>/dev/null
  cat > pg-db${n}.ext <<EOF
subjectAltName = DNS:${host}, DNS:localhost, IP:${ip}, IP:${cip}, IP:192.168.236.14, IP:127.0.0.1
extendedKeyUsage = serverAuth
keyUsage = digitalSignature, keyEncipherment
EOF
  openssl req -newkey rsa:2048 -nodes -subj "/CN=${host}" \
    -keyout pg-db${n}.key -out pg-db${n}.csr 2>/dev/null
  openssl x509 -req -in pg-db${n}.csr -CA ca.crt -CAkey ca.key -CAcreateserial \
    -days 365 -extfile pg-db${n}.ext -out pg-db${n}.crt 2>/dev/null
  cat > rest-db${n}.ext <<EOF
subjectAltName = DNS:${host}, IP:${ip}, IP:127.0.0.1
extendedKeyUsage = serverAuth
keyUsage = digitalSignature, keyEncipherment
EOF
  openssl req -newkey rsa:2048 -nodes -subj "/CN=${host}-rest" \
    -keyout rest-db${n}.key -out rest-db${n}.csr 2>/dev/null
  openssl x509 -req -in rest-db${n}.csr -CA ca.crt -CAkey ca.key -CAcreateserial \
    -days 365 -extfile rest-db${n}.ext -out rest-db${n}.crt 2>/dev/null
done
cat > etcd-client.ext <<'EOF'
extendedKeyUsage = clientAuth
keyUsage = digitalSignature, keyEncipherment
EOF
openssl req -newkey rsa:2048 -nodes -subj "/CN=patroni-etcd-client" \
  -keyout etcd-client.key -out etcd-client.csr 2>/dev/null
openssl x509 -req -in etcd-client.csr -CA ca.crt -CAkey ca.key -CAcreateserial \
  -days 365 -extfile etcd-client.ext -out etcd-client.crt 2>/dev/null
cat > mdb-db3.ext <<'EOF'
subjectAltName = DNS:db3, IP:192.168.236.13
extendedKeyUsage = serverAuth
keyUsage = digitalSignature, keyEncipherment
EOF
openssl req -newkey rsa:2048 -nodes -subj "/CN=db3-mariadb" \
  -keyout mdb-db3.key -out mdb-db3.csr 2>/dev/null
openssl x509 -req -in mdb-db3.csr -CA ca.crt -CAkey ca.key -CAcreateserial \
  -days 365 -extfile mdb-db3.ext -out mdb-db3.crt 2>/dev/null
cat > mdb-client1.ext <<'EOF'
subjectAltName = DNS:client1, IP:192.168.236.14
extendedKeyUsage = serverAuth
keyUsage = digitalSignature, keyEncipherment
EOF
openssl req -newkey rsa:2048 -nodes -subj "/CN=client1-mariadb" \
  -keyout mdb-client1.key -out mdb-client1.csr 2>/dev/null
openssl x509 -req -in mdb-client1.csr -CA ca.crt -CAkey ca.key -CAcreateserial \
  -days 365 -extfile mdb-client1.ext -out mdb-client1.crt 2>/dev/null
chmod 644 ./*.crt
chmod 600 ./*.key
tar czf /tmp/handbook-certs.tgz -C /etc/ssl/handbook .
echo "certificates generated"

Three certificate families, one per channel, per node: etcd-db* carries both serverAuth and clientAuth (each etcd member is a server to its peers and a peer to its servers) with the node's replication-network name and address; pg-db* is the PostgreSQL server identity on both networks plus the HAProxy address; rest-db* is the Patroni API identity. One shared client-only certificate (etcd-client) is what Patroni presents to etcd on every node. The two mdb-* pairs are the MariaDB TLS certificates section 34.8 uses - generated now so the whole lab shares one CA. The script ends by bundling everything into /tmp/handbook-certs.tgz, a transient archive for immediate copying, not a workspace.

Create the directory and run it, on db1:

$ sudo install -d /etc/ssl/handbook

The directory creation is silent. Then run the generator:

$ sudo bash ~/debian-handbook/databases/gen-certs.sh
certificates generated

Copy /tmp/handbook-certs.tgz to db2, db3, and client1 (with scp, or any transfer you use), and on each of those hosts extract it:

$ sudo install -d /etc/ssl/handbook && sudo tar xzf handbook-certs.tgz -C /etc/ssl/handbook

The extraction is silent. Then set ownership per role - on each database node, with the node's own number in the file names (db1 shown):

$ sudo chown postgres:postgres /etc/ssl/handbook/pg-db1.key /etc/ssl/handbook/pg-db1.crt /etc/ssl/handbook/rest-db1.key /etc/ssl/handbook/rest-db1.crt /etc/ssl/handbook/etcd-client.key /etc/ssl/handbook/etcd-client.crt /etc/ssl/handbook/ca.crt

PostgreSQL and Patroni run as postgres on Debian, so they take ownership of their keys, the REST API certificate, the shared etcd client pair, and the CA. Silent on success. Then lock the private keys to that owner:

$ sudo chmod 600 /etc/ssl/handbook/pg-db1.key /etc/ssl/handbook/rest-db1.key /etc/ssl/handbook/etcd-client.key
$ sudo chmod 644 /etc/ssl/handbook/pg-db1.crt /etc/ssl/handbook/rest-db1.crt /etc/ssl/handbook/etcd-client.crt /etc/ssl/handbook/ca.crt

Keys become mode 600, certificates 644. The etcd peer identity is the one exception - etcd runs as its own user, so its key goes to the etcd group, still unreadable to others:

$ sudo chown root:etcd /etc/ssl/handbook/etcd-db1.key && sudo chmod 640 /etc/ssl/handbook/etcd-db1.key
$ sudo chmod 644 /etc/ssl/handbook/etcd-db1.crt

All five commands are silent on success, and every service can read exactly the identities it serves and nothing else. On client1, no permission changes are needed yet (the CA becomes the client's trust anchor, and section 34.8 installs the MariaDB files).

Etcd next. Its Debian service reads /etc/default/etcd, and the cluster is declared identically on every member except for each member's own name and address. On db1:

DAEMON_ARGS=""
ETCD_NAME=db1
ETCD_DATA_DIR=/var/lib/etcd/default
ETCD_LISTEN_CLIENT_URLS=https://192.168.237.11:2379,https://127.0.0.1:2379
ETCD_ADVERTISE_CLIENT_URLS=https://192.168.237.11:2379
ETCD_LISTEN_PEER_URLS=https://192.168.237.11:2380
ETCD_INITIAL_ADVERTISE_PEER_URLS=https://192.168.237.11:2380
ETCD_INITIAL_CLUSTER=db1=https://192.168.237.11:2380,db2=https://192.168.237.12:2380,db3=https://192.168.237.13:2380
ETCD_INITIAL_CLUSTER_STATE=new
ETCD_INITIAL_CLUSTER_TOKEN=handbook-ch34
ETCD_CERT_FILE=/etc/ssl/handbook/etcd-db1.crt
ETCD_KEY_FILE=/etc/ssl/handbook/etcd-db1.key
ETCD_PEER_CERT_FILE=/etc/ssl/handbook/etcd-db1.crt
ETCD_PEER_KEY_FILE=/etc/ssl/handbook/etcd-db1.key
ETCD_TRUSTED_CA_FILE=/etc/ssl/handbook/ca.crt
ETCD_PEER_TRUSTED_CA_FILE=/etc/ssl/handbook/ca.crt
ETCD_CLIENT_CERT_AUTH=true
ETCD_PEER_CLIENT_CERT_AUTH=true
# Lab-only concession: the shared hypervisor's disk stalls made fsync
# destabilize quorum. This weakens the store's durability guarantee
# and must not be used in production.
ETCD_UNSAFE_NO_FSYNC=true
ETCD_HEARTBEAT_INTERVAL=500
ETCD_ELECTION_TIMEOUT=5000

On db2 and db3 the same file carries their own names and addresses in ETCD_NAME, the four URLS lines, and the etcd-db2/etcd-db3 certificate names; the ETCD_INITIAL_CLUSTER line is shared verbatim, and the token is what keeps separate etcd clusters on the same network from ever merging. ETCD_CLIENT_CERT_AUTH=true is the important line: no connection without a client certificate the CA signed, so the store is not reachable by anything that did not receive etcd-client.*. The two timing lines widen etcd's failure-detection window for the lab's virtual network; defaults are finer and belong in production. Prepare the data directory and start the members, on each of db1, db2, db3:

$ sudo install -d -o etcd -g etcd -m 700 /var/lib/etcd/default

The directory creation is silent. Start the member:

$ sudo systemctl start etcd

Also silent on success. Bring the three up in quick succession - a new cluster boot goes smoothest when the first member does not spend long waiting for peers. Then check health and membership from 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 | 20.947534ms |       |
| https://192.168.237.13:2379 |   true |  28.98517ms |       |
| https://192.168.237.12:2379 |   true | 28.596714ms |       |
+-----------------------------+--------+-------------+-------+

One health line per endpoint, every member true - all three answer over TLS to the client certificate, with the probe's round-trip time in the TOOK column. The membership view of the same cluster:

$ 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 member list -w table
+------------------+---------+------+-----------------------------+-----------------------------+------------+
|        ID        | STATUS  | NAME |         PEER ADDRS          |        CLIENT ADDRS         | IS LEARNER |
+------------------+---------+------+-----------------------------+-----------------------------+------------+
| 4d8fcbd10b35ad08 | started |  db3 | https://192.168.237.13:2380 | https://192.168.237.13:2379 |      false |
| 730f3e88dde8d563 | started |  db2 | https://192.168.237.12:2380 | https://192.168.237.12:2379 |      false |
| 970d29a81583e584 | started |  db1 | https://192.168.237.11:2380 | https://192.168.237.11:2379 |      false |
+------------------+---------+------+-----------------------------+-----------------------------+------------+

Three members, all started, each with its peer and client address - the consensus store is whole. ETCDCTL_API=3 selects the API version etcd 3.5 serves; the environment variable prefix is the documented way to pin it.

34.6.5. Bootstrapping Patroni and Preventing Competing PostgreSQL Service Managers

Patroni does not merely start PostgreSQL - it owns it: it decides when the process runs, what configuration it has, whether it is primary or standby, and it rewrites postgresql.auto.conf and pg_hba.conf as roles change. Two owners is the classic failure: an unattended-upgrade restarts the cluster under systemd, Patroni sees a process it did not start or a demotion it did not order, and the cluster spends its evening thrashing between two managers. The walkthrough therefore removes systemd from the database's control path on all three nodes. Stop, disable, and mask the unit:

$ sudo systemctl stop postgresql

The stop is silent. Then:

$ sudo systemctl disable postgresql

disable prints a short notice about the unit's symlink being removed; it stops the cluster from starting at boot. Then mask it:

$ sudo systemctl mask postgresql

mask prints the symlink it creates, pointing the unit at /dev/null. A masked unit cannot be started by anything - not systemctl start, not a dependency's pull-in, not an upgrade script. Patroni's own unit (patroni.service, running as postgres) starts and stops PostgreSQL directly through the versioned binaries, so nothing else in the system will race it.

The bootstrap needs an empty data directory on the first node. The next command destroys the clusters built in sections 34.2 through 34.5 - deliberately: the manual cluster is being replaced by the managed one. The dumps in ~/debian-handbook/databases and the archive disk are untouched, and the manual cluster's lessons have already been recorded. On all three nodes:

$ sudo rm -rf /var/lib/postgresql/17/main && sudo install -d -o postgres -g postgres -m 700 /var/lib/postgresql/17/main

Silent on success. db1 will be initialized fresh by Patroni's bootstrap; db2 and db3 will receive copies of it.

Now the Patroni configuration itself. Debian's package ships a commented example at /usr/share/doc/patroni/examples/postgres0.yml.gz; the walkthrough's configuration is that shape with the security of 34.6.4 applied. Save it as /etc/patroni/config.yml on db1 (create /etc/patroni first; the file is root-owned and world-readable, which is correct - it contains no key material, only references to it):

scope: handbook
namespace: /db/
name: db1
log:
  level: INFO
  dir: /var/log/patroni
restapi:
  listen: 192.168.237.11:8008
  connect_address: 192.168.237.11:8008
  authentication:
    username: patroni
    password: patroni-secret
  certfile: /etc/ssl/handbook/rest-db1.crt
  keyfile: /etc/ssl/handbook/rest-db1.key
ctl:
  cacert: /etc/ssl/handbook/ca.crt
  authentication:
    username: patroni
    password: patroni-secret
etcd3:
  hosts:
    - 192.168.237.11:2379
    - 192.168.237.12:2379
    - 192.168.237.13:2379
  protocol: https
  cacert: /etc/ssl/handbook/ca.crt
  cert: /etc/ssl/handbook/etcd-client.crt
  key: /etc/ssl/handbook/etcd-client.key
watchdog:
  mode: automatic
  device: /dev/watchdog
  safety_margin: 5
bootstrap:
  dcs:
    ttl: 40
    loop_wait: 10
    retry_timeout: 20
    maximum_lag_on_failover: 1048576
    synchronous_mode: false
    postgresql:
      use_pg_rewind: true
      use_slots: true
      parameters:
        wal_level: replica
        max_wal_senders: 10
        max_replication_slots: 10
        wal_keep_size: 256MB
        hot_standby: 'on'
      pg_hba:
        - local all postgres peer
        - local all all peer
        - host all all 127.0.0.1/32 scram-sha-256
        - host all all ::1/128 scram-sha-256
        - hostssl all all 192.168.236.0/24 scram-sha-256
        - hostssl all all 192.168.237.0/24 scram-sha-256
        - hostssl replication replicator 192.168.237.0/24 scram-sha-256
        - hostssl replication replicator 192.168.236.0/24 scram-sha-256
  initdb:
    - encoding: UTF8
    - data-checksums
  post_init: /usr/local/bin/patroni-post-init.sh
postgresql:
  listen: 0.0.0.0:5432
  connect_address: 192.168.237.11:5432
  data_dir: /var/lib/postgresql/17/main
  bin_dir: /usr/lib/postgresql/17/bin
  pgpass: /var/lib/postgresql/.pgpass
  authentication:
    replication:
      username: replicator
      password: repl-secret
      sslmode: verify-full
      sslrootcert: /etc/ssl/handbook/ca.crt
    superuser:
      username: postgres
      password: postgres-secret
    rewind:
      username: rewind_user
      password: rewind-secret
  parameters:
    unix_socket_directories: /var/run/postgresql
    ssl: 'on'
    ssl_cert_file: /etc/ssl/handbook/pg-db1.crt
    ssl_key_file: /etc/ssl/handbook/pg-db1.key
    ssl_ca_file: /etc/ssl/handbook/ca.crt
  create_replica_methods:
    - basebackup
  basebackup:
    - checkpoint: fast

On db2 and db3 the file differs only in the per-node values: name (db2 or db3), both restapi addresses, connect_address under postgresql, and the pg-db2/pg-db3 certificate names. Everything else - scope, namespace, the etcd list, the whole bootstrap block - is shared verbatim, and that is the design: the cluster's policy lives in one block, the node's identity in five lines.

Read the blocks against what they control. scope and namespace name this cluster in the DCS (/db/handbook/...), so multiple Patroni clusters can share one etcd. restapi is each agent's control surface, TLS-terminated with its own certificate and password-protected. ctl is the client side used by patronictl. etcd3 is the DCS with the shared client certificate. watchdog arms the node-local backstop that section 34.6.7 explains. Under bootstrap, the dcs block is written to etcd once, by whichever node bootstraps the cluster, and afterwards it is the cluster's living configuration: ttl is the lease lifetime in seconds, loop_wait the agent loop period, retry_timeout how long a DCS operation may take, maximum_lag_on_failover (here 1 MB) the lag a replica may have and still be allowed to promote, and synchronous_mode: false the commit policy - asynchronous for availability, exactly as section 34.5.2 discussed. The pg_hba list is what Patroni writes into every member's pg_hba.conf: peer for local administration, scram over TLS for both practice networks, and the replication entry admitting only the replicator role. initdb runs on the bootstrapping node only - note data-checksums, which makes physical corruption detectable and also satisfies one of pg_rewind's prerequisites. post_init is a script run once, against the fresh primary, to create the application's roles; save it on db1 as /usr/local/bin/patroni-post-init.sh, root-owned and executable:

#!/usr/bin/env bash
set -euo pipefail
psql -v ON_ERROR_STOP=1 <<'SQL'
CREATE ROLE app_owner LOGIN PASSWORD 'owner-secret';
CREATE ROLE app_reader LOGIN PASSWORD 'reader-secret';
CREATE ROLE rewind_user LOGIN SUPERUSER PASSWORD 'rewind-secret';
CREATE DATABASE inventory OWNER app_owner;
SQL
psql -v ON_ERROR_STOP=1 -d inventory <<'SQL'
CREATE SCHEMA app AUTHORIZATION app_owner;
SET ROLE app_owner;
CREATE TABLE app.items (
    id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    name text NOT NULL,
    quantity integer NOT NULL CHECK (quantity >= 0)
);
INSERT INTO app.items (name, quantity) VALUES ('bolts', 120), ('nuts', 80);
GRANT USAGE ON SCHEMA app TO app_reader;
GRANT SELECT ON ALL TABLES IN SCHEMA app TO app_reader;
SQL

It is the section 34.2.2 procedure with one addition: rewind_user, a dedicated superuser for pg_rewind so the automatic rejoin never depends on the postgres role's password. (A role limited to the rewind-related privileges is the least-privilege refinement; a separate dedicated account is the part that matters, and never sharing it with applications.)

Finally the node-local plumbing: Patroni logs to a directory it owns, and the watchdog drop-in that section 34.6.7 explains must exist before the service first runs. On each database node:

$ sudo install -d -o postgres -g postgres -m 750 /var/log/patroni
$ sudo install -d -m 755 /etc/systemd/system/patroni.service.d

Two directory creations, both silent: the log directory Patroni will write to as postgres, and the systemd drop-in directory. Then the drop-in, /etc/systemd/system/patroni.service.d/watchdog.conf on each node:

[Service]
ExecStartPre=+/sbin/modprobe softdog
ExecStartPre=+/bin/chown postgres /dev/watchdog

And load the module at boot, on each node:

$ echo softdog | sudo tee /etc/modules-load.d/softdog.conf
softdog

tee echoes the line back. The + prefixes on ExecStartPre mark privileged steps - loading the software watchdog module and handing the device to postgres - after which Patroni can open it. Section 34.6.7 covers what it does.

Bootstrap time. Start Patroni on db1 only:

$ sudo systemctl start patroni

The start is silent. Patroni sees an empty DCS and an empty data directory, initializes a fresh cluster (initdb with data checksums), runs the post-init script, writes the cluster configuration to etcd, takes the leader lease, and brings PostgreSQL up as primary. Give it a few seconds and ask for the state, 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 | Leader | running |  1 |           |
+--------+----------------+--------+---------+----+-----------+

The cluster exists: one member, db1, leader, timeline 1, running. The long number in the title line is the cluster's DCS key-space identifier, allocated when the scope was first bootstrapped; it carries no configuration, and a lab rebuilt from scratch gets a different one. Now add the other two nodes - on db2, then db3:

$ sudo systemctl start patroni

Each joining node finds the DCS record, sees it has no local data, and clones the leader with pg_basebackup (the create_replica_methods: basebackup setting) before starting its standby. The start may take a minute while the copy streams. Once both have joined, the list shows the full cluster, 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 | Leader  | running   |  1 |           |
| db2    | 192.168.237.12 | Replica | streaming |    |         0 |
| db3    | 192.168.237.13 | Replica | streaming |  1 |         0 |
+--------+----------------+---------+-----------+----+-----------+

One leader, two streaming replicas, lag zero; db2's timeline column is still blank only because it joined moments before the listing, and the display fills it in on its next refresh. The database's own view agrees - on db1, as the postgres superuser:

$ sudo -u postgres psql -c "SELECT client_addr, state, sync_state FROM pg_stat_replication;"
  client_addr   |   state   | sync_state 
----------------+-----------+------------
 192.168.237.13 | streaming | async
 192.168.237.12 | streaming | async
(2 rows)

Two WAL senders, both asynchronous. Two things are already different from the manual cluster of section 34.5, and both are Patroni working for you: each replica holds a replication slot (use_slots: true), so the primary retains exactly the WAL each replica needs - no more guessing wal_keep_size - and each replica's primary_conninfo and pg_hba.conf were written and verified by the agent that owns them.

34.6.6. Leader Leases, Quorum, Promotion Eligibility, Replication Lag, and Synchronous Commit Tradeoffs

The lease is the whole trick, so it deserves a precise description. The cluster's state lives in etcd under one key - the leader key - and that key is created with a TTL of 40 seconds. The leader's agent renews the lease every loop_wait (10 seconds); as long as it succeeds, every other agent sees a valid lease and stays a replica. When the leader's machine dies, renewal stops, etcd expires the key 40 seconds after the last renewal, and the first replica to successfully acquire the key becomes the new leader - with the cluster-level configuration (maximum_lag_on_failover, the PostgreSQL parameters, the pg_hba template) available to it because it lives in the same store. Quorum is the safety on the whole mechanism: etcd itself needs 2 of 3 members, and no Patroni agent acts without the store - a node that cannot see etcd cannot promote itself, which is exactly the property that prevents two primaries on a network partition.

The REST API is the window into that state, and it is what lets a proxy share the same truth. On client1, as john, ask the leader what it is:

$ curl -sS --cacert /etc/ssl/handbook/ca.crt --user patroni:patroni-secret https://192.168.237.11:8008/primary -o /dev/null -w "%{http_code}\n"
200

/primary answers 200 on the node holding the lease and 503 on every other node - the one-bit answer HAProxy will consume in section 34.6.8. The API verifies its TLS identity against the same CA, and the password is required. Prove both, still from client1 - first with no credentials at all:

$ curl -sS --cacert /etc/ssl/handbook/ca.crt -X PATCH -H "Content-Type: application/json" -d "{}" https://192.168.237.11:8008/config -o /dev/null -w "%{http_code}\n"
401

401 Unauthorized. Then with the wrong password:

$ curl -sS --cacert /etc/ssl/handbook/ca.crt --user patroni:wrong -X PATCH -H "Content-Type: application/json" -d "{}" https://192.168.237.11:8008/config -o /dev/null -w "%{http_code}\n"
401

Also 401 - the password gate works. Then with the right one:

$ curl -sS --cacert /etc/ssl/handbook/ca.crt --user patroni:patroni-secret -X PATCH -H "Content-Type: application/json" -d "{}" https://192.168.237.11:8008/config -o /dev/null -w "%{http_code}\n"
400

400 Bad Request - the request was authenticated, and what it asked for (a configuration patch containing nothing) is invalid. The three responses together are the API's security story: unauthenticated and mistaken credentials never reach the handler; authenticated ones do. The -o /dev/null -w "%{http_code}\n" pair discards the body and prints only the status, the useful form for scripted checks.

Promotion eligibility is where lag becomes policy. When the lease expires, Patroni does not promote the first replica to grab the key: a replica whose recorded lag exceeds maximum_lag_on_failover - 1 MB of WAL in this configuration - is passed over, because promoting it would silently discard everything between its position and the primary's last write. A replica farther behind is a candidate only if no other is available, and the cluster's lag column in patronictl list is the same number a human reads. retry_timeout bounds how long any single DCS interaction may take before the agent treats the store as unreachable - with the consequence that an agent cut off from etcd demotes itself once it can no longer renew its own lease, rather than assuming the network is everyone else's problem.

The synchronous-commit tradeoff arrives here as one boolean: synchronous_mode. This cluster keeps it false, inheriting the section 34.5.2 analysis - asynchronous commit acknowledges after the primary's local flush, an unreachable primary means the loss window is exactly the lag, and writes never stall on a replica's absence. Turning it on in the DCS configuration (patronictl edit-config, then synchronous_mode: true) makes Patroni maintain synchronous_standby_names itself, naming replicas healthy enough to be sync candidates, with synchronous_mode_strict refusing to promote without one when the cluster would rather be down than silently asynchronous. The rule of thumb is the one the RPO table in section 34.1.3 set up: sync mode when losing one acknowledged transaction is worse than being unavailable; async mode when a sub-second lag window is an acceptable price for never stalling. The walkthrough's tests in section 34.7 run against the asynchronous configuration, and their transaction ledger is read with that in mind.

34.6.7. Lease Expiry, Watchdogs, Fencing, and Stale-Primary Isolation

Between lease expiry and the new leader's first write lies the most dangerous interval in automatic failover: the old primary's PostgreSQL is still open, its agent cannot reach the store, and if the machine's problem was only the network - or only the agent - the old primary may still accept writes that the new primary will never see. Patroni's defense is layered, and each layer covers what the previous one cannot:

  1. The agent demotes. A running Patroni that cannot renew its lease does not wait to be told: it demotes PostgreSQL (recovery.signal, read-only) before another member can take the key, retrying the renewal as it goes. This covers network partitions and store outages - the common case.
  2. The watchdog reboots the node. If the agent is dead or wedged - a kernel hang, a stopped process, a bug holding the loop - no software instruction can demote PostgreSQL. So Patroni arms a watchdog device while it holds leadership: the kernel expects a keepalive petting /dev/watchdog every few seconds and reboots the machine if the pets stop. PostgreSQL stops with the whole node, which is fencing by the only authority a dead process still answers to.
  3. The promotion gate. Even while a stale primary lingers, no replica promotes until the lease has actually expired in etcd - so the overlapping-writers window is bounded by ttl, not by operator reaction time.

The walkthrough's configuration uses the softdog kernel module - a software watchdog, armed by the drop-in and module load from section 34.6.5 (watchdog: mode: automatic, device: /dev/watchdog, safety_margin: 5). Software watchdogs cover a hung or dead process faithfully: the kernel keeps petting nothing, and the reboot happens roughly ttl + safety_margin seconds after the last successful renewal. What they cannot cover is a hung kernel - the module itself stops running. That is the boundary where production needs a hardware watchdog (petted by the kernel against real firmware counters) or an out-of-band fencing device - the Chapter 32 discussion applies unchanged, and the honest statement is the same one that chapter made: unfenced automated failover trades availability for a small, real probability of two writers; the watchdog is what buys that probability down.

The lease arithmetic also explains the tuning knobs: ttl sets both the worst-case failover detection (just under 40 seconds here, plus one loop_wait for a watching replica to notice) and the maximum time a cut-off but healthy leader keeps accepting writes before its own agent demotes it. Lower ttl fails over faster and demands more from the store; higher ttl tolerates store hiccups and slows everything down. The lab's 40/10/20 values are deliberately boring middle ground.

34.6.8. Routing Clients with Role-Aware HAProxy Checks and Bounded Reconnection

Clients must find the primary without knowing its name. The walkthrough's answer is HAProxy on client1, configured to check each node's Patroni REST API - the same /primary endpoint section 34.6.6 probed - and forward writes to whichever node answers 200. Save on client1 as /etc/haproxy/haproxy.cfg:

global
    log stdout format raw local0
    stats socket /run/haproxy/admin.sock mode 660 level admin
    maxconn 200

defaults
    mode tcp
    log global
    option tcplog
    timeout connect 2s
    timeout client 5s
    timeout server 5s
    retries 2

frontend postgres
    bind 192.168.236.14:5432
    default_backend postgres_primary

backend postgres_primary
    option httpchk GET /primary
    http-check expect status 200
    default-server inter 2s fall 3 rise 2 on-marked-down shutdown-sessions
    server db1 192.168.237.11:5432 check port 8008 check-ssl verify required ca-file /etc/ssl/handbook/ca.crt
    server db2 192.168.237.12:5432 check port 8008 check-ssl verify required ca-file /etc/ssl/handbook/ca.crt
    server db3 192.168.237.13:5432 check port 8008 check-ssl verify required ca-file /etc/ssl/handbook/ca.crt

listen stats
    mode http
    bind 127.0.0.1:8404
    stats enable
    stats uri /stats
    stats refresh 5s

Every line of the backend earns its place. The three server lines name the PostgreSQL addresses, but check port 8008 check-ssl verify required ca-file ... moves the health check to each node's Patroni API, TLS-verified against the lab CA - HAProxy is not asking "is something listening on 5432" (a replica would answer that too) but "does this node claim to be primary and can it prove its identity". option httpchk GET /primary with http-check expect status 200 turns the answer into up/down. default-server inter 2s fall 3 rise 2 makes the verdict deliberate: three consecutive failures (about 6 seconds) to mark a node down, two successes to trust it again - fast enough for the lease arithmetic, slow enough not to flap on a hiccup. And on-marked-down shutdown-sessions is the subtle one that matters most: when the primary's check fails, HAProxy kills the client sessions pinned to it instead of letting them hang until their own timeouts fire, which pushes clients into reconnecting promptly against the new primary that the same check has just discovered.

Validate and start, on client1:

$ sudo haproxy -c -f /etc/haproxy/haproxy.cfg

The check prints nothing when the configuration is valid, and prints the problem with a line number when it is not. Then restart:

$ sudo systemctl restart haproxy

Silent on success. Confirm the service state:

$ systemctl is-active haproxy
active

Now the client's eye view - connect through the proxy address and ask which database served you, on client1, as john:

$ 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.11
(1 row)

inet_server_addr() reports the server's own address for the session - 192.168.237.11, db1 - reached through HAProxy's 192.168.236.14. The client connected to a stable address, verified the server's certificate (the proxy passes TCP through, so end-to-end TLS still holds), and landed on the current primary without ever being told its name. The PostgreSQL side accepted it because the pg_hba template Patroni wrote admits hostssl all all 192.168.236.0/24 scram-sha-256.

The connect_timeout=3 in the client's connection string is the last piece of the reconnection story - bounded reconnection, on the client's side, matching HAProxy's bounded verdicts on its own. A client that hangs for minutes on a dead address has not failed over no matter what the proxy does; one that fails fast and retries lands on the new primary seconds after it appears. Applications with their own pools set the same bound in the pool's connection acquisition; the principle is identical everywhere in the path: no participant waits unboundedly.

HAProxy's statistics socket shows the machinery at work - on client1:

$ echo "show stat" | sudo socat /run/haproxy/admin.sock stdio | grep -E "postgres_primary,(db|BACKEND)" | cut -d, -f1-18
postgres_primary,db1,0,0,0,1,,1,2529,3302,,0,,0,1,0,0,UP
postgres_primary,db2,0,0,0,0,,0,0,0,,0,,0,0,0,0,DOWN
postgres_primary,db3,0,0,0,0,,0,0,0,,0,,0,0,0,0,DOWN
postgres_primary,BACKEND,0,0,0,1,20,1,2529,3302,0,0,,0,1,0,0,UP

The pipeline sends the show stat command into HAProxy's admin socket, filters the backend's rows, and trims to the first eighteen CSV fields. The last field of each server row is the verdict: db1 UP, db2 and db3 DOWN - exactly right, because the check is not "is PostgreSQL alive" but "does this node answer 200 on /primary", and the replicas correctly answer 503 and are correctly excluded. The BACKEND row is up with one server. The web statistics page (listen stats on 127.0.0.1:8404) presents the same data for humans; the socket is for scripts and for the checks Chapter 28 would wire into monitoring.