Every database you run in production is a promise that the data will still be there tomorrow. A single PostgreSQL instance keeps that promise right up until the disk dies, the VM is evicted, or a migration goes wrong at 2 AM. Replication is the standard answer: keep a second copy of the data, on another machine, kept current enough to take over. What makes replication interesting is not the copying — it’s deciding how current “current enough” is, and what you’re willing to pay for it.
This post walks through how streaming replication works in practice: physical versus logical replication, the difference between the transport of WAL and the commit policy that decides whether a replica can lose transactions, how to measure lag honestly, and the failure modes that show up only during failover. The examples use PostgreSQL, but the tradeoffs — sync versus async, replay lag, promotion — map onto MySQL, SQL Server availability groups, and most managed database offerings.
Physical vs Logical: Two Ways to Copy a Database
PostgreSQL’s write-ahead log records every change to pages and rows before they hit the data files. Physical replication ships that WAL stream to a standby byte-for-byte: the standby replays the same page changes into an identical copy of the cluster. It’s fast, simple, and exact — but the replica is a mirror of one specific PostgreSQL version on one specific architecture, and it can’t be queried with different data visible. The whole cluster replicates or nothing does.
Logical replication decodes the WAL back into row-level changes and publishes them by table. A subscriber can live on a different PostgreSQL major version, replicate only a subset of tables, or even fan the changes out into a different schema. That flexibility costs more: logical decoding has CPU overhead, large transactions replicate only at commit, and sequences and DDL don’t replicate at all — a gap that has bitten everyone who set up logical replication and then wondered why their identity columns drifted out of sync.
The default choice for high availability is physical streaming replication; logical replication earns its keep for upgrades, consolidation, and feeding analytics pipelines. The rest of this post applies to both — the transport differs, but the commit policy and the lag math are the same.
The Pipeline: WAL, Walsender, Walreceiver
Streaming replication has three moving parts. On the primary, a walsender process reads WAL records as they’re generated and streams them to the standby. On the standby, a walreceiver writes the incoming records into its own WAL. Then the standby’s recovery machinery replays those records into its data files while the instance runs read-only queries — this is hot standby mode.
Under normal load the standby trails the primary by milliseconds. That’s the number everyone forgets to plan for, because the interesting failures are all lag failures: the network hiccups, the standby’s disk falls behind on replay, a long-running analytical query on the replica blocks vacuum from cleaning up rows the primary already recycled. Healthy replication is boring; the day it isn’t boring is the day you find out what your commit policy actually promised.
Sync vs Async: What a Commit Actually Waits For
Here’s the distinction that matters. With asynchronous replication — the default posture — a commit is acknowledged as soon as it’s durable on the primary’s local disk. WAL reaches the standby in its own time. If the primary’s disk dies before a committed transaction reached the standby, that transaction is gone, even though the client saw a successful commit. Your recovery point objective is not zero; it’s however much WAL hadn’t arrived yet.
The synchronous_commit setting turns this into a dial with five positions, ordered from least to most durability:
- off — acknowledge before even the local flush; a primary crash can lose recently committed transactions
- local — wait for the local disk flush; async replication, no replica guarantee
- remote_write — wait until the standby has received WAL in its OS cache
- on — wait until the standby has flushed WAL to its disk
- remote_apply — wait until the standby has replayed the transaction and it’s visible to queries
One subtlety trips people up: the default value of synchronous_commit is on, but with synchronous_standby_names unset, on behaves like local — the commit only waits for the primary’s own flush. You get synchronous replication only when you name a standby. And when you do, each commit pays a network round trip plus the standby’s disk flush, so write latency grows by roughly the distance between the machines. A standby in another region turns a one-millisecond commit into a forty-millisecond commit. That’s the entire price of zero data loss, charged per transaction.
remote_apply is the strictest mode and the one that buys you something extra: with it, once a commit returns, a read against the standby sees the data. That’s the only setting under which shipping reads to replicas preserves read-your-writes semantics for the writing session. Every other mode allows a window where the client wrote, a replica-served request reads, and the write isn’t there yet.
Measuring Lag Honestly
Lag is not one number. A WAL record passes through four stages — sent by the primary, written by the standby’s OS, flushed to the standby’s disk, replayed into the data files — and can stall at any of them. The pg_stat_replication view on the primary exposes each stage: the current LSN positions plus write_lag, flush_lag, and replay_lag. A growing write_lag points at the network; a growing replay_lag with a healthy network means the standby can’t apply fast enough — often because a long query there is blocking replay, or its disks are saturated.
SELECT application_name,
state,
pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS replay_bytes_behind,
write_lag, flush_lag, replay_lag
FROM pg_stat_replication;
Alert on replay_bytes_behind relative to your WAL retention, and on replay_lag relative to your failover tolerance. A useful rule: if lag can exceed the volume of data you can afford to lose, your RPO is that lag, not zero, regardless of what the architecture diagram says.
Failover Is Where the Bill Arrives
Promoting a standby is mechanically easy — pg_promote() or a managed platform’s button — but three costs tend to surprise. First, with async replication, promotion orphans whatever WAL hadn’t arrived: transactions that returned success to clients simply vanish. Applications that write then immediately read may see their own writes disappear. Second, the old primary can’t just rejoin as a replica; its timeline has forked. pg_rewind copies the diverged blocks back so the demoted node can follow the new primary — without it, you rebuild from a fresh base backup. Third, anything that held state keyed to the old primary’s identity — connection pools, DNS entries, replication slots — needs updating, and a slot on the demoted node pointing at a discarded timeline will sit there holding WAL forever.
Replication slots deserve their own warning. A slot pins WAL on the primary so a disconnected standby can catch up later. If that standby never comes back — decommissioned, forgotten, replaced by a new host — the primary retains WAL until the disk fills and the database stops accepting writes. Slots created for standby servers should be monitored the same way you monitor disk: pg_replication_slots shows active status and restart_lsn; an inactive slot of unknown ownership is an incident waiting for a full disk.
Practical Failure Modes Worth Knowing in Advance
- Query conflicts on the standby. Replay can remove rows a running standby query can still see, so PostgreSQL cancels the query.
hot_standby_feedbackmakes the standby report its oldest snapshot to the primary, which then delays vacuum — trading replica query stability for bloat on the primary. - Read-after-write across replicas. Route replica traffic behind a load balancer and any write-followed-by-read sequence can hit a stale replica. Either pin the writing session to the primary for a short window, gate replica reads on replay position, or accept
remote_apply‘s latency. - Single synchronous standby, single point of latency. When
synchronous_standby_namesnames one replica and that replica stalls, every commit on the primary stalls.ANY 1 (standby_a, standby_b)syntax waits for any one of several standbys, which converts a replica outage into a durability-availability tradeoff you chose in advance. - Split brain after a network partition. Fencing — ensuring the old primary cannot accept writes after promotion — is a property of your failover tooling (STONITH, watcher quorum, managed platform behavior), not of PostgreSQL itself.
Wrapping Up
Replication design reduces to two decisions: how much WAL a commit waits for (synchronous_commit plus your standby naming policy), and how much lag you can tolerate before failover loses data. Decide both explicitly, measure lag at the replay stage rather than guessing from dashboard vibes, monitor replication slots like disk usage, and rehearse promotion with pg_rewind at least once before the night you need it. The copy of the data is the easy part — the hard part is knowing precisely what “we have a replica” promised you, before a Tuesday-morning disk failure collects on the difference.