PostgreSQL’s built-in streaming replication keeps standby servers up to date, but it doesn’t decide when a standby should take over, and it doesn’t stop two servers from both thinking they’re the primary. Patroni adds exactly that. It runs next to PostgreSQL on every node, manages it, and uses a distributed consensus store, etcd, to agree on which node is the leader. When the primary fails, Patroni promotes the best replica within about 30 seconds, and it makes sure the old primary can never accept writes again.
This guide builds a three-node cluster, pg-01, pg-02 and pg-03, on Debian 13, using Debian’s own packages and integration. It covers:
- etcd as a three-member cluster with mutual TLS for peers and clients
- PostgreSQL 17 managed by Patroni 4, using Debian’s
pg_createconfig_patroniandpatroni@units - Synchronous replication: a committed transaction survives the loss of the primary
- Fencing with a watchdog: a hung primary reboots itself before a new leader is chosen
- Secrets outside the config file, TLS for client connections and the REST API, and SCRAM authentication
- A VIP that follows the leader (vip-manager), and a redundant HAProxy pair with keepalived for read/write routing, plus why keepalived doesn’t belong on the database nodes
- Tests for switchover, failover and losing etcd, monitoring, backups and day-2 operations
Tested on: Debian 13 “trixie” with PostgreSQL 17, Patroni 4.0, etcd 3.5 and HAProxy 3.0, all from the Debian archive. All commands run as root. Commands marked (all nodes) run on pg-01, pg-02 and pg-03.
Table of contents
- Placeholders
- Architecture
- Prerequisites
- Firewall
- Certificates
- Install the packages
- The etcd cluster
- Patroni configuration
- The watchdog
- Start the cluster
- Client access: VIP, HAProxy and keepalived
- Testing
- Monitoring
- Backups
- Day-2 operations
- Troubleshooting
- Checklist
1. Placeholders
| Placeholder | Meaning |
|---|---|
pg-01.example.org / 10.20.0.41 | Node 1 |
pg-02.example.org / 10.20.0.42 | Node 2 |
pg-03.example.org / 10.20.0.43 | Node 3 |
10.20.10.0/24 | Application servers / HAProxy hosts |
17-main | Debian’s cluster name: PostgreSQL version 17, cluster main |
2. Architecture
Each of the three nodes runs three services:
| Component | Role | Port |
|---|---|---|
| etcd | Consensus store. Holds the leader key, which only one node can own at a time. Three members tolerate the loss of one. | 2379 (clients), 2380 (peers) |
| Patroni | Manages the local PostgreSQL: starts it, configures replication, renews the leader key, promotes or demotes. Exposes a REST API with health endpoints. | 8008 |
| PostgreSQL 17 | The database. One primary, two streaming replicas. | 5432 |
How a failover works:
- The primary’s Patroni renews its leader key in etcd every 10 seconds. The key expires after 30 seconds (
ttl). - If the primary dies, or loses contact with etcd, the key expires. A primary that can’t renew the key demotes itself to read-only, and the watchdog reboots it if Patroni itself hangs.
- The remaining Patronis race to take the key. Only a replica that is synchronous (or within
maximum_lag_on_failover) may win. - The winner promotes its PostgreSQL. The others follow it. The old primary rejoins as a replica when it comes back, using
pg_rewindif needed.
Why etcd on the database nodes? Three nodes running both etcd and PostgreSQL is a common, well-supported layout. For large or critical installations, a separate three-node etcd cluster isolates the consensus store from database load. The configuration is the same, apart from the addresses.
3. Prerequisites
(all nodes)
- Three separate failure domains (hypervisor hosts at least)
- Low, stable latency between the nodes. etcd and synchronous replication are both latency-sensitive.
- Fast disks for etcd. etcd calls
fsyncon every write, so slow storage causes leader elections. SSD or NVMe is a must. - Resolvable names: every node resolves
pg-01..03.example.org - Synchronised time (chrony)
4. Firewall
(all nodes) Create /etc/nftables.d/patroni.nft:
destroy table inet patroni
table inet patroni {
set nodes_v4 {
type ipv4_addr
elements = { 10.20.0.41, 10.20.0.42, 10.20.0.43 }
}
set clients_v4 {
type ipv4_addr
flags interval
elements = { 10.20.10.0/24 }
}
chain input {
type filter hook input priority filter - 10; policy accept;
iif "lo" accept
# etcd peers and clients: cluster nodes only
tcp dport { 2379, 2380 } ip saddr @nodes_v4 accept
tcp dport { 2379, 2380 } counter drop
# Patroni REST API: nodes and HAProxy hosts (health checks)
tcp dport 8008 ip saddr { @nodes_v4, @clients_v4 } accept
tcp dport 8008 counter drop
# PostgreSQL: nodes (replication) and applications
tcp dport 5432 ip saddr { @nodes_v4, @clients_v4 } accept
tcp dport 5432 counter drop
}
}Code language: PHP (php)
nft -c -f /etc/nftables.conf && systemctl reload nftables
5. Certificates
Everything in this cluster talks TLS: etcd peers, Patroni to etcd, the REST API and PostgreSQL clients. Use a dedicated internal CA for the cluster. On an admin workstation (not on the nodes), create the CA and one certificate per node, valid for both server and client use:
mkdir -p ~/pg-cluster-ca && cd ~/pg-cluster-ca
umask 077
openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes \
-days 3650 -subj "/CN=PG Cluster CA" -keyout ca.key -out ca.crt
for n in 1 2 3; do
H=pg-0$n; IP=10.20.0.4$n
openssl req -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes \
-subj "/CN=$H.example.org" -keyout $H.key -out $H.csr
openssl x509 -req -in $H.csr -CA ca.crt -CAkey ca.key -CAcreateserial -days 825 -out $H.crt \
-extfile <(printf 'subjectAltName=DNS:%s.example.org,DNS:%s,DNS:localhost,IP:%s,IP:127.0.0.1\nbasicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature\nextendedKeyUsage=serverAuth,clientAuth\n' "$H" "$H" "$IP")
done
openssl verify -CAfile ca.crt pg-0*.crtCode language: PHP (php)
clientAuth is included because the same certificate authenticates each node to the etcd peers, and Patroni to etcd.
The files go into two places on each node (shown here for pg-01; repeat with each node’s own files). etcd needs its own copy because it runs as user etcd:
# For etcd (created after package installation, when the etcd user exists, see section 6)
install -d -m 0750 -o root -g etcd /etc/etcd/ssl
install -m 0644 -o root -g etcd ca.crt /etc/etcd/ssl/ca.crt
install -m 0644 -o root -g etcd pg-01.crt /etc/etcd/ssl/server.crt
install -m 0640 -o root -g etcd pg-01.key /etc/etcd/ssl/server.key
# For Patroni and PostgreSQL (user postgres)
install -d -m 0750 -o postgres -g postgres /etc/patroni/ssl
install -m 0644 -o postgres -g postgres ca.crt /etc/patroni/ssl/ca.crt
install -m 0644 -o postgres -g postgres pg-01.crt /etc/patroni/ssl/server.crt
install -m 0600 -o postgres -g postgres pg-01.key /etc/patroni/ssl/server.keyCode language: PHP (php)
PostgreSQL insists that its private key is 0600 when owned by postgres. Keep ca.key off the nodes.
6. Install the packages
(all nodes) Installing PostgreSQL normally creates and starts a default cluster 17/main. With Patroni, that’s in the way: Patroni must create and own the cluster. Tell postgresql-common not to create it, and enable data checksums for the cluster Patroni will create:
apt update
apt install postgresql-common
cat >> /etc/postgresql-common/createcluster.conf <<'EOF'
# Patroni creates the cluster; don't create one on package installation
create_main_cluster = false
# Detect storage corruption: checksum every data page
initdb_options = '--data-checksums'
EOFCode language: PHP (php)
Now install the rest:
apt install postgresql-17 patroni python3-etcd etcd-server etcd-client
pg_lsclusters # must list no clustersCode language: PHP (php)
| Package | Purpose |
|---|---|
postgresql-17 | PostgreSQL 17 |
patroni | The HA manager, with Debian’s pg_createconfig_patroni and patroni@ units |
python3-etcd | The client library Patroni’s etcd support builds on |
etcd-server, etcd-client | etcd 3.5 and etcdctl |
HAProxy doesn’t belong on the database nodes. It runs on the application hosts (section 11).
If a
17/maincluster was created anyway (because PostgreSQL was installed before), remove it:pg_dropcluster --stop 17 main. This deletes its data. Don’t do it on a server with data you need.
7. The etcd cluster
(all nodes) Debian starts etcd after installation as a stand-alone, single-member instance. That data must go, otherwise the members refuse to form a cluster:
systemctl stop etcd
rm -rf /var/lib/etcd/*Code language: JavaScript (javascript)
(all nodes) Configure etcd in /etc/default/etcd (shown for pg-01; change the name and the four node addresses on each node):
# --- Identity ------------------------------------------------------------------
ETCD_NAME="pg-01"
ETCD_DATA_DIR="/var/lib/etcd/default"
# --- Peer traffic (between etcd members) ---------------------------------------
ETCD_LISTEN_PEER_URLS="https://10.20.0.41:2380"
ETCD_INITIAL_ADVERTISE_PEER_URLS="https://10.20.0.41:2380"
# --- Client traffic (Patroni, etcdctl) -----------------------------------------
ETCD_LISTEN_CLIENT_URLS="https://10.20.0.41:2379,https://127.0.0.1:2379"
ETCD_ADVERTISE_CLIENT_URLS="https://10.20.0.41:2379"
# --- Initial cluster (identical on all nodes) ----------------------------------
ETCD_INITIAL_CLUSTER="pg-01=https://10.20.0.41:2380,pg-02=https://10.20.0.42:2380,pg-03=https://10.20.0.43:2380"
ETCD_INITIAL_CLUSTER_STATE="new"
ETCD_INITIAL_CLUSTER_TOKEN="pg-etcd-prod"
# --- Client TLS: clients must present a certificate signed by the cluster CA ----
ETCD_CERT_FILE="/etc/etcd/ssl/server.crt"
ETCD_KEY_FILE="/etc/etcd/ssl/server.key"
ETCD_TRUSTED_CA_FILE="/etc/etcd/ssl/ca.crt"
ETCD_CLIENT_CERT_AUTH="true"
# --- Peer TLS: members must present a certificate signed by the cluster CA ------
ETCD_PEER_CERT_FILE="/etc/etcd/ssl/server.crt"
ETCD_PEER_KEY_FILE="/etc/etcd/ssl/server.key"
ETCD_PEER_TRUSTED_CA_FILE="/etc/etcd/ssl/ca.crt"
ETCD_PEER_CLIENT_CERT_AUTH="true"
# --- Housekeeping ----------------------------------------------------------------
# Compact the key history every hour, so the database doesn't grow forever
ETCD_AUTO_COMPACTION_MODE="periodic"
ETCD_AUTO_COMPACTION_RETENTION="1"Code language: PHP (php)
Start etcd on all three nodes within a short time. The first member waits for the others to form a quorum:
systemctl enable etcd
systemctl start etcd
Check the cluster from any node. Set these variables once per shell (or put them in /root/.etcdctl, and source it):
export ETCDCTL_ENDPOINTS=https://pg-01.example.org:2379,https://pg-02.example.org:2379,https://pg-03.example.org:2379
export ETCDCTL_CACERT=/etc/etcd/ssl/ca.crt
export ETCDCTL_CERT=/etc/etcd/ssl/server.crt
export ETCDCTL_KEY=/etc/etcd/ssl/server.key
etcdctl member list -w table
etcdctl endpoint health --cluster # all three "is healthy"
etcdctl endpoint status -w table # one member shows IS LEADER = trueCode language: PHP (php)
Finally, change ETCD_INITIAL_CLUSTER_STATE to "existing" on all nodes. The value only matters for the very first start, and existing prevents a member that lost its data from accidentally starting a new cluster.
Without a client certificate, etcd refuses every request, which is the point. Any certificate from the cluster CA grants full access. For an extra layer, enable etcd’s role-based access control and give Patroni a user restricted to its key prefix (
/postgresql-common/). See the etcd documentation on authentication.
8. Patroni configuration
8.1 Tell Patroni about etcd
(all nodes) Debian’s Patroni integration reads its DCS settings from /etc/patroni/dcs.yml. The shipped file points to ZooKeeper. Replace it completely:
# /etc/patroni/dcs.yml: etcd v3 API with mutual TLS
etcd3:
hosts:
- pg-01.example.org:2379
- pg-02.example.org:2379
- pg-03.example.org:2379
protocol: https
cacert: /etc/patroni/ssl/ca.crt
cert: /etc/patroni/ssl/server.crt
key: /etc/patroni/ssl/server.keyCode language: PHP (php)
8.2 Generate the cluster configuration
pg_createconfig_patroni --hostip=10.20.0.41 --network=10.20.0.0/24 17 main # on pg-01
pg_createconfig_patroni --hostip=10.20.0.42 --network=10.20.0.0/24 17 main # on pg-02
pg_createconfig_patroni --hostip=10.20.0.43 --network=10.20.0.0/24 17 main # on pg-03Code language: PHP (php)
This writes /etc/patroni/17-main.yml with Debian’s paths (data in /var/lib/postgresql/17/main, config in /etc/postgresql/17/main) and Debian’s bootstrap scripts (pg_createcluster_patroni creates the primary, pg_clonecluster_patroni clones replicas). The scope is 17-main, and the etcd namespace is /postgresql-common/.
8.3 Harden the generated configuration
The generated file is a starting point. It contains placeholder passwords and md5 authentication. Edit /etc/patroni/17-main.yml, keep Debian’s values for scope, namespace, name, data_dir, bin_dir, config_dir, pgpass and the bootstrap or replica method entries, and make the following sections look like this (addresses for pg-01):
restapi:
listen: 10.20.0.41:8008
connect_address: 10.20.0.41:8008
certfile: /etc/patroni/ssl/server.crt
keyfile: /etc/patroni/ssl/server.key
cafile: /etc/patroni/ssl/ca.crt
# Health endpoints work without a client certificate; changes need authentication
verify_client: optional
ctl:
cacert: /etc/patroni/ssl/ca.crt
certfile: /etc/patroni/ssl/server.crt
keyfile: /etc/patroni/ssl/server.key
bootstrap:
dcs:
ttl: 30
loop_wait: 10
retry_timeout: 10
# A replica more than 1 MB behind may not become leader
maximum_lag_on_failover: 1048576
# Commit waits for one synchronous replica; only it may be promoted
synchronous_mode: true
synchronous_node_count: 1
postgresql:
use_pg_rewind: true
use_slots: true
parameters:
wal_level: replica
hot_standby: "on"
max_wal_senders: 10
max_replication_slots: 10
wal_keep_size: 1GB
wal_log_hints: "on"
# (keep Debian's "method: pg_createcluster" and its pg_createcluster block here)
postgresql:
listen: 10.20.0.41,127.0.0.1:5432
connect_address: 10.20.0.41:5432
use_unix_socket: true
# (keep Debian's data_dir, bin_dir, config_dir, pgpass, create_replica_methods)
authentication:
superuser:
username: postgres
replication:
username: replicator
rewind:
username: rewind_user
# Passwords come from /etc/patroni/env.conf (section 8.4)
parameters:
password_encryption: scram-sha-256
ssl: "on"
ssl_cert_file: /etc/patroni/ssl/server.crt
ssl_key_file: /etc/patroni/ssl/server.key
ssl_ca_file: /etc/patroni/ssl/ca.crt
ssl_min_protocol_version: TLSv1.2
pg_hba:
- local all all peer
- hostssl replication replicator 10.20.0.41/32 scram-sha-256
- hostssl replication replicator 10.20.0.42/32 scram-sha-256
- hostssl replication replicator 10.20.0.43/32 scram-sha-256
- hostssl all rewind_user 10.20.0.41/32 scram-sha-256
- hostssl all rewind_user 10.20.0.42/32 scram-sha-256
- hostssl all rewind_user 10.20.0.43/32 scram-sha-256
- hostssl all all 10.20.10.0/24 scram-sha-256
watchdog:
mode: required
device: /dev/watchdog
safety_margin: 5Code language: PHP (php)
| Setting | Why |
|---|---|
synchronous_mode: true | Every commit waits until one replica has the WAL. On failover, Patroni promotes only that replica, so no committed transaction is lost. |
maximum_lag_on_failover | If synchronous mode can’t be honoured, a badly lagging replica still can’t become leader |
use_pg_rewind: true | An old primary rejoins quickly by rewinding its divergent WAL, instead of a full re-clone |
use_slots: true | Replication slots keep WAL a replica still needs, so replicas don’t fall out of sync after a short outage |
pg_hba with hostssl and scram-sha-256 | Only TLS connections, only modern password hashes, and replication only between the nodes |
local all all peer | Patroni and admins on the node connect as the OS user postgres through the socket, without a password |
verify_client: optional | Health checks (HAProxy, monitoring) can query /primary, /replica and /health. Changes through the API require authentication. |
watchdog: mode: required | A node can only become leader with a working watchdog (section 9) |
bootstrap.dcsis only read once, when the cluster is first created. After that, these settings live in etcd. Change them withpatronictl edit-config(section 15), not in the YAML file.
8.4 Secrets outside the config file
Debian’s patroni@.service reads /etc/patroni/env.conf. Patroni takes passwords from environment variables, so the YAML file never contains a secret. Generate strong passwords once, and use the same values on all three nodes:
for v in SUPERUSER REPLICATION REWIND RESTAPI; do
echo "PATRONI_${v}_PASSWORD=$(openssl rand -base64 30 | tr -d '/+=')"
doneCode language: PHP (php)
Create /etc/patroni/env.conf (same content on all nodes):
PATRONI_SUPERUSER_USERNAME=postgres
PATRONI_SUPERUSER_PASSWORD=<generated>
PATRONI_REPLICATION_USERNAME=replicator
PATRONI_REPLICATION_PASSWORD=<generated>
PATRONI_REWIND_USERNAME=rewind_user
PATRONI_REWIND_PASSWORD=<generated>
PATRONI_RESTAPI_USERNAME=patroni
PATRONI_RESTAPI_PASSWORD=<generated>Code language: HTML, XML (xml)
chown root:root /etc/patroni/env.conf
chmod 0600 /etc/patroni/env.conf
systemd reads the file as root before starting Patroni as postgres, so the postgres user doesn’t even need read access to it.
9. The watchdog
If the primary’s Patroni process hangs (for example, the VM freezes), it can’t demote PostgreSQL. When it wakes up, a new leader might already exist: two primaries. The watchdog prevents that. Patroni feeds a timer, and if Patroni stops feeding it, the kernel reboots the node before the leader key expires.
(all nodes) In a VM, give it a virtual watchdog device. On KVM/QEMU and Proxmox, add an i6300esb watchdog to the VM. Otherwise, use the kernel’s software watchdog:
echo softdog > /etc/modules-load.d/softdog.conf
modprobe softdogCode language: JavaScript (javascript)
Patroni runs as postgres and must be able to open the device. Create /etc/udev/rules.d/60-watchdog.rules:
KERNEL=="watchdog", OWNER="postgres", GROUP="postgres", MODE="0600"Code language: JavaScript (javascript)
udevadm control --reload && udevadm trigger --subsystem-match=misc
ls -l /dev/watchdog # crw------- postgres postgresCode language: PHP (php)
The software watchdog runs inside the kernel it protects, so it can’t catch a completely frozen kernel. A hypervisor-provided device (
i6300esb) can. Withmode: required, Patroni refuses to become leader if the device is missing.
10. Start the cluster
On pg-01 first. Patroni finds no cluster in etcd, takes the leader key, and bootstraps a new PostgreSQL cluster:
systemctl enable --now patroni@17-main
journalctl -u patroni@17-main -f # until "no action. I am (pg-01), the leader with the lock"Code language: PHP (php)
Then pg-02 and pg-03. They find a leader, clone it with pg_basebackup (through Debian’s pg_clonecluster_patroni), and start streaming:
systemctl enable --now patroni@17-mainCode language: CSS (css)
Check the result. patronictl needs the REST API password for changes, so this helper reads it from env.conf. Put it in root’s .bashrc:
pctl() { ( set -a; . /etc/patroni/env.conf; set +a; patronictl -c /etc/patroni/17-main.yml "$@" ); }Code language: JavaScript (javascript)
pctl listCode language: PHP (php)
+ Cluster: 17-main ----------+--------------+-----------+----+-----------+
| Member | Host | Role | State | TL | Lag in MB |
+--------+------------+--------------+-----------+----+-----------+
| pg-01 | 10.20.0.41 | Leader | running | 1 | |
| pg-02 | 10.20.0.42 | Sync Standby | streaming | 1 | 0 |
| pg-03 | 10.20.0.43 | Replica | streaming | 1 | 0 |
+--------+------------+--------------+-----------+----+-----------+
Debian’s own postgresql@17-main.service must not run alongside Patroni. Patroni manages PostgreSQL itself. Make sure it’s never started:
cat /etc/postgresql/17/main/start.conf # must say "manual" or "disabled"Code language: PHP (php)
If it says auto, set it to manual (echo manual > /etc/postgresql/17/main/start.conf). Otherwise postgresql.service would try to start the cluster at boot, next to Patroni.
11. Client access: VIP, HAProxy and keepalived
Clients must always reach the current primary, wherever it is after a failover. There are several ways to do that, and they fit different environments:
| Approach | How clients find the primary | Best for |
|---|---|---|
| A. VIP with vip-manager | One floating IP that always sits on the Patroni leader | Simple setups in one L2 network: the easiest client configuration |
| B. HAProxy on the application hosts | Local HAProxy health-checks Patroni’s /primary | Few application servers; no extra hosts needed |
| C. HAProxy pair with keepalived | A VIP (keepalived) on two dedicated proxies, which route by Patroni health checks | Many clients, read/write split, and a central entry point |
| D. libpq multi-host | The client driver tries all nodes and picks the writable one | No extra component at all |
11.1 Why not keepalived on the database nodes?
It’s tempting: keepalived is well known, and a VIP on the database nodes sounds simple. But keepalived elects its VIP owner through VRRP, completely separately from Patroni’s leader election in etcd. In a network partition, the two elections can disagree, and the VIP ends up on a node that isn’t the primary. Clients then get read-only errors, or worse, reach a node that’s about to be demoted.
You could make keepalived follow Patroni with a track_script that checks /primary. That works most of the time, but it still layers a second consensus mechanism on top of the first. vip-manager solves the problem cleanly: it doesn’t elect anything, it simply puts the VIP wherever the etcd leader key points. The VIP can’t disagree with Patroni, because it’s driven by the same decision. Keep keepalived for the layer where it shines: a redundant pair of proxies (11.4).
11.2 Option A: a VIP on the leader with vip-manager
vip-manager runs on all three nodes. Every second it reads the leader key in etcd. The node whose name matches the key adds the VIP to its interface, and the others remove it. During a failover, the VIP moves with the leader.
Extra placeholders for this option:
| Placeholder | Meaning |
|---|---|
10.20.0.40 | The VIP (a free address in the nodes’ subnet) |
pg.example.org | DNS name for the VIP: what applications connect to |
ens18 | The network interface that carries 10.20.0.0/24 |
1. Certificates must include the VIP. Clients that verify the server name (sslmode=verify-full) connect to pg.example.org, but reach whichever node holds the VIP. Reissue each node’s certificate (section 5) with the VIP’s name and address added to the SAN:
subjectAltName=DNS:pg-01.example.org,DNS:pg-01,DNS:pg.example.org,DNS:localhost,IP:10.20.0.41,IP:10.20.0.40,IP:127.0.0.1
2. PostgreSQL must accept connections on the VIP. A node can only bind to an address it owns, and the VIP moves. Let PostgreSQL listen on all addresses: firewall and pg_hba already decide who may connect. In /etc/patroni/17-main.yml, change:
postgresql:
listen: "*:5432"Code language: JavaScript (javascript)
3. Install and configure vip-manager. (all nodes)
apt install vip-manager
Debian’s pg_createconfig_patroni --vip=... can generate the file, but it builds plain http:// etcd endpoints from IP addresses in dcs.yml, and it doesn’t fill in TLS settings. With the TLS etcd from this guide, write the file yourself. Debian’s vip-manager@.service reads /etc/patroni/<cluster>.vip, so create /etc/patroni/17-main.vip (change VIP_HOST per node):
# /etc/patroni/17-main.vip: environment for vip-manager@17-main
VIP_IP="10.20.0.40"
VIP_MASK="24"
VIP_NETMASK="24"
VIP_IFACE="ens18"
# The Patroni leader key: <namespace>/<scope>/leader
VIP_KEY="/postgresql-common/17-main/leader"
VIP_TRIGGER_KEY="/postgresql-common/17-main/leader"
# This node's Patroni member name: the VIP goes here when the key holds this value
VIP_HOST="pg-01"
VIP_TRIGGER_VALUE="pg-01"
VIP_TYPE="etcd"
VIP_DCS_TYPE="etcd"
VIP_ENDPOINT="https://pg-01.example.org:2379,https://pg-02.example.org:2379,https://pg-03.example.org:2379"
VIP_DCS_ENDPOINTS="https://pg-01.example.org:2379,https://pg-02.example.org:2379,https://pg-03.example.org:2379"
VIP_ETCD_CA_FILE="/etc/patroni/ssl/ca.crt"
VIP_ETCD_CERT_FILE="/etc/patroni/ssl/server.crt"
VIP_ETCD_KEY_FILE="/etc/patroni/ssl/server.key"
# Check every second, retry 3 times before giving up on etcd
VIP_INTERVAL="1000"
VIP_RETRY_AFTER="250"
VIP_RETRY_NUM="3"Code language: PHP (php)
Both spellings of the key, value, type and endpoint variables are set on purpose. Debian’s template and the upstream documentation use different names, and setting both works with either.
chmod 0600 /etc/patroni/17-main.vip
systemctl enable --now vip-manager@17-main
journalctl -u vip-manager@17-main -n 20 --no-pager
4. Check it.
pctl list # who is Leader?
ip -br addr show ens18 # the leader shows 10.20.0.40 as a second address
pctl switchover --leader pg-01 --candidate pg-02 --force
ip -br addr show ens18 # on pg-02: the VIP moved within ~2 sCode language: PHP (php)
If the VIP never appears,
journalctl -u vip-manager@17-maintells you why. The usual causes are a certificate error, a wrong interface name, or a trigger value that doesn’t match the Patroni member name (pctl listshows the names). If the log shows successful etcd connections but the key is never found, your vip-manager build reads a different etcd key space than Patroni’s v3 API writes. In that case, use Option B or C, which rely only on Patroni’s REST API.
Applications then connect to pg.example.org:5432 with sslmode=verify-full. Point the DNS name at the VIP and you’re done: no proxy, no client-side magic.
Limits: a VIP needs all nodes in one L2 network (the same VLAN), because it’s announced with ARP. It doesn’t work across subnets or data centres, and in most public clouds it needs their API instead (vip-manager’s hetzner mode is one example). It also gives you no read-only endpoint. For that, add Option B or C next to it.
11.3 Option B: HAProxy on the application hosts
Patroni’s REST API answers the routing question directly: GET /primary returns 200 only on the leader, and GET /replica returns 200 only on healthy replicas. Install HAProxy on each application host, and add to /etc/haproxy/haproxy.cfg:
listen pg-primary
bind 127.0.0.1:5432
mode tcp
option tcpka
timeout client 8h
timeout server 8h
option httpchk GET /primary
http-check expect status 200
default-server inter 3s fall 3 rise 2 on-marked-down shutdown-sessions check port 8008 check-ssl verify required ca-file /etc/haproxy/pg-cluster-ca.crt
server pg-01 10.20.0.41:5432
server pg-02 10.20.0.42:5432
server pg-03 10.20.0.43:5432
listen pg-replicas
bind 127.0.0.1:5433
mode tcp
balance leastconn
option tcpka
timeout client 8h
timeout server 8h
# Healthy replicas no more than 16 MB behind
option httpchk GET /replica?lag=16MB
http-check expect status 200
default-server inter 3s fall 3 rise 2 on-marked-down shutdown-sessions check port 8008 check-ssl verify required ca-file /etc/haproxy/pg-cluster-ca.crt
server pg-01 10.20.0.41:5432
server pg-02 10.20.0.42:5432
server pg-03 10.20.0.43:5432Code language: PHP (php)
Copy the cluster’s ca.crt to /etc/haproxy/pg-cluster-ca.crt. Applications connect to 127.0.0.1:5432 for reads and writes, and 127.0.0.1:5433 for read-only queries, with sslmode=verify-ca and the cluster CA. TLS runs end-to-end through HAProxy (mode tcp).
| Setting | Why |
|---|---|
option httpchk GET /primary | Only the node Patroni considers leader passes. A demoted or isolated old primary fails the check immediately. |
check-ssl verify required ca-file | The health check itself runs over TLS and verifies the node’s certificate |
on-marked-down shutdown-sessions | Connections to a former primary are cut at once, so applications reconnect to the new one instead of hanging |
/replica?lag=16MB | Replicas that fall behind drop out of the read pool automatically |
11.4 Option C: a redundant HAProxy pair with keepalived
With many application servers, a central entry point is easier to manage than one HAProxy per host. Two dedicated proxy hosts run the HAProxy configuration from 11.3, and keepalived moves a VIP between them. If the active proxy (or its HAProxy) dies, the standby takes over the VIP within about 3 seconds. Here keepalived is exactly the right tool: it decides between two stateless proxies, while Patroni alone decides about the database.
Extra placeholders:
| Placeholder | Meaning |
|---|---|
pgproxy-01 / 10.20.10.11 | Proxy 1 (normally active) |
pgproxy-02 / 10.20.10.12 | Proxy 2 (standby) |
10.20.10.50 / pg.example.org | The proxies’ VIP: what applications connect to |
On both proxies, install the packages and apply the HAProxy configuration from 11.3, but with bind :5432 and bind :5433, so HAProxy also accepts connections on the VIP when it arrives:
apt install haproxy keepalived
keepalived runs its health-check script as a dedicated unprivileged user:
useradd --system --no-create-home --shell /usr/sbin/nologin keepalived_script
Create /etc/keepalived/keepalived.conf on pgproxy-01:
global_defs {
router_id pgproxy-01
enable_script_security
script_user keepalived_script
}
# The VIP may only sit on a proxy whose HAProxy is running
vrrp_script chk_haproxy {
script "/usr/bin/systemctl is-active --quiet haproxy"
interval 2
fall 2
rise 2
}
vrrp_instance PG_PROXY {
state BACKUP
interface ens18
virtual_router_id 52
priority 150
advert_int 1
nopreempt
# Unicast VRRP: no multicast, and only the peer is accepted
unicast_src_ip 10.20.10.11
unicast_peer {
10.20.10.12
}
virtual_ipaddress {
10.20.10.50/24 dev ens18
}
track_script {
chk_haproxy
}
}
On pgproxy-02, use the same file with router_id pgproxy-02, priority 100, unicast_src_ip 10.20.10.12 and unicast_peer { 10.20.10.11 }.
| Setting | Why |
|---|---|
state BACKUP on both + nopreempt | After a failover, the VIP stays where it is when the old proxy returns. That avoids a second, unnecessary interruption. |
unicast_src_ip / unicast_peer | VRRP goes only between the two proxies, with no multicast on the network, and announcements from other hosts are ignored |
track_script | A proxy whose HAProxy crashed gives up the VIP, even though the machine is still up |
enable_script_security + script_user | The check runs unprivileged, and keepalived refuses scripts that non-root users could modify |
virtual_router_id 52 | Must be unique in the L2 network. Don’t reuse an ID that other keepalived pairs already use. |
Allow VRRP between the proxies, and PostgreSQL from the applications. Create /etc/nftables.d/pgproxy.nft on both proxies (shown for pgproxy-01):
destroy table inet pgproxy
table inet pgproxy {
chain input {
type filter hook input priority filter - 10; policy accept;
iif "lo" accept
# VRRP from the peer proxy only
ip protocol vrrp ip saddr 10.20.10.12 accept
ip protocol vrrp counter drop
# PostgreSQL (read/write and read-only) from the application network
tcp dport { 5432, 5433 } ip saddr 10.20.10.0/24 accept
tcp dport { 5432, 5433 } counter drop
}
}Code language: PHP (php)
nft -c -f /etc/nftables.conf && systemctl reload nftables
systemctl enable --now haproxy keepalived
ip -br addr show ens18 # pgproxy-01 holds 10.20.10.50Code language: PHP (php)
Test the proxy failover: stop HAProxy on the active proxy (systemctl stop haproxy). Within a few seconds, ip -br addr shows the VIP on the other proxy, and psql "host=pg.example.org ..." keeps working. Start HAProxy again, and the VIP stays put (nopreempt).
Applications connect to pg.example.org:5432 (read/write) and pg.example.org:5433 (read-only). Two independent mechanisms do two separate jobs: keepalived keeps a proxy reachable, and Patroni health checks send traffic to the primary.
11.5 Option D: libpq multi-host
Every libpq-based client (psql, and most drivers) can try several hosts and pick the writable one:
postgresql://app@pg-01.example.org,pg-02.example.org,pg-03.example.org/appdb?target_session_attrs=read-write&sslmode=verify-full&sslrootcert=/etc/ssl/pg-cluster-ca.crtCode language: JavaScript (javascript)
It’s simple and has no extra component. Reconnects after a failover take a little longer, because the client tries the hosts one by one. Use target_session_attrs=prefer-standby for read-only connections.
11.6 Which one?
- One VLAN, simple needs: Option A (vip-manager). It’s the least moving parts for clients, and it can’t disagree with Patroni.
- Read/write split, many clients, or several subnets: Option C (HAProxy pair with keepalived), optionally combined with A.
- A handful of application servers: Option B, or simply D.
12. Testing
12.1 Replication and synchronous commit
# On the leader
sudo -u postgres psql -c "CREATE TABLE ha_test (id int PRIMARY KEY, note text);
INSERT INTO ha_test VALUES (1, 'before failover');"
sudo -u postgres psql -c "SELECT application_name, state, sync_state FROM pg_stat_replication;"
# one replica "sync", one "async" (or "potential")
# On a replica
sudo -u postgres psql -c "SELECT * FROM ha_test;" # the row is thereCode language: PHP (php)
12.2 Planned switchover
pctl switchover --leader pg-01 --candidate pg-02 --force
pctl list # pg-02 is Leader, pg-01 streams from itCode language: PHP (php)
12.3 Unplanned failover
systemctl stop patroni@17-main # on the current leader (or hard power-off the VM)
pctl list # on another node, within ~30 s: a new leader
sudo -u postgres psql -h 127.0.0.1 -c "SELECT * FROM ha_test;" # nothing lost
systemctl start patroni@17-main # the old leader rejoins as a replica (pg_rewind)Code language: PHP (php)
Through HAProxy, applications reconnect to the new primary on their own. Check the pg-primary backend on the stats page, or just reconnect with psql -h 127.0.0.1.
12.4 Losing etcd
systemctl stop etcd # on ONE node: cluster unaffected (quorum 2 of 3)
etcdctl endpoint health --cluster # one unhealthy, two healthy
systemctl start etcdCode language: PHP (php)
Stop etcd on two nodes, and etcd loses its quorum. Patroni can no longer renew the leader key, so the primary demotes itself to read-only after ttl. That’s intended: without consensus, no node may claim to be primary. (Patroni 4’s failsafe_mode, set with patronictl edit-config, can keep the primary running during a pure etcd outage, as long as all Patroni nodes can still reach each other. Consider it if your etcd runs separately from the database nodes.)
12.5 TLS everywhere
curl -s --cacert /etc/patroni/ssl/ca.crt https://pg-01.example.org:8008/health -o /dev/null -w '%{http_code}\n' # 200
curl -s http://pg-01.example.org:8008/health # fails: TLS only
psql "host=pg-01.example.org dbname=postgres user=app sslmode=disable" # rejected by pg_hbaCode language: PHP (php)
Clean up with DROP TABLE ha_test; on the leader.
13. Monitoring
Patroni exposes Prometheus metrics at https://<node>:8008/metrics, and etcd at https://<node>:2379/metrics (that one needs a client certificate). Scrape both, and alert on at least these:
- alert: PatroniNoLeader
expr: sum by (scope) (patroni_primary) != 1
for: 1m
labels:
severity: critical
annotations:
summary: "Patroni cluster {{ $labels.scope }} has {{ $value }} leaders (must be exactly 1)"
- alert: PatroniPostgresDown
expr: patroni_postgres_running == 0
for: 1m
labels:
severity: critical
annotations:
summary: "PostgreSQL isn't running on {{ $labels.instance }}"
- alert: PatroniDcsUnreachable
expr: time() - patroni_dcs_last_seen > 60
for: 1m
labels:
severity: warning
annotations:
summary: "{{ $labels.instance }} hasn't reached etcd for over a minute"
- alert: EtcdNoLeader
expr: etcd_server_has_leader == 0
for: 1m
labels:
severity: critical
annotations:
summary: "etcd member {{ $labels.instance }} has no leader"Code language: JavaScript (javascript)
Add the PostgreSQL view as well, with replication lag from pg_stat_replication and database health, for example through prometheus-postgres-exporter (in Debian).
14. Backups
Replication protects against server failure, not against DELETE without a WHERE. That’s replicated instantly. You need backups with point-in-time recovery (PITR).
The standard tool is pgBackRest (Debian package pgbackrest). It knows about Patroni clusters, backs up from a replica to spare the primary, archives WAL continuously, and restores to any second. The outline:
- Set up a repository: a dedicated backup host, or object storage (S3-compatible), encrypted (
repo1-cipher-type=aes-256-cbc). - Enable WAL archiving through Patroni:
patronictl edit-config, and setarchive_mode: "on"andarchive_command: "pgbackrest --stanza=17-main archive-push %p". - Schedule full and differential backups, and test restores regularly.
pgBackRest deserves a post of its own. The important part here: plan it from day one, and keep at least one copy outside the cluster’s infrastructure.
Also back up etcd’s configuration state, mainly for disaster recovery documentation. Patroni can rebuild its keys from a running PostgreSQL, but a snapshot costs nothing:
etcdctl snapshot save /var/backups/etcd-$(date +%F).dbCode language: JavaScript (javascript)
15. Day-2 operations
| Task | Command |
|---|---|
| Cluster status | pctl list |
| Planned switchover (maintenance) | pctl switchover --leader pg-01 --candidate pg-02 |
| Change PostgreSQL parameters cluster-wide | pctl edit-config, then pctl restart 17-main if pctl list shows “Pending restart” |
| Rolling restart | pctl restart 17-main --pending (replicas first, then the leader with a switchover) |
| Rebuild a broken replica from scratch | pctl reinit 17-main pg-03 |
| Pause automatic failover (e.g. for maintenance on etcd) | pctl pause โฆ pctl resume |
| Failover history | pctl history |
| etcd health and leader | etcdctl endpoint status --cluster -w table |
| Defragment etcd (after many compactions) | etcdctl defrag --cluster |
Patching (rolling): for each replica in turn, stop Patroni, upgrade, reboot, start, and wait for streaming. Then switch over away from the leader, and patch it last. Stagger the unattended-upgrades reboot windows (see my unattended-upgrades post), so no two nodes reboot together. The two etcd members on the other nodes keep the quorum.
Never edit postgresql.conf or pg_hba.conf in /etc/postgresql/17/main/ by hand. Patroni overwrites them. Everything goes through 17-main.yml (node-local) or patronictl edit-config (cluster-wide).
16. Troubleshooting
| Symptom | Cause / fix |
|---|---|
etcd won’t start: member ... has already been bootstrapped or cluster ID mismatch | Old data from Debian’s automatic single-node start. Stop etcd, empty /var/lib/etcd/, and start all members again. |
etcd: remote error: tls: bad certificate | Certificate not signed by the cluster CA, missing clientAuth, or the node’s IP isn’t in its SAN |
Patroni: failed to connect to etcd | dcs.yml wasn’t applied before pg_createconfig_patroni (check the etcd3: section in 17-main.yml), or there’s a certificate or firewall problem |
Patroni: watchdog is not available, refusing to become leader | /dev/watchdog is missing or not owned by postgres (section 9) |
Replica stuck in creating replica | Replication login refused: check the pg_hba entries, PATRONI_REPLICATION_PASSWORD (identical on all nodes), and port 5432 between nodes |
| Writes hang on the leader | synchronous_mode with no healthy sync replica. Check pctl list. Patroni falls back to async unless synchronous_mode_strict is on. |
| Cluster read-only, no leader | etcd lost its quorum (two etcd members down). Restore etcd first. |
| Old leader won’t rejoin after failover | pg_rewind failed (missing rewind user rights or WAL). Run pctl reinit 17-main <member>. |
pg_lsclusters shows the cluster as “down” | Normal: Debian’s tools don’t know about Patroni-managed instances. Use pctl list. |
17. Checklist
- โ Three nodes on separate hypervisor hosts, with fast disks for etcd and low latency between them
- โ The firewall allows etcd (2379/2380) between nodes only, and the REST API and PostgreSQL only from nodes and applications
- โ A dedicated cluster CA, and per-node certificates with all names and IPs, valid for server and client use
- โ
create_main_cluster = falseand--data-checksumsincreatecluster.conf, and no Debian-managed17/maincluster - โ etcd: three members, mutual TLS for peers and clients, auto-compaction,
INITIAL_CLUSTER_STATE=existingafter the first start - โ
dcs.ymlpoints to etcd v3 over HTTPS with client certificates - โ
17-main.yml: REST API over TLS, synchronous mode,pg_rewind, slots,hostssl+ SCRAM only inpg_hba, watchdog required - โ Passwords only in
/etc/patroni/env.conf(0600 root:root), identical on all nodes - โ A watchdog device (i6300esb, or softdog) is owned by
postgres - โ
pctl listshows one Leader, one Sync Standby and one Replica, all streaming - โ Client access chosen deliberately: a VIP via vip-manager (certificates include the VIP, and PostgreSQL listens on
*), and/or HAProxy routing to/primaryand/replicawith TLS health checks - โ If there are central proxies: an HAProxy pair with keepalived (unicast VRRP,
track_script,nopreempt), with VRRP firewalled to the peer - โ No keepalived on the database nodes: the VIP follows etcd, not a second election
- โ The VIP moving on switchover and failover is tested, and so is proxy failover
- โ Switchover, failover, rejoin, single etcd loss and TLS enforcement were all tested
- โ Monitoring alerts on leader count, PostgreSQL down, DCS unreachable and etcd leader loss
- โ pgBackRest (or equivalent) with WAL archiving and tested PITR restores
- โ Rolling patch procedure documented, and reboot windows staggered