Skip to content

Deploying PostgreSQL streaming replication with manual failover on Ubuntu 22.04

Stand up a primary + two standbys on Ubuntu 22.04 with WAL streaming and a documented manual promotion runbook — the lean alternative to Patroni when you don't want a consensus store.

You don’t want Patroni. You don’t want etcd. You have three Ubuntu 22.04 VMs in the same private network, a sysadmin who’s on rotation, and a clear policy that failover is a human-in-the-loop decision because the application can tolerate fifteen minutes of read-only mode during an incident — what it cannot tolerate is a split-brain caused by a flaky DCS at 3 a.m. This article gives you streaming replication with two warm standbys, a documented promotion runbook, replication slots so a slow replica doesn’t fall off the WAL stream, and pg_rewind ready on every node so reintegration after a promotion is a single command instead of a pg_basebackup rebuild.

What’s happening

PostgreSQL streaming replication ships WAL records from a primary to one or more standbys over a long-lived TCP connection authenticated as a replication-role user. The standby applies the records in order and stays a few hundred milliseconds behind. With physical replication slots, the primary refuses to recycle WAL segments that a registered standby hasn’t yet consumed — which prevents the classic “replica lagged for ten minutes, missed a checkpoint, now it can’t catch up without a full rebuild” failure. With pg_rewind, a former primary that has been demoted (because you promoted a standby) can rejoin as a new standby without copying the full data directory — pg_rewind walks the WAL of the new primary and only rewrites pages that diverged.

The piece you don’t get for free with this topology is automatic failover. There is no consensus store voting. Promotion is a deliberate action: a human runs pg_ctl promote (or SELECT pg_promote()) on a chosen standby after confirming the primary is genuinely dead and the standby is sufficiently caught up. The application’s connection string then has to be repointed — either by updating a service-discovery DNS record, by editing the floating IP on a load balancer, or by reconfiguring pgBouncer to point at the new primary. This is the trade-off: you accept a longer time-to-recovery (minutes, not seconds) in exchange for never being woken up by a false failover.

The most important detail nobody documents: every node ships with pg_rewind configured and wal_log_hints = on enabled from day one. If you forget wal_log_hints on the original primary, the first time you try to rewind it back into the cluster after a failover, pg_rewind will refuse and you’ll end up doing a full pg_basebackup — which on a multi-terabyte database means hours of catch-up.

How to verify

From the primary, confirm both standbys are connected and not lagging:

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;

All four *_lag columns should be in the kilobytes range under normal write load. From a standby, confirm it’s in recovery and tracking:

SELECT pg_is_in_recovery(), pg_last_wal_receive_lsn(), pg_last_wal_replay_lsn();

Replication slots from the primary — slot restart_lsn should be moving:

SELECT slot_name, active, restart_lsn,
       pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn) AS retained_bytes
FROM pg_replication_slots;

If retained_bytes grows without bound, a standby is offline and the primary is hoarding WAL on its behalf — you’ll fill the disk. Drop the slot if the standby is permanently gone, then rebuild it when the standby returns.

The fix

Save the installer below as /root/setup-streaming-node.sh and run it on each of the three Ubuntu 22.04 nodes after editing the variables at the top. It installs PostgreSQL 16 from the PGDG repo, configures replication credentials, sets wal_log_hints and hot_standby_feedback, opens pg_hba.conf only for the private subnet, sets up replication slots on the primary, runs pg_basebackup on the standbys, and writes a documented promotion runbook to /root/RUNBOOK-promote.md on every node so whoever wakes up at 3 a.m. doesn’t have to invent it.

#!/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"

Run order: primary first (ROLE=primary), then each standby with ROLE=standby and the right NODE_NAME. After all three are up, confirm pg_stat_replication on the primary shows two streaming entries with state = streaming and sync_state = async. Do a promotion drill before production traffic: pick pg-standby1, simulate primary failure by systemctl stop postgresql@16-main on it, follow the runbook on pg-standby2, then pg_rewind the old primary back in. Time the whole drill — if it takes longer than the agreed RTO, either tighten the runbook or move to an automatic-failover topology.

If you’d rather not be the human in the runbook, Managed Cloud Ops covers the on-call, the drill cadence, and the documented procedure — pair it with our cloud compute tier and open a scoping call for the design review.