Log inSign up

Build a hot standby with PostgreSQL streaming replication

Install the same PostgreSQL major version on two servers, turn on TLS on the primary, create a role with the REPLICATION attribute, and allow only the standby IP in both pg_hba.conf (as a hostssl line) and the firewall. Then clone the primary with pg_basebackup -R -C -S standby1 on the second server; it starts as a read-only hot standby that streams every change, and SELECT pg_promote(); turns it into the new primary when needed.

Topic: Databases · Tested on: Ubuntu 24.04 and 22.04, Debian 12 and 13, Rocky Linux 9, AlmaLinux 9 · Updated 2026-12-03

What does this setup look like?

Two servers, each with its own public IPv4 address, run the same PostgreSQL major version. The primary accepts writes and ships its write-ahead log (WAL) to the standby over one encrypted connection on port 5432. The standby replays that log continuously and can answer read-only queries.

In this guide the primary is db1.example.net at 198.51.100.24 and the standby is db2.example.net at 198.51.100.25. There is no private network between servers, so replication traffic crosses the internet. That is fine with three rules: encrypt with TLS, accept the replication role only from the peer address, and block port 5432 for everyone else at the firewall. Create DNS A records for both names first (the DNS records tutorial shows how), because certificate checks use the hostname.

Placing the two servers in different cities gives you protection against a site-wide problem, at the cost of some network latency on the stream.

How do you install the same version on both servers?

Use the PostgreSQL project repository so both machines run an identical major version, here 17. Streaming replication requires the same major version on both ends.

Ubuntu and Debian

sudo apt update
sudo apt install -y postgresql-common
sudo /usr/share/postgresql-common/pgdg/apt.postgresql.org.sh
sudo apt install -y postgresql-17
psql --version
sudo systemctl status postgresql@17-main --no-pager

Rocky Linux 9 and AlmaLinux 9

sudo dnf install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-9-x86_64/pgdg-redhat-repo-latest.noarch.rpm
sudo dnf -qy module disable postgresql
sudo dnf install -y postgresql17-server
sudo /usr/pgsql-17/bin/postgresql-17-setup initdb
sudo systemctl enable --now postgresql-17

Config files live in /etc/postgresql/17/main/ on Debian family systems and inside the data directory /var/lib/pgsql/17/data/ on Rocky and Alma. Data directories are /var/lib/postgresql/17/main and /var/lib/pgsql/17/data. The PostgreSQL install guide covers the basics in more depth.

How do you enable TLS on the primary?

Give the primary a certificate whose name matches db1.example.net, point PostgreSQL at it, and switch ssl on. A self-signed certificate works because the standby will trust that exact certificate.

sudo mkdir -p /etc/postgresql/17/main/tls
cd /etc/postgresql/17/main/tls
sudo openssl req -x509 -newkey rsa:3072 -nodes -days 1825 -keyout server.key -out server.crt -subj "/CN=db1.example.net" -addext "subjectAltName=DNS:db1.example.net"
sudo chown postgres:postgres server.key server.crt
sudo chmod 600 server.key

On Rocky and Alma, put the files in a tls folder inside /var/lib/pgsql/17/data/ instead. If you already have a Let's Encrypt certificate for the name, you can use it; the Certbot guide explains how to obtain one. Now edit postgresql.conf on the primary:

listen_addresses = 'localhost,198.51.100.24'
ssl = on
ssl_cert_file = '/etc/postgresql/17/main/tls/server.crt'
ssl_key_file = '/etc/postgresql/17/main/tls/server.key'
ssl_min_protocol_version = 'TLSv1.2'
wal_level = replica
max_wal_senders = 10
max_replication_slots = 10
wal_keep_size = '1GB'

The last four values are already close to the defaults in recent releases, but stating them makes the intent clear to the next person who reads the file.

How do you create the replication role and access rule?

Create a role that can only replicate, set a strong password, and allow it from the standby address over TLS only.

sudo -u postgres psql -c "CREATE ROLE replicator WITH REPLICATION LOGIN;"
sudo -u postgres psql -c "\password replicator"

Then add one line near the top of pg_hba.conf:

# TYPE   DATABASE     USER        ADDRESS            METHOD
hostssl  replication  replicator  198.51.100.25/32   scram-sha-256

The hostssl type refuses plain connections, and the /32 mask admits a single address. Restart and confirm the server listens on the public address:

sudo systemctl restart postgresql@17-main      # postgresql-17 on Rocky/Alma
sudo ss -tlnp | grep 5432

The PostgreSQL roles guide explains attributes such as REPLICATION in more detail.

Which firewall rules allow only the peer?

Open port 5432 to the standby address and to nothing else. Do the same on the standby for the primary address, so traffic can flow the other way after a failover.

Ubuntu and Debian (ufw)

sudo ufw allow from 198.51.100.25 to any port 5432 proto tcp comment 'pg standby'
sudo ufw status numbered

