Vous ne voulez pas de Patroni. Vous ne voulez pas d’etcd. Vous avez trois VM Ubuntu 22.04 dans le même réseau privé, un sysadmin en astreinte et une politique claire : la bascule est une décision humaine, parce que l’application supporte quinze minutes en lecture seule pendant un incident — ce qu’elle ne supporte pas, c’est un split-brain causé par un DCS instable à 3 h du matin. Cet article vous donne la réplication par streaming avec deux standbys chauds, un runbook de promotion documenté, des replication slots pour qu’un réplica lent ne décroche pas du flux WAL, et pg_rewind prêt sur chaque nœud pour que la réintégration après promotion soit une commande au lieu d’un pg_basebackup complet.
Ce qui se passe
La réplication par streaming PostgreSQL achemine les enregistrements WAL d’un primaire vers un ou plusieurs standbys via une connexion TCP persistante authentifiée comme utilisateur du rôle replication. Le standby applique les enregistrements dans l’ordre et reste quelques centaines de millisecondes en arrière. Avec les replication slots physiques, le primaire refuse de recycler les segments WAL qu’un standby enregistré n’a pas encore consommés — ce qui prévient l’échec classique « réplica en retard de dix minutes, raté un checkpoint, ne peut plus rattraper sans reconstruction complète ». Avec pg_rewind, un ancien primaire qui a été rétrogradé (parce que vous avez promu un standby) peut rejoindre comme nouveau standby sans copier l’intégralité du data directory — pg_rewind parcourt le WAL du nouveau primaire et ne réécrit que les pages qui ont divergé.
Ce que vous n’obtenez pas gratuitement avec cette topologie, c’est la bascule automatique. Pas de vote de consensus. La promotion est une action délibérée : un humain lance pg_ctl promote (ou SELECT pg_promote()) sur un standby choisi, après avoir confirmé que le primaire est réellement mort et que le standby est suffisamment à jour. La chaîne de connexion de l’application doit alors être redirigée — soit en mettant à jour un enregistrement DNS de service-discovery, soit en éditant l’IP flottante sur un load balancer, soit en reconfigurant pgBouncer pour pointer sur le nouveau primaire. C’est le compromis : vous acceptez un délai de récupération plus long (minutes, pas secondes) en échange de ne jamais être réveillé par une fausse bascule.
Le détail le plus important que personne ne documente : chaque nœud part avec pg_rewind configuré et wal_log_hints = on activé dès le premier jour. Si vous oubliez wal_log_hints sur le primaire d’origine, la première fois que vous tenterez de le ramener dans la grappe après une bascule, pg_rewind refusera et vous finirez par faire un pg_basebackup complet — ce qui sur une base de plusieurs téra-octets signifie des heures de rattrapage.
Comment vérifier
Depuis le primaire, confirmez que les deux standbys sont connectés et ne traînent pas :
SELECT application_name, state, sync_state,
pg_wal_lsn_diff(pg_current_wal_lsn(), sent_lsn) AS sent_lag,
pg_wal_lsn_diff(pg_current_wal_lsn(), write_lsn) AS write_lag,
pg_wal_lsn_diff(pg_current_wal_lsn(), flush_lsn) AS flush_lag,
pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS replay_lag
FROM pg_stat_replication;
Les quatre colonnes *_lag doivent rester dans l’ordre des kilo-octets en charge d’écriture normale. Depuis un standby, confirmez qu’il est en recovery et qu’il suit :
SELECT pg_is_in_recovery(), pg_last_wal_receive_lsn(), pg_last_wal_replay_lsn();
Replication slots depuis le primaire — le restart_lsn doit avancer :
SELECT slot_name, active, restart_lsn,
pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn) AS retained_bytes
FROM pg_replication_slots;
Si retained_bytes croît sans limite, un standby est hors ligne et le primaire accumule du WAL pour lui — vous allez remplir le disque. Supprimez le slot si le standby est définitivement perdu, puis recréez-le quand le standby revient.
Le correctif
Enregistrez l’installeur ci-dessous sous /root/setup-streaming-node.sh et lancez-le sur chacun des trois nœuds Ubuntu 22.04 après avoir édité les variables en tête. Il installe PostgreSQL 16 depuis le dépôt PGDG, configure les identifiants de réplication, active wal_log_hints et hot_standby_feedback, ouvre pg_hba.conf uniquement pour le sous-réseau privé, crée les replication slots sur le primaire, lance pg_basebackup sur les standbys, et écrit un runbook de promotion documenté dans /root/RUNBOOK-promote.md sur chaque nœud pour que celui qui se réveille à 3 h du matin n’ait pas à l’inventer.
#!/usr/bin/env bash
set -euo pipefail
### Ubuntu 22.04 PostgreSQL 16 streaming replication installer
### Roles: pg-primary | pg-standby1 | pg-standby2
### Edit ROLE, NODE_NAME, NODE_IP, PEER_IPS and re-run on each node
if [[ "$(id -u)" -ne 0 ]]; then
echo "Run as root."
exit 1
fi
# === EDIT PER NODE ===
ROLE="primary" # primary | standby
NODE_NAME="pg-primary" # pg-primary / pg-standby1 / pg-standby2
NODE_IP="10.20.0.11" # this node's private IP
PRIMARY_IP="10.20.0.11" # IP of the (current) primary
PEER_IPS=("10.20.0.11" "10.20.0.12" "10.20.0.13")
PRIVATE_SUBNET="10.20.0.0/16"
CLUSTER_NAME="pgcluster"
REPL_USER="replicator"
REPL_PASSWORD="CHANGE_ME_REPL"
SUPERUSER_PASSWORD="CHANGE_ME_SUPER"
APP_DB="app"
APP_USER="app"
APP_PASSWORD="CHANGE_ME_APP"
# =====================
echo
echo "========================================"
echo "PostgreSQL streaming node ${NODE_NAME} (${ROLE})"
echo "========================================"
echo
echo "==> Base OS update"
export DEBIAN_FRONTEND=noninteractive
apt-get update -y
apt-get upgrade -y
apt-get install -y curl ca-certificates gnupg lsb-release \
ufw fail2ban unattended-upgrades chrony \
jq lsof tcpdump dnsutils net-tools
systemctl enable --now chrony
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 ssh
echo "==> Configuring unattended-upgrades for security only"
cat > /etc/apt/apt.conf.d/51unattended-upgrades-tighten <<'AUTO'
Unattended-Upgrade::Automatic-Reboot "false";
Unattended-Upgrade::Allowed-Origins {
"${distro_id}:${distro_codename}-security";
};
AUTO
systemctl enable --now unattended-upgrades
echo "==> Kernel/sysctl tuning"
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
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
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 "==> fail2ban for SSH"
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
echo "==> Adding PGDG repo + PostgreSQL 16"
install -d -m 0755 /etc/apt/keyrings
curl -fsSL https://www.postgresql.org/media/keys/ACCC4CF8.asc \
| gpg --dearmor -o /etc/apt/keyrings/postgresql.gpg
echo "deb [signed-by=/etc/apt/keyrings/postgresql.gpg] http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" \
> /etc/apt/sources.list.d/pgdg.list
apt-get update -y
apt-get install -y postgresql-16 postgresql-contrib-16 postgresql-client-16
systemctl stop postgresql@16-main
PGDATA="/var/lib/postgresql/16/main"
PGCONF="/etc/postgresql/16/main/postgresql.conf"
PGHBA="/etc/postgresql/16/main/pg_hba.conf"
echo "==> postgresql.conf (common to primary + standby)"
cat >> "${PGCONF}" <<EOF
# === streaming replication tuning ===
listen_addresses = '${NODE_IP},127.0.0.1'
port = 5432
max_connections = 500
shared_buffers = 4GB
effective_cache_size = 12GB
work_mem = 16MB
maintenance_work_mem = 512MB
wal_level = replica
wal_log_hints = on
max_wal_senders = 10
max_replication_slots = 10
wal_keep_size = 2GB
hot_standby = on
hot_standby_feedback = on
synchronous_commit = on
password_encryption = scram-sha-256
log_min_duration_statement = 500
log_line_prefix = '%m [%p] %q%u@%d '
log_checkpoints = on
log_lock_waits = on
log_temp_files = 0
log_autovacuum_min_duration = 1000
checkpoint_timeout = 15min
max_wal_size = 4GB
min_wal_size = 1GB
EOF
echo "==> pg_hba.conf — local + replication + app subnet"
cat > "${PGHBA}" <<EOF
local all postgres peer
local all all scram-sha-256
host all all 127.0.0.1/32 scram-sha-256
host all all ::1/128 scram-sha-256
host all ${APP_USER} ${PRIVATE_SUBNET} scram-sha-256
host replication ${REPL_USER} ${PRIVATE_SUBNET} scram-sha-256
EOF
chown postgres:postgres "${PGHBA}"
chmod 640 "${PGHBA}"
if [[ "${ROLE}" == "primary" ]]; then
echo "==> Bootstrapping primary"
systemctl start postgresql@16-main
sleep 5
sudo -u postgres psql -v ON_ERROR_STOP=1 <<SQL
ALTER USER postgres WITH PASSWORD '${SUPERUSER_PASSWORD}';
CREATE ROLE ${REPL_USER} WITH REPLICATION LOGIN PASSWORD '${REPL_PASSWORD}';
CREATE DATABASE ${APP_DB};
CREATE ROLE ${APP_USER} WITH LOGIN PASSWORD '${APP_PASSWORD}';
GRANT ALL ON DATABASE ${APP_DB} TO ${APP_USER};
SELECT pg_create_physical_replication_slot('standby1_slot');
SELECT pg_create_physical_replication_slot('standby2_slot');
SQL
echo "==> Primary up. Replication slots created. Provision standbys next."
elif [[ "${ROLE}" == "standby" ]]; then
echo "==> Provisioning standby via pg_basebackup from ${PRIMARY_IP}"
STANDBY_SLOT="standby1_slot"
if [[ "${NODE_NAME}" == *standby2* ]]; then
STANDBY_SLOT="standby2_slot"
fi
# wipe the auto-initialized PGDATA
rm -rf "${PGDATA}"/*
PGPASSWORD="${REPL_PASSWORD}" sudo -u postgres \
pg_basebackup \
-h "${PRIMARY_IP}" -p 5432 -U "${REPL_USER}" \
-D "${PGDATA}" -Fp -Xs -P -R \
--slot="${STANDBY_SLOT}"
# pg_basebackup -R writes standby.signal + primary_conninfo in postgresql.auto.conf
# Tighten primary_conninfo with explicit application_name for pg_stat_replication
sudo -u postgres bash -c "cat >> ${PGDATA}/postgresql.auto.conf" <<EOF
primary_conninfo = 'host=${PRIMARY_IP} port=5432 user=${REPL_USER} password=${REPL_PASSWORD} application_name=${NODE_NAME}'
primary_slot_name = '${STANDBY_SLOT}'
restore_command = '/bin/false'
EOF
systemctl start postgresql@16-main
echo "==> Standby started, catching up"
else
echo "Unknown ROLE=${ROLE}" ; exit 2
fi
echo "==> Writing /root/RUNBOOK-promote.md"
cat > /root/RUNBOOK-promote.md <<'RUNBOOK'
# Manual failover runbook (streaming replication)
## When to promote
- Primary is genuinely dead (VM gone, OS unresponsive, disk failure).
- Primary is reachable but unfencable (split-brain risk): isolate it first
via security group / firewall before promoting any standby.
## Pre-flight on the chosen standby
1. Confirm replay is current (within seconds, ideally zero lag):
sudo -u postgres psql -c "SELECT pg_last_wal_receive_lsn(), pg_last_wal_replay_lsn();"
2. Confirm primary is fenced (cannot accept writes). Verify by trying a write
from the application network — it must fail.
## Promote
sudo -u postgres pg_ctlcluster 16 main promote
# Or:
sudo -u postgres psql -c "SELECT pg_promote(true, 60);"
## Repoint the application
- Update DNS / floating IP / pgBouncer config to point at the new primary.
- Verify writes succeed:
psql "host=<new-primary> dbname=app user=app" -c "INSERT INTO _healthz DEFAULT VALUES RETURNING now();"
## Rejoin the old primary as a standby
On the old primary (after it is recovered and reachable):
1. Stop postgres if running:
systemctl stop postgresql@16-main
2. Run pg_rewind (requires wal_log_hints=on, which we set):
sudo -u postgres /usr/lib/postgresql/16/bin/pg_rewind \
--target-pgdata=/var/lib/postgresql/16/main \
--source-server="host=<new-primary> port=5432 user=replicator dbname=postgres"
3. Recreate standby signal + primary_conninfo for the new primary.
4. Drop the old slot on the new primary if it's stale, create a fresh one.
5. Start the service. Verify it appears in pg_stat_replication on the new primary.
## Don't
- Don't promote two standbys.
- Don't skip fencing the old primary.
- Don't forget to recreate the replication slot — without it the new primary
will recycle WAL the rejoining node hasn't consumed.
RUNBOOK
chmod 600 /root/RUNBOOK-promote.md
echo "==> ufw"
ufw --force reset
ufw default deny incoming
ufw default allow outgoing
ufw allow 22/tcp
ufw allow from ${PRIVATE_SUBNET} to any port 5432 proto tcp
ufw --force enable
echo
echo "========================================"
echo "DONE — ${NODE_NAME} (${ROLE})"
echo "========================================"
echo
echo "Listeners:"
ss -lntp | grep -E ':(5432)\b' || true
echo
echo "Service status:"
systemctl is-active postgresql@16-main
echo
if [[ "${ROLE}" == "primary" ]]; then
echo "Replication slots (re-check after standbys come up):"
sudo -u postgres psql -c "SELECT slot_name, active, restart_lsn FROM pg_replication_slots;"
fi
echo
echo "Runbook: /root/RUNBOOK-promote.md"
Ordre d’exécution : primaire d’abord (ROLE=primary), puis chaque standby avec ROLE=standby et le bon NODE_NAME. Une fois les trois nœuds montés, confirmez sur le primaire que pg_stat_replication affiche deux entrées streaming avec state = streaming et sync_state = async. Faites un exercice de promotion avant le trafic de production : choisissez pg-standby1, simulez la panne primaire avec systemctl stop postgresql@16-main, suivez le runbook sur pg-standby2, puis ramenez l’ancien primaire avec pg_rewind. Chronométrez l’exercice — s’il dépasse le RTO convenu, soit on resserre le runbook, soit on passe à une topologie de bascule automatique.
Si vous préférez ne pas être l’humain dans le runbook, Environnements infogérés (Environnements infogérés) couvre l’astreinte, la cadence des exercices et la procédure documentée — appairez avec notre tier Cloud Compute et planifiez un appel de cadrage pour la revue de design.