Replication & High Availability
Replication Models
Replication copies changes from a primary server, which accepts writes, to one or more replicas (standbys). Engines replicate either the physical storage changes or logical row changes, and each approach suits different goals.
Figure: WAL streaming keeps standbys synchronized while WAL archives and base backups enable point-in-time recovery.
Physical vs Logical Replication
| Physical (streaming) | Logical | |
|---|---|---|
| What is sent | WAL: byte-level changes to data files. | Decoded row changes (insert, update, delete) per table. |
| Scope | The whole cluster, every database. | Selected tables, possibly filtered. |
| Replica | Read-only, identical copy; same major version. | Writable, independent database; versions may differ. |
| Typical use | HA failover, read scaling, disaster recovery. | Major-version upgrades, data distribution, integration. |
Set Up a Streaming Replica
A streaming replica starts from a base backup of the primary and then continuously receives WAL. With PostgreSQL 12+, pg_basebackup -R writes the connection settings and the standby.signal file for you:
# On the replica host: clone the primary and configure it as a standby.
pg_basebackup --host=db-primary --username=replicator \
--pgdata=/var/lib/postgresql/data \
--wal-method=stream --write-recovery-conf \
--slot=replica_1 --create-slot --progress
A replication slot makes the primary keep WAL until this replica has received it, so a replica that falls behind can still catch up. The cost is that a replica which disappears causes WAL to pile up on the primary until the disk fills; cap it with max_slot_wal_keep_size and drop slots of decommissioned replicas.
Publish and Subscribe Tables
Logical replication works at the table level with a publication on the source and a subscription on the target. The source needs wal_level = logical, and the target needs the table definitions in advance; schema changes are not replicated.
-- On the source database:
CREATE PUBLICATION shop_pub FOR TABLE customer, customer_order, order_line;
-- On the target database (tables already created with the same structure):
CREATE SUBSCRIPTION shop_sub
CONNECTION 'host=db-source dbname=shop user=replicator sslmode=verify-full'
PUBLICATION shop_pub;
Synchronous and Asynchronous Replication
The central trade-off of replication is when the primary tells a client that a commit succeeded.
Durability vs Latency
- Asynchronous (the default): the primary commits locally and sends WAL afterwards. Commits are fast, but if the primary fails, the most recent transactions may never reach the replica — the data loss equals the replication lag.
- Synchronous: the primary waits until at least one standby confirms it has the WAL. No committed transaction is lost when the primary fails, but every commit pays a network round trip, and if no synchronous standby is reachable, commits stop.
# postgresql.conf on the primary: wait for any one of two named standbys.
synchronous_standby_names = 'ANY 1 (replica_1, replica_2)'
synchronous_commit = on # remote_apply also waits until the change is visible
Configure at least two candidate synchronous standbys, so the loss of one does not halt writes. Place them close enough that the round trip is acceptable; synchronous replication across continents adds that latency to every commit.
Monitor Replication Lag
Lag is both a data-loss risk and a correctness issue for applications that read from replicas: a user may not see the change they just made. Measure it on the primary:
SELECT application_name,
state,
sync_state,
write_lag, flush_lag, replay_lag,
pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn)) AS replay_behind
FROM pg_stat_replication;
Alert when lag exceeds what the RPO and the read-your-writes needs of the application allow. Route reads that must see the latest data to the primary.
Failover and High Availability
Replication provides the copy; failover is the act of making a replica the new primary and redirecting clients to it. Doing it automatically is valuable — and dangerous when done wrong.
Promote a Standby
A manual failover in PostgreSQL is a single command on the chosen standby, after confirming the old primary is really down:
-- On the standby (PostgreSQL 12+): stop recovery and start accepting writes.
SELECT pg_promote();
After promotion, clients must find the new primary. Common approaches are a virtual IP that moves, a DNS name that is updated, a proxy such as HAProxy or PgBouncer in front of the cluster, or multi-host connection strings with target_session_attrs=read-write, which make the client driver try each host until it finds the writable one.
Avoid Split Brain
The worst HA failure is split brain: two servers both believe they are primary and accept writes, so the data diverges and cannot be merged automatically. It happens when a network partition makes a healthy primary look dead. Prevent it with:
- A consensus store (etcd, Consul or ZooKeeper) that decides which node holds the leader lock; a node that loses contact with the majority must stop accepting writes.
- Fencing: forcibly isolating the old primary (shutting it down or cutting its network) before promoting a replacement.
- An odd number of voters across at least three failure zones, so a majority always exists on one side of a partition.
For PostgreSQL, Patroni is a widely used HA manager built on these principles; managed cloud services provide multi-zone failover as a feature. Do not build automatic failover from ad hoc scripts.
Rejoin the Old Primary
After a failover, the old primary may contain transactions that never reached the new one. It cannot simply be restarted as a replica; it must be rewound to the point where timelines diverged with pg_rewind, or rebuilt from a fresh base backup. Any transactions it held only locally are lost, which is exactly the asynchronous-replication risk described above.
Designing for Resilience
High availability is an architecture, not a feature switch. Decide what failures must be survived and what each costs.
Common Topologies
| Topology | Survives | Trade-off |
|---|---|---|
| Primary + async replica, same zone | Server failure, with possible small data loss. | Cheap; zone outage takes both. |
| Primary + sync replicas in three zones | Zone failure without data loss. | Commit latency; needs a consensus-based manager. |
| Above + async replica in another region | Regional disaster, with possible data loss. | Cost and operational complexity; manual regional failover. |
Replication Is Not Backup
A replica faithfully copies every change — including DROP TABLE, a buggy migration and data encrypted by ransomware — within milliseconds. HA protects against losing a server; only backups with point-in-time recovery protect against losing data. Run both, as described in Backup & Recovery. Delayed replicas (recovery_min_apply_delay) can add a safety window, but they complement backups rather than replace them.
Practice Lab
Run three PostgreSQL instances on one machine on different ports, or as containers.
Build and Break a Replica
- Create a streaming replica with a replication slot, insert rows on the primary and read them on the replica.
- Try to write on the replica and read the error.
- Stop the replica for a few minutes under write load, watch WAL accumulate on the primary, then restart it and watch the lag in
pg_stat_replicationfall to zero.
Practice a Failover
- Stop the primary abruptly, promote the replica with
pg_promote(), and connect a client using a multi-host connection string. - Make the old primary rejoin as a replica of the new one using
pg_rewind(it requireswal_log_hints = onor data checksums, so enable one before the lab starts). - Write a one-page runbook from what you did, including how you confirmed the old primary was really down before promoting.