High Availability

PostgreSQL Streaming Replication Setup: Complete Guide for PG15+

Set up PostgreSQL streaming replication from scratch. Covers primary configuration, standby base backup, replication monitoring, and manual failover promotion.

JusDB Team
February 10, 2025
5 min read
172 views

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

text
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

ini
# postgresql.conf on primary
wal_level = replica
max_wal_senders = 5
wal_keep_size = 512MB
listen_addresses = '*'
hot_standby = on

Primary: Create Replication User

sql
CREATE ROLE replicator WITH REPLICATION LOGIN PASSWORD 'repl_pass';

Primary: pg_hba.conf

text
# 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-256

Standby: Take Base Backup

bash
# 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_conninfo

Standby: postgresql.conf

ini
hot_standby = on
primary_conninfo = 'host=192.168.1.10 port=5432 user=replicator password=repl_pass'

Verify Replication

sql
-- 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;
Tip: Use 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)

bash
# 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 = replica and max_wal_senders >= 3 on the primary
  • Use pg_basebackup -R to auto-generate standby.signal
  • Monitor pg_stat_replication for 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.

Share this article

JusDB Team

Official JusDB content team