Rocky Linux and AlmaLinux (firewalld)

sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="198.51.100.25/32" port port="5432" protocol="tcp" accept'
sudo firewall-cmd --reload
sudo firewall-cmd --list-rich-rules

Never add a plain allow 5432 rule. From a third machine, nc -vz 198.51.100.24 5432 should time out, while the same command run on the standby connects. The ufw guide and firewalld guide cover the tools in general.

How do you clone the primary onto the standby?

Stop PostgreSQL on the standby, empty its data directory, and run pg_basebackup as the postgres user with a connection string that demands full certificate verification.

sudo systemctl stop postgresql@17-main
sudo -u postgres mkdir -p /var/lib/postgresql/.postgresql
# copy server.crt from the primary into this file
sudo -u postgres nano /var/lib/postgresql/.postgresql/root.crt
sudo -u postgres chmod 600 /var/lib/postgresql/.postgresql/root.crt
sudo -u postgres bash -c "rm -rf /var/lib/postgresql/17/main/*"
sudo -u postgres pg_basebackup -d "host=db1.example.net user=replicator sslmode=verify-full" -D /var/lib/postgresql/17/main -X stream -R -C -S standby1 -P
sudo systemctl start postgresql@17-main

On Rocky and Alma the postgres home is /var/lib/pgsql, the data directory is /var/lib/pgsql/17/data and the service is postgresql-17. Put the password in ~postgres/.pgpass (mode 600) as db1.example.net:5432:replication:replicator:PASSWORD so the standby can reconnect on its own after restarts.

The -R flag writes standby.signal and a primary_conninfo line into postgresql.auto.conf. The -C -S standby1 pair creates a replication slot on the primary, so it keeps the WAL the standby still needs even if the link drops for a while.

How do you check that replication works?

Query the statistics views on both sides, then write a row on the primary and read it on the standby.

# on the primary
sudo -u postgres psql -c "SELECT client_addr, state, ssl, sync_state, replay_lag FROM pg_stat_replication JOIN pg_stat_ssl USING (pid);"
sudo -u postgres psql -c "SELECT slot_name, active, wal_status FROM pg_replication_slots;"
# on the standby
sudo -u postgres psql -c "SELECT pg_is_in_recovery();"
sudo -u postgres psql -c "SELECT status, sender_host FROM pg_stat_wal_receiver;"

You want state = streaming, ssl = t, and true from pg_is_in_recovery(). A test table created on the primary should appear on the standby within a second or so, and an INSERT on the standby must fail with a read-only error.

Watch the slot: a standby that stays offline makes the primary keep WAL indefinitely. Setting max_slot_wal_keep_size = '20GB' on the primary caps that growth, and the monitoring guides help you alert on free disk space.

How do you fail over, and what about automatic failover?

For a planned or manual failover, stop writes on the old primary if it is still alive, then promote the standby. It leaves recovery and accepts writes at once.

sudo -u postgres psql -c "SELECT pg_promote();"
sudo -u postgres psql -c "SELECT pg_is_in_recovery();"   # now false

Point the application at db2.example.net (or move the DNS record), and rebuild the old primary as a new standby with pg_basebackup or pg_rewind. Never let both servers accept writes at the same time.

Manual promotion is enough for many small setups. When you need automatic failover, look at Patroni: it runs beside PostgreSQL on each node, stores the cluster state in a consensus store such as etcd (three members, so usually a third small server), promotes a standby when the leader disappears, and exposes a REST health check. HAProxy then reads those health checks and sends client connections to whichever node is the current leader. Apply the same rules there: TLS between every component and firewall rules listing each peer address.

Plans that fit this guide

Base city prices. Every plan includes a dedicated IPv4 address, IPv6, full root and all 18 images.

All prices
PlanFits becauseSizeMonthlyOrder from
A2-4primary and standby for a small app2 vCPU, 4 GB RAM, 100 GB NVMe$14.40/mo$43.20 for 3 months
A4-8larger working sets in RAM4 vCPU, 8 GB RAM, 180 GB NVMe$28.80/mo$86.40 for 3 months

Questions about PostgreSQL streaming replication

Can the two servers run different PostgreSQL versions?

Not for streaming replication. Both need the same major version (minor versions may differ briefly during updates). For version upgrades across servers use logical replication or pg_upgrade.

Is the replication stream encrypted?

Only if you make it so. With hostssl in pg_hba.conf and sslmode=verify-full on the standby, the stream is encrypted and the standby verifies it is talking to the real primary.

Is a standby a backup?

No. A dropped table is dropped on the standby a moment later. Keep separate backups; the backup and restore guide shows how.

Should I use synchronous replication?

Set synchronous_standby_names only if losing the last few transactions on a crash is unacceptable. Each commit then waits for the standby, which over a long distance adds noticeable latency.

Can my application read from the standby?

Yes, hot standby is on by default, so read-only queries work. Results can lag the primary slightly, so send reads that must see the latest write to the primary.