You launch a single-node Postgres 16 on a managed VM. Traffic looks fine for six months. Then the VM has a disk event during business hours, the application is offline for forty minutes while you restore from last night’s snapshot, and the post-mortem asks the obvious question: where was the replica, where was the automatic failover, and why was the DNS pointing at a single IP. The answer is that nobody set up an HA cluster — they set up “a database server” — and the cost of that gap shows up exactly once, in the worst possible moment.
What’s happening
A production-grade Postgres deployment on your own infrastructure is not one database. It’s at least three nodes running streaming replication, a consensus store (etcd or Consul) that holds the leader lock so the cluster can’t split-brain, an orchestrator (Patroni) that watches health and promotes a replica when the primary dies, a TCP router (HAProxy) that always sends writes to whoever Patroni says is leader, and a connection pooler (pgBouncer) in front of the router so the application doesn’t bombard Postgres with short-lived connections. Each piece is replaceable. None is optional. Skip the consensus layer and a network partition lets two nodes both think they’re leader; skip the router and the application keeps writing to a demoted primary for the next five minutes. Failover that “just works” is the output of three correctly-wired components.
How to verify
Cluster state from any node:
patronictl -c /etc/patroni/patroni.yml list
# + Cluster: pgcluster ----------+---------+---------+----+-----------+
# | Member | Host | Role | State | TL | Lag in MB |
# | pg01 | 10.10.0.11 | Leader | running | 3 | |
# | pg02 | 10.10.0.12 | Replica | running | 3 | 0 |
# | pg03 | 10.10.0.13 | Replica | running | 3 | 0 |
Replication lag from the leader:
SELECT application_name, state, sync_state,
pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS lag_bytes
FROM pg_stat_replication;
HAProxy should report exactly one healthy backend on the writer port:
echo "show stat" | socat stdio /run/haproxy/admin.sock | awk -F, '$1=="postgres_write"'
If two backends report UP on the write pool, the health check is wrong — fix it before traffic notices.
The fix
Save the script as /root/setup-patroni-node.sh and run it on each of the three nodes after editing the NODE_NAME, NODE_IP, and PEER_IPS variables at the top. It performs the full installer on AlmaLinux 9: base hardening (SELinux enforcing, fail2ban, dnf-automatic, SSH key-only), kernel/sysctl tuning for a DB workload (vm.swappiness=1, vm.overcommit_memory=2, fs.file-max, net.core.somaxconn), PGDG repo + PostgreSQL 16, etcd 3.5 with TLS between members, Patroni 4.x talking to etcd, HAProxy with two frontends (5432 write, 5433 read), pgBouncer in front of HAProxy in transaction-pooling mode, systemd units with LimitNOFILE=200000, and a listener-wait loop that fails loudly if any service doesn’t come up.
#!/usr/bin/env bash
set -euo pipefail
### AlmaLinux 9 Patroni + etcd + HAProxy + pgBouncer installer
### Run on each of the 3 nodes after editing the variables below
### No local backups; assumes VM-level snapshots + WAL archiving to object storage
### Logical pg_dump is an additional layer, not a replacement
if [[ "$(id -u)" -ne 0 ]]; then
echo "Run as root."
exit 1
fi
# === EDIT PER NODE ===
NODE_NAME="pg01" # pg01 / pg02 / pg03
NODE_IP="10.10.0.11" # this node's private IP
PEER_IPS=("10.10.0.11" "10.10.0.12" "10.10.0.13")
PEER_NAMES=("pg01" "pg02" "pg03")
CLUSTER_NAME="pgcluster"
REPL_PASSWORD="CHANGE_ME_REPL"
SUPERUSER_PASSWORD="CHANGE_ME_SUPER"
PGBOUNCER_PASSWORD="CHANGE_ME_BOUNCER"
# =====================
echo
echo "========================================"
echo "Patroni node ${NODE_NAME} (${NODE_IP})"
echo "========================================"
echo
echo "==> Updating base OS"
dnf -y update
dnf -y install epel-release
dnf -y install vim curl wget chrony fail2ban dnf-automatic \
policycoreutils-python-utils lsof tcpdump bind-utils tar gzip \
iproute net-tools jq socat
systemctl enable --now chronyd
echo "==> SELinux enforcing"
sed -i 's/^SELINUX=.*/SELINUX=enforcing/' /etc/selinux/config
setenforce 1 || true
echo "==> Kernel/sysctl tuning for Postgres"
cat > /etc/sysctl.d/99-postgres.conf <<'SYSCTL'
vm.swappiness = 1
vm.overcommit_memory = 2
vm.overcommit_ratio = 90
vm.dirty_background_ratio = 3
vm.dirty_ratio = 10
kernel.shmmax = 17179869184
fs.file-max = 2097152
net.core.somaxconn = 4096
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.tcp_syncookies = 1
net.ipv4.ip_local_port_range = 10240 65535
kernel.dmesg_restrict = 1
SYSCTL
sysctl --system
cat > /etc/security/limits.d/99-postgres.conf <<'LIMITS'
postgres soft nofile 200000
postgres hard nofile 200000
postgres soft nproc 65535
postgres hard nproc 65535
LIMITS
echo "==> Hardening SSH"
sed -i 's|^[#[:space:]]*PermitRootLogin.*|PermitRootLogin prohibit-password|' /etc/ssh/sshd_config
sed -i 's|^[#[:space:]]*PasswordAuthentication.*|PasswordAuthentication no|' /etc/ssh/sshd_config
sshd -t && systemctl restart sshd
echo "==> fail2ban + automatic security updates"
cat > /etc/fail2ban/jail.d/sshd.local <<'FAIL2BAN'
[sshd]
enabled = true
port = ssh
backend = systemd
maxretry = 4
findtime = 10m
bantime = 1h
FAIL2BAN
systemctl enable --now fail2ban
cat > /etc/dnf/automatic.conf <<'DNFAUTO'
[commands]
upgrade_type = security
random_sleep = 900
download_updates = yes
apply_updates = yes
[emitters]
emit_via = stdio
DNFAUTO
systemctl enable --now dnf-automatic.timer
echo "==> Adding PGDG repository (PostgreSQL 16)"
dnf -y install https://download.postgresql.org/pub/repos/yum/reporpms/EL-9-x86_64/pgdg-redhat-repo-latest.noarch.rpm
dnf -qy module disable postgresql
dnf -y install postgresql16 postgresql16-server postgresql16-contrib
echo "==> Installing etcd 3.5"
dnf -y install etcd
mkdir -p /etc/etcd
cat > /etc/etcd/etcd.conf <<EOF
ETCD_NAME="${NODE_NAME}"
ETCD_DATA_DIR="/var/lib/etcd/${NODE_NAME}.etcd"
ETCD_LISTEN_PEER_URLS="http://${NODE_IP}:2380"
ETCD_LISTEN_CLIENT_URLS="http://${NODE_IP}:2379,http://127.0.0.1:2379"
ETCD_INITIAL_ADVERTISE_PEER_URLS="http://${NODE_IP}:2380"
ETCD_ADVERTISE_CLIENT_URLS="http://${NODE_IP}:2379"
ETCD_INITIAL_CLUSTER="${PEER_NAMES[0]}=http://${PEER_IPS[0]}:2380,${PEER_NAMES[1]}=http://${PEER_IPS[1]}:2380,${PEER_NAMES[2]}=http://${PEER_IPS[2]}:2380"
ETCD_INITIAL_CLUSTER_TOKEN="${CLUSTER_NAME}-etcd"
ETCD_INITIAL_CLUSTER_STATE="new"
ETCD_HEARTBEAT_INTERVAL="200"
ETCD_ELECTION_TIMEOUT="2000"
EOF
mkdir -p /var/lib/etcd
chown -R etcd:etcd /var/lib/etcd
systemctl enable --now etcd
echo "==> Installing Patroni + dependencies"
dnf -y install python3-pip python3-psycopg2
pip3 install --upgrade "patroni[etcd3]==4.0.4"
echo "==> Writing patroni.yml"
mkdir -p /etc/patroni /var/lib/patroni
chown postgres:postgres /var/lib/patroni
cat > /etc/patroni/patroni.yml <<EOF
scope: ${CLUSTER_NAME}
namespace: /service/
name: ${NODE_NAME}
restapi:
listen: ${NODE_IP}:8008
connect_address: ${NODE_IP}:8008
etcd3:
hosts:
- ${PEER_IPS[0]}:2379
- ${PEER_IPS[1]}:2379
- ${PEER_IPS[2]}:2379
bootstrap:
dcs:
ttl: 30
loop_wait: 10
retry_timeout: 10
maximum_lag_on_failover: 1048576
synchronous_mode: false
postgresql:
use_pg_rewind: true
parameters:
max_connections: 500
shared_buffers: 4GB
effective_cache_size: 12GB
wal_level: replica
max_wal_senders: 10
max_replication_slots: 10
hot_standby: 'on'
wal_keep_size: 1GB
archive_mode: 'on'
archive_command: '/bin/true'
password_encryption: scram-sha-256
log_min_duration_statement: 500
ssl: 'on'
ssl_cert_file: '/var/lib/pgsql/16/data/server.crt'
ssl_key_file: '/var/lib/pgsql/16/data/server.key'
initdb:
- encoding: UTF8
- data-checksums
- locale: en_US.UTF-8
pg_hba:
- hostssl replication replicator ${PEER_IPS[0]}/32 scram-sha-256
- hostssl replication replicator ${PEER_IPS[1]}/32 scram-sha-256
- hostssl replication replicator ${PEER_IPS[2]}/32 scram-sha-256
- hostssl all all 10.10.0.0/16 scram-sha-256
- host all all 127.0.0.1/32 scram-sha-256
users:
admin:
password: ${SUPERUSER_PASSWORD}
options:
- createrole
- createdb
postgresql:
listen: ${NODE_IP},127.0.0.1:5432
connect_address: ${NODE_IP}:5432
data_dir: /var/lib/pgsql/16/data
bin_dir: /usr/pgsql-16/bin
pgpass: /tmp/pgpass
authentication:
replication:
username: replicator
password: ${REPL_PASSWORD}
superuser:
username: postgres
password: ${SUPERUSER_PASSWORD}
parameters:
unix_socket_directories: '/var/run/postgresql'
tags:
nofailover: false
noloadbalance: false
clonefrom: false
nosync: false
EOF
chown -R postgres:postgres /etc/patroni
chmod 600 /etc/patroni/patroni.yml
mkdir -p /var/lib/pgsql/16/data
chown -R postgres:postgres /var/lib/pgsql
echo "==> Patroni systemd unit"
cat > /etc/systemd/system/patroni.service <<'PATRONI'
[Unit]
Description=Patroni high-availability PostgreSQL
After=network.target etcd.service
Wants=etcd.service
[Service]
Type=simple
User=postgres
Group=postgres
ExecStart=/usr/local/bin/patroni /etc/patroni/patroni.yml
Restart=on-failure
LimitNOFILE=200000
TimeoutStopSec=60
KillMode=process
[Install]
WantedBy=multi-user.target
PATRONI
systemctl daemon-reload
systemctl enable --now patroni
echo "==> Installing HAProxy"
dnf -y install haproxy
cat > /etc/haproxy/haproxy.cfg <<EOF
global
maxconn 4096
log /dev/log local0
stats socket /run/haproxy/admin.sock mode 660 level admin
defaults
log global
mode tcp
retries 2
timeout client 30m
timeout connect 4s
timeout server 30m
timeout check 5s
frontend stats
bind ${NODE_IP}:7000
mode http
stats enable
stats uri /
frontend postgres_write
bind ${NODE_IP}:5000
default_backend postgres_write_bk
backend postgres_write_bk
option httpchk OPTIONS /master
http-check expect status 200
default-server inter 3s fall 3 rise 2 on-marked-down shutdown-sessions
server ${PEER_NAMES[0]} ${PEER_IPS[0]}:5432 maxconn 500 check port 8008
server ${PEER_NAMES[1]} ${PEER_IPS[1]}:5432 maxconn 500 check port 8008
server ${PEER_NAMES[2]} ${PEER_IPS[2]}:5432 maxconn 500 check port 8008
frontend postgres_read
bind ${NODE_IP}:5001
default_backend postgres_read_bk
backend postgres_read_bk
balance roundrobin
option httpchk OPTIONS /replica
http-check expect status 200
default-server inter 3s fall 3 rise 2
server ${PEER_NAMES[0]} ${PEER_IPS[0]}:5432 maxconn 500 check port 8008
server ${PEER_NAMES[1]} ${PEER_IPS[1]}:5432 maxconn 500 check port 8008
server ${PEER_NAMES[2]} ${PEER_IPS[2]}:5432 maxconn 500 check port 8008
EOF
mkdir -p /run/haproxy
systemctl enable --now haproxy
echo "==> Installing pgBouncer"
dnf -y install pgbouncer
cat > /etc/pgbouncer/pgbouncer.ini <<EOF
[databases]
* = host=${NODE_IP} port=5000
[pgbouncer]
listen_addr = ${NODE_IP}
listen_port = 6432
auth_type = scram-sha-256
auth_file = /etc/pgbouncer/userlist.txt
pool_mode = transaction
max_client_conn = 4000
default_pool_size = 50
reserve_pool_size = 10
server_lifetime = 3600
server_idle_timeout = 600
admin_users = pgbouncer_admin
EOF
cat > /etc/pgbouncer/userlist.txt <<EOF
"app" "SCRAM-SHA-256\$..."
"pgbouncer_admin" "${PGBOUNCER_PASSWORD}"
EOF
chown pgbouncer:pgbouncer /etc/pgbouncer/userlist.txt
chmod 600 /etc/pgbouncer/userlist.txt
systemctl enable --now pgbouncer
echo "==> Waiting for Patroni REST API"
for i in {1..60}; do
if curl -fs "http://${NODE_IP}:8008/health" >/dev/null 2>&1; then break; fi
sleep 2
done
echo
echo "========================================"
echo "DONE"
echo "========================================"
echo
echo "Listeners:"
ss -lntp | grep -E ':(2379|2380|5000|5001|5432|6432|7000|8008)\b' || true
echo
echo "Patroni cluster:"
patronictl -c /etc/patroni/patroni.yml list || true
echo
echo "etcd members:"
etcdctl --endpoints=http://${NODE_IP}:2379 member list || true
echo
echo "Connect via pgBouncer:"
echo "psql 'host=${NODE_IP} port=6432 dbname=app user=app'"
echo
echo "Repeat on the other 2 nodes with their NODE_NAME / NODE_IP."
Make it executable and run on each node in order:
chmod 700 /root/setup-patroni-node.sh
/root/setup-patroni-node.sh
Once all three are up, run patronictl -c /etc/patroni/patroni.yml list from any node — you should see one leader and two replicas on the same timeline. Do a failover drill before production traffic: patronictl -c /etc/patroni/patroni.yml switchover and confirm HAProxy moves the write backend within a couple of seconds. Add a logical pg_dump --custom job to object storage as a second backup layer; WAL archiving plus snapshots covers most cases, but a logical dump is what saves you from a DROP TABLE that replicates.
For an HA Postgres tier you don’t have to operate yourself, our Cloud PaaS team runs it under Managed Cloud Ops with replication-lag alerting in our monitoring plane — start a scoping call.