Complete Guide to PostgreSQL Replication
Set up and operate PostgreSQL replication in production: streaming and logical replication, synchronous commit, Patroni failover, and lag monitoring.
Introduction
A single PostgreSQL server is a single point of failure. When it goes down, your application goes with it, and restoring from a backup can take hours. Replication solves two problems at once: high availability (a replica can be promoted in seconds) and read scaling (replicas serve queries the primary doesn’t have to).
PostgreSQL has two native mechanisms. Streaming replication ships raw WAL records and produces byte-for-byte replicas — the right tool for HA and read scaling. Logical replication decodes WAL into row-level changes and publishes them to subscribers — the right tool for selective replication, cross-version upgrades, and feeding other systems. This guide covers both, plus cascading topologies, synchronous commit, automatic failover with Patroni, lag monitoring, replication slots, and disaster recovery. The examples target PostgreSQL 16+, and the conceptual foundation lives in Database Replication — Primary-Replica, Multi-Primary if you need it first.
When to Use
Use streaming replication when:
- You need automatic or manual failover for high availability.
- You want to offload read traffic to replicas without changing application logic.
- You’re building a disaster-recovery copy in another region.
Use logical replication when:
- You’re upgrading major versions and want near-zero downtime (replicate from 16 to 17, then switch).
- You need only a subset of tables in another database or region.
- You’re feeding a data warehouse, a search index, or a different PostgreSQL schema.
When replication is the wrong tool: replication isn’t a backup. It propagates everything, including your DROP TABLE. Keep point-in-time backups (pgBackRest, WAL-G, or pg_basebackup + archive) regardless of how many replicas you run. If you only need read scaling and can tolerate data rebuild, managed read replicas or connection pooling may be simpler.
Prerequisites
Before touching configuration:
- All nodes run the same PostgreSQL major version (for streaming replication).
- Network connectivity on port 5432 between primary and replicas, plus whatever port your DCS needs (etcd uses 2379).
- Enough disk on the primary for retained WAL — a replica that’s offline keeps WAL until it reconnects, and that WAL has to live somewhere.
- A replication user separate from your application users, with only the
REPLICATIONprivilege.
-- On the primary
CREATE ROLE replicator WITH REPLICATION LOGIN PASSWORD 'use_a_real_password';
Streaming Replication
Streaming replication sends WAL (Write-Ahead Log) records from the primary to replicas as they’re generated. Each replica applies the records and stays a nearly-live copy. The mechanics are documented in the PostgreSQL log-shipping standby docs.
Primary Configuration
# postgresql.conf (primary)
listen_addresses = '*' # or the specific interface replicas reach
wal_level = replica
max_wal_senders = 10 # postmaster-level: requires restart
max_replication_slots = 10 # postmaster-level: requires restart
wal_keep_size = 1024 # MB of WAL kept for replicas without slots
hot_standby = on # allow read queries on replicas
A common mistake: wal_level, max_wal_senders, max_replication_slots, and listen_addresses are postmaster-context parameters. Editing postgresql.conf and running pg_reload_conf() isn’t enough — these need systemctl restart postgresql (or pg_ctl restart). Parameters like wal_keep_size and synchronous_standby_names apply on reload.
# pg_hba.conf (primary) — scope it to the replica subnet only
host replication replicator 10.0.1.0/24 scram-sha-256
Reload after editing pg_hba.conf — it does apply on reload.
Replica Setup
# On the replica, stop PostgreSQL and empty the data directory
pg_ctl stop -D /var/lib/postgresql/16/data
rm -rf /var/lib/postgresql/16/data/*
# Take a base backup straight from the primary
pg_basebackup \
-h primary.example.com \
-U replicator \
-D /var/lib/postgresql/16/data \
-Fp -Xs -P -R
# -R writes standby.signal and stores primary_conninfo in postgresql.auto.conf
pg_ctl start -D /var/lib/postgresql/16/data
Don’t put the replication password in primary_conninfo. Use a .pgpass file in the postgres user’s home (primary.example.com:5432:replication:replicator:password, mode 0600) or environment variables, so credentials don’t leak into postgresql.auto.conf and process listings.
# postgresql.conf (replica) — only needed when NOT using pg_basebackup -R
hot_standby = on
primary_conninfo = 'host=primary.example.com port=5432 user=replicator'
primary_slot_name = 'replica1_slot' # keeps WAL on the primary for this replica
-- On the primary: create the slot the replica will use
SELECT pg_create_physical_replication_slot('replica1_slot');
Verify Replication
-- On the primary: who is connected and how far behind
SELECT
application_name,
client_addr,
state,
sync_state,
pg_wal_lsn_diff(sent_lsn, replay_lsn) AS lag_bytes
FROM pg_stat_replication;
-- On the replica
SELECT pg_is_in_recovery(); -- should return t
SELECT status, latest_end_lsn, latest_end_time FROM pg_stat_wal_receiver;
A healthy replica shows state = 'streaming' on the primary and status = 'streaming' in pg_stat_wal_receiver. If the replica sits in catchup for a long time, the initial WAL transfer is still running or it can’t keep up — check network throughput before assuming it’s broken.
Cascading Replication
When you run many replicas, each one consumes a walsender process and network bandwidth on the primary. Cascading lets a replica re-send WAL to its own downstream replicas, offloading the primary.
# On Replica 1 — it also needs sender capacity and pg_hba rules for downstream
max_wal_senders = 5
wal_keep_size = 1024
# pg_hba.conf on Replica 1:
# host replication replicator 10.0.2.0/24 scram-sha-256
# On Replica 2 — point at Replica 1 instead of the primary
primary_conninfo = 'host=replica1.example.com port=5432 user=replicator'
Cascading adds latency at each hop and makes failover chains harder to reason about. Two levels is usually the practical limit; for more replicas than that, prefer direct replicas with a well-sized max_wal_senders, or read replicas on a managed layer.
Logical Replication
Logical replication decodes WAL into logical change events (INSERT, UPDATE, DELETE) instead of shipping raw bytes. That buys you table-level granularity, replication between different major versions, and replication into differently-shaped targets — see the official logical replication chapter for the full capability matrix.
Publisher Configuration
-- wal_level must be 'logical', and it requires a restart — reload is NOT enough
ALTER SYSTEM SET wal_level = 'logical';
ALTER SYSTEM SET max_replication_slots = 10;
ALTER SYSTEM SET max_logical_replication_workers = 4;
-- then: systemctl restart postgresql
CREATE PUBLICATION my_publication FOR TABLE users, orders, products;
-- Only publish inserts (useful for append-only/event tables)
CREATE PUBLICATION insert_only FOR TABLE audit_log WITH (publish = 'insert');
-- Row filters (PostgreSQL 15+): replicate only matching rows
CREATE PUBLICATION eu_users FOR TABLE users WHERE (region = 'eu');
-- Manage membership later
ALTER PUBLICATION my_publication ADD TABLE new_table;
ALTER PUBLICATION my_publication DROP TABLE old_table;
For UPDATE and DELETE to replicate, each table needs a replica identity: a primary key by default, or ALTER TABLE t REPLICA IDENTITY FULL (slower, logs the whole row) for keyless tables.
Subscriber Configuration
-- The tables must already exist on the subscriber with a compatible schema
CREATE TABLE users (id bigint PRIMARY KEY, name text, email text);
CREATE TABLE orders (id bigint PRIMARY KEY, user_id bigint, total numeric);
CREATE SUBSCRIPTION my_subscription
CONNECTION 'host=publisher.example.com port=5432 user=replicator dbname=mydb'
PUBLICATION my_publication
WITH (
copy_data = true, -- copy existing rows first
create_slot = true,
slot_name = 'my_sub_slot',
synchronous_commit = off -- apply worker doesn't wait for local flush
);
-- After adding tables to the publication
ALTER SUBSCRIPTION my_subscription REFRESH PUBLICATION;
Watch the apply worker on the subscriber:
SELECT subname, pid, received_lsn, latest_end_lsn
FROM pg_stat_subscription;
-- On the publisher: is the subscription keeping up?
SELECT slot_name, active,
pg_wal_lsn_diff(pg_current_wal_lsn(), confirmed_flush_lsn) AS lag_bytes
FROM pg_replication_slots WHERE slot_type = 'logical';
Logical Replication Limitations
What logical replication does NOT carry over:
- DDL / schema changes — apply migrations on both sides, subscriber first
- Sequence values — resync them manually after initial copy or switchover
- Large objects (lo_* functions; plain bytea is fine)
- TEMPORARY and UNLOGGED table changes
- System catalogs
Common gotchas:
- No replica identity → UPDATE/DELETE fail with "cannot update table"
- A conflict (e.g., duplicate PK on subscriber) stops the apply worker
until you fix the row or skip the transaction
- TRUNCATE replicates as truncate of the published tables only
- Each subscription consumes a walsender + a replication slot on the publisher
Synchronous Replication
Asynchronous replication can lose the last few transactions when the primary dies. Synchronous replication makes a commit wait until a replica confirms it holds the WAL — you trade write latency for durability.
# postgresql.conf (primary) — all of these apply on reload, no restart needed
synchronous_commit = on
# Wait for one specific replica (by application_name in primary_conninfo)
synchronous_standby_names = 'replica1'
# Wait for the 2 fastest of 3
synchronous_standby_names = 'FIRST 2 (replica1, replica2, replica3)'
# Wait for any 2 of 3 (all listed replicas confirm independently)
synchronous_standby_names = 'ANY 2 (replica1, replica2, replica3)'
synchronous_commit levels, fastest → safest:
off — commit without local WAL flush; can lose recent transactions
local — local flush only; doesn't wait for any replica
on — local flush + remote replica flush (the usual choice)
remote_write — replica has written but not flushed WAL
remote_apply — replica has replayed WAL; strictest, adds most latency
The replica’s application_name must match the name in synchronous_standby_names — set it inside primary_conninfo (application_name=replica1) or it defaults to walreceiver and never matches.
Securing Replication Connections
Replication traffic carries your entire dataset. Two hardening steps matter most:
# Encrypt the replication stream — in primary_conninfo on each replica
primary_conninfo = 'host=primary.example.com port=5432 user=replicator sslmode=verify-full sslrootcert=/etc/ssl/ca.crt'
# On the primary — require SSL for replication connections only
# pg_hba.conf
hostssl replication replicator 10.0.1.0/24 scram-sha-256
hostnossl replication replicator 0.0.0.0/0 reject
Additional rules that pay off in production:
scram-sha-256overmd5— md5 password verification is weak; treat it as deprecated.- Restrict pg_hba to the exact replica subnet, never
0.0.0.0/0. - The replication user gets
REPLICATION, nothing else — noSUPERUSER, no table access it doesn’t need. - Rotate the replication password on a schedule; it lives in
.pgpasson every replica.
Failover with Patroni
Manual promotion works, but at 3 a.m. you want automation. Patroni manages leader election and failover through a distributed configuration store (etcd, Consul, or ZooKeeper). For the mechanics behind it — health checks, promotion, failback — see the Failover pattern; for the operational side — runbooks, decision trees, post-failover checks — see the Database Failover Runbook.
# /etc/patroni/patroni.yml
scope: pg_cluster
name: node1
restapi:
listen: 0.0.0.0:8008
connect_address: 10.0.1.10:8008
etcd:
hosts: 10.0.1.100:2379,10.0.1.101:2379,10.0.1.102:2379
bootstrap:
dcs:
ttl: 30
loop_wait: 10
retry_timeout: 10
maximum_lag_on_failover: 1048576 # refuse failover if replica lags >1MB
synchronous_mode: true # elect a synchronous replica only
postgresql:
use_pg_rewind: true # resync old primary without full rebase
parameters:
wal_level: replica
hot_standby: on
max_wal_senders: 10
max_replication_slots: 10
wal_keep_size: 1024
postgresql:
listen: 0.0.0.0:5432
connect_address: 10.0.1.10:5432
data_dir: /var/lib/postgresql/16/data
bin_dir: /usr/lib/postgresql/16/bin
authentication:
replication:
username: replicator
password: use_a_real_password
superuser:
username: postgres
password: super_secure_password
# Operate the cluster
patroni /etc/patroni/patroni.yml
patronictl -c /etc/patroni/patroni.yml list
# Planned primary maintenance: switchover keeps the old node as a replica
patronictl -c /etc/patroni/patroni.yml switchover pg_cluster
# Unplanned: promote the healthiest replica
patronictl -c /etc/patroni/patroni.yml failover pg_cluster
# A diverged old primary comes back — pg_rewind fixes it without re-backup
patronictl -c /etc/patroni/patroni.yml reinit pg_cluster node2
Two configuration details burn people in production: ttl and loop_wait control detection time (30s TTL means roughly 30–60s to detect and promote), and maximum_lag_on_failover protects you from promoting a stale replica — don’t set it to 0 or a node with no lag tolerance could win an election during a WAL storm.
Monitoring Replication Lag
Lag is the metric that decides whether a replica is useful. Track it in bytes and in seconds — a replica can be close in bytes but far in time during a bulk load.
-- On the primary: lag per replica
SELECT
application_name,
state,
pg_wal_lsn_diff(sent_lsn, replay_lsn) AS lag_bytes,
write_lag,
flush_lag,
replay_lag
FROM pg_stat_replication;
-- On the replica: time since last replayed transaction
SELECT EXTRACT(EPOCH FROM (now() - pg_last_xact_replay_timestamp())) AS lag_seconds,
pg_last_wal_replay_lsn();
-- Slot retention: how much WAL each slot pins on the primary
SELECT
slot_name,
slot_type,
active,
wal_status,
pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn) AS retained_bytes
FROM pg_replication_slots;
Alert on two conditions: lag_bytes above your RPO budget (say 16 MB for strict setups), and any slot sitting active = false while retained_bytes grows — that’s WAL piling up on the primary disk. Graph pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn) per slot; the curve going vertical means the replica is dead and the disk is filling.
Replication Slot Management
A slot tells the primary “don’t delete WAL this consumer hasn’t read.” It’s the difference between a replica that reconnects cleanly and one that needs a full rebuild — and also a disk-filling hazard if the consumer dies silently.
SELECT pg_create_physical_replication_slot('replica1_slot');
SELECT pg_create_logical_replication_slot('my_slot', 'pgoutput'); -- pgoutput for native logical
SELECT pg_drop_replication_slot('replica1_slot'); -- must be inactive
-- Check every slot's health
SELECT slot_name, slot_type, active, wal_status,
pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn) AS pinned_bytes
FROM pg_replication_slots;
-- Skip forward past transactions you don't want (logical only)
SELECT pg_replication_slot_advance('my_slot', '0/2000000');
wal_status meanings:
reserved — WAL needed is still within normal retention
extended — WAL is being kept beyond wal_keep_size for this slot
unreserved — some needed WAL may already be gone
lost — required WAL was removed; drop and recreate the slot
Bound the blast radius with max_slot_wal_keep_size (e.g., 8192 MB). The primary will invalidate a slot rather than let it consume the whole disk — the replica breaks, but the primary survives. Decide deliberately which failure you prefer; the default -1 means unlimited retention.
Backup and Point-in-Time Recovery
Replicas are live copies — they’re useless the moment you DELETE without a WHERE. PITR requires WAL archiving on top of replication:
# postgresql.conf (primary)
archive_mode = on # postmaster-level: restart required
archive_command = 'test ! -f /archive/%f && cp %p /archive/%f'
# better: archive_command = 'pgbackrest --stanza=main archive-push %p'
# On the recovery node (PostgreSQL 12+)
touch /var/lib/postgresql/16/data/recovery.signal
# postgresql.auto.conf or postgresql.conf — PG12+ has no recovery.conf
restore_command = 'cp /archive/%f %p'
recovery_target_time = '2026-11-05 14:30:00'
recovery_target_action = 'promote'
recovery_target_inclusive = true
recovery.conf only exists in PostgreSQL 11 and earlier; from version 12 on, the trigger is the recovery.signal file and the parameters live in postgresql.conf/postgresql.auto.conf. After the target is reached and promote fires, the server jumps to a new timeline — check it with SELECT timeline_id FROM pg_control_checkpoint();. Timelines matter when the old primary rejoins: without a rewind or rebase, two nodes on different timelines can’t stream from each other.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
Replica stuck in catchup | WAL needed was already removed, or slow link | Check pg_stat_replication; increase wal_keep_size or add a slot; worst case, re-run pg_basebackup |
wal_status = 'lost' | Replica offline past slot retention | Drop and recreate slot, rebuild the replica |
| Apply worker stopped (logical) | Conflict — duplicate PK or missing replica identity | Fix the row on subscriber, then ALTER SUBSCRIPTION ... ENABLE; or pg_replication_origin_advance to skip |
ERROR: canceling statement due to conflict with recovery | Replica query collides with WAL replay | max_standby_streaming_delay = 30s, or hot_standby_feedback = on on the replica |
| Primary disk filling fast | Dead slot pinning WAL | Find it via pg_replication_slots, drop it; set max_slot_wal_keep_size |
| Replica won’t connect at all | pg_hba missing replication line, or wrong auth | hostssl replication ... scram-sha-256 then reload |
Query conflicts deserve one more note: hot_standby_feedback = on lets the replica report its oldest transaction so the primary delays vacuum cleanup. It reduces cancels but can bloat the primary — use it when long analytical queries run on replicas and you can tolerate the bloat.
Best Practices
- Always use replication slots on production replicas. Without one, an overnight network blip becomes a morning
pg_basebackup. - Monitor lag in bytes and seconds, and alert on inactive slots before they fill the disk — set
max_slot_wal_keep_sizeas a backstop. - Encrypt replication traffic (
sslmode=verify-full+hostssl) and scope pg_hba to replica subnets only. - Rehearse failover. A Patroni cluster that’s never failed over in staging will fail creatively in production.
- Test restores, not just backups: PITR to a scratch host quarterly confirms your archive is actually usable.
- Keep
synchronous_standby_namesaligned with reality — a named replica that doesn’t exist adds commit latency to every write. - For logical replication, apply DDL on the subscriber before the publisher, or the apply worker errors on missing columns.
Common Mistakes
- Running
pg_reload_conf()after changingwal_level,max_wal_senders, ormax_replication_slotsand wondering why nothing happened — these need a restart. - Treating replication as a backup. It faithfully replicates
DROP TABLEand badUPDATEs. Keep WAL archives regardless. - Leaving a dead logical slot in place “just in case” — it pins WAL forever and eventually eats the primary’s disk.
- Forgetting replica identity on keyless logical-replication tables; INSERTs work, UPDATE/DELETE error out.
- Setting
synchronous_commit = remote_applyeverywhere for “safety” and discovering the write path got 3× slower. - Promoting a replica while the old primary is still alive — split-brain. Always fence the old node (
pg_ctl stop -m immediate, or better, Patroni handles it).
See Also
- Runnable companion — docker-compose streaming lab, Patroni template, production configs and monitoring queries
- Database Replication — Primary-Replica, Multi-Primary
- Database Failover Runbook
- Read Replicas: Scale Reads Without Changing Application
- Complete Guide to Database Sharding
- Complete Guide to Redis in Production
- Complete Guide to SQL Query Optimization
Frequently Asked Questions
What is the difference between streaming and logical replication?
Streaming replication ships raw WAL bytes and produces a byte-for-byte copy of the primary — same major version and architecture required. Logical replication decodes WAL into row changes and lets you pick tables, cross major versions, and replicate into different schemas. Streaming is for HA and read replicas; logical is for selective replication, integrations, and zero-downtime major upgrades.
When should I use synchronous vs asynchronous replication?
Synchronous when data loss is unacceptable — payments, orders, anything with an RPO of zero — accepting the added write latency of replica confirmation. Asynchronous when throughput matters more than losing a few seconds of transactions — reporting, caching, analytics feeds. Most production clusters run one synchronous replica in-region and asynchronous replicas elsewhere.
How do I handle replication conflicts on a read replica?
A query on the replica can block WAL replay and get cancelled. Options: raise max_standby_streaming_delay so replay waits before cancelling, enable hot_standby_feedback so the primary's vacuum respects replica queries (watch for bloat), or push long queries to a dedicated replica with aggressive settings.
What is a replication slot and why do I need one?
A slot makes the primary keep WAL until the consumer confirms it. Without one, an offline replica can come back to find its needed WAL already deleted — forcing a full pg_basebackup rebuild. Slots are cheap insurance, but monitor them: an abandoned slot pins WAL until the disk fills or max_slot_wal_keep_size invalidates it.
How does Patroni handle failover?
Patroni tracks cluster state in a DCS (etcd/Consul). When the leader key expires — typically 30s after the primary dies — the replica with the least lag acquires it and promotes itself. Remaining replicas repoint automatically. The old primary returns as a replica, resynced via pg_rewind if it diverged. Typical end-to-end failover: 10–60 seconds depending on ttl/loop_wait.
Can I replicate between different PostgreSQL versions?
Not with streaming — both ends need the same major version. Logical replication does cross versions, which is the standard trick for near-zero-downtime major upgrades: publish on 16, subscribe on 17, cut over when caught up. Subscribing from newer to older has limits; always check the version compatibility matrix for logical replication.
Related Resources
Complete Guide to SQL Query Optimization
Find and fix slow SQL queries: read EXPLAIN plans, index the right way, kill N+1 queries, and apply partitioning, pooling, and caching on PostgreSQL and MySQL.
GuideComplete Guide to Database Sharding
Master database sharding: shard keys, partitioning strategies, consistent hashing, cross-shard queries, resharding, Vitess and Citus.
GuideComplete Guide to Redis in Production: HA & Persistence
Keep Redis stable in production: RDB/AOF persistence, Sentinel vs Cluster for HA, memory management, security hardening, monitoring, and backups.
GuideComplete Guide to Elasticsearch Cluster Setup
Deploy and scale Elasticsearch clusters in production. Covers node roles, sharding, index templates, mapping, ILM, snapshots, security, and tuning.
RecipeSeed Database
How to seed databases with realistic data for development, testing, and staging environments using seed scripts, migrations, and factories across PostgreSQL, MongoDB, and Prisma.
GuideComplete Guide to MongoDB Indexing
Choose the right MongoDB index for every query pattern: compound, text, geospatial, TTL, wildcard, partial indexes, the ESR rule, covered queries, and explain plans.