PostgreSQL streaming replication lets a standby server stay continuously in sync with the primary by streaming WAL records in real time. This guide covers a complete setup for PostgreSQL 15+.
Architecture
Primary (192.168.1.10)
└─ WAL stream ──► Standby (192.168.1.11)
└─ WAL stream ──► Standby2 (192.168.1.12) [optional cascade]Primary: Configure postgresql.conf
# postgresql.conf on primary
wal_level = replica
max_wal_senders = 5
wal_keep_size = 512MB
listen_addresses = '*'
hot_standby = onPrimary: Create Replication User
CREATE ROLE replicator WITH REPLICATION LOGIN PASSWORD 'repl_pass';Primary: pg_hba.conf
# TYPE DATABASE USER ADDRESS METHOD
host replication replicator 192.168.1.11/32 scram-sha-256
host replication replicator 192.168.1.12/32 scram-sha-256Standby: Take Base Backup
# Run on standby server
pg_basebackup -h 192.168.1.10 -U replicator -D /var/lib/postgresql/15/main \
-P -Xs -R --checkpoint=fast
# -R automatically creates standby.signal and sets primary_conninfoStandby: postgresql.conf
hot_standby = on
primary_conninfo = 'host=192.168.1.10 port=5432 user=replicator password=repl_pass'Verify Replication
-- On primary
SELECT client_addr, state, sent_lsn, write_lsn, flush_lsn, replay_lsn,
write_lag, flush_lag, replay_lag
FROM pg_stat_replication;
-- On standby
SELECT status, received_lsn, latest_end_lsn,
now() - latest_end_time AS replication_lag
FROM pg_stat_wal_receiver;pg_replication_slots if you cannot guarantee the standby will reconnect quickly. Slots prevent WAL from being recycled before the standby consumes it.Promotion (Failover)
# Promote standby to primary
pg_ctl promote -D /var/lib/postgresql/15/main
# Or via SQL (PostgreSQL 12+)
SELECT pg_promote();Key Takeaways
- Set
wal_level = replicaandmax_wal_senders >= 3on the primary - Use
pg_basebackup -Rto auto-generatestandby.signal - Monitor
pg_stat_replicationfor lag and state - Replication slots prevent WAL loss but can fill disk if standby disconnects
JusDB Can Help
Streaming replication is the foundation of PostgreSQL HA. JusDB can design and validate your replication topology, including failover automation with Patroni. Get in touch.