In short
Replication keeps copies of a database on other servers by shipping its change log to them, so reads can be spread across replicas, a standby can take over when the primary fails, and data can sit closer to the people reading it. In PostgreSQL, physical streaming replication copies the write-ahead log byte for byte and is asynchronous by default, while logical replication sends row changes through publications and subscriptions. Asynchronous replicas lag behind, so an application that reads from them needs a rule for read-your-writes, such as sending a user's reads to the primary right after a write or checking that the replica has replayed past the write's log position.
Key points
- Replicate for three reasons: to spread reads, to survive the loss of the primary, and to put data near its readers. Each one asks for a different setup.
- Asynchronous replication is the default in PostgreSQL and MySQL. A commit returns before any replica has the change, so a failover can lose the latest commits and a replica read can be stale.
- Synchronous commit trades write latency for durability:
onwaits for a standby to flush,remote_applywaits until the change is visible there, andANY ksets a quorum. - Measure lag in bytes and in time from
pg_stat_replicationon the primary, and alert on both; a lag figure alone does not tell you whether a given user's write has arrived. - Get read-your-writes by routing a session to the primary for a short window after it writes, or by carrying the write's LSN and reading only from a replica that has replayed past it.
- Failover needs an outside referee and a way to fence the old primary. Two primaries accepting writes is the failure that loses data.
Why replicate a database
A single database server is one machine, one disk and one location. Replication keeps one or more copies on other servers and keeps them current by sending them the primary's change log. Teams reach for it for three different reasons, and the reason decides most of the design:
- Read scaling. Reports, search pages and dashboards read far more than they write. Sending those reads to replicas leaves the primary's CPU, memory and connections for writes and for reads that must be current.
- Availability. A standby that already has nearly all the data can be promoted when the primary dies, instead of restoring a backup. How much data that standby is allowed to miss is the central choice, covered under synchronous commit below.
- Locality. A replica in another region answers reads for people near it with a shorter round trip, and doubles as a disaster recovery copy if the primary's region is lost.
What replication does not do is protect you from your own mistakes. A DELETE without a WHERE clause, or a bad migration, is replicated as faithfully as a good one, within seconds or less. Replicas complement backups and point-in-time recovery; they do not replace them, as backup and disaster recovery explains.
Replication also changes what a read means. With one server, a read after a write sees the write. With replicas, it might not, and which guarantees you can still offer is the subject of consistency models and the CAP theorem. This post stays practical: how PostgreSQL replicates, how to measure the gap, and how an application routes around it.
Physical streaming vs logical replication in PostgreSQL
PostgreSQL writes every change to its write-ahead log (WAL) before changing data files. Both kinds of replication start from that log, but they send different things.
Physical streaming replication sends the WAL itself. A standby connects to the primary, which streams WAL records as they are generated, without waiting for a WAL file to fill; the documentation says the delay is typically under one second, and that streaming replication is asynchronous by default. The standby replays the records and ends up with a block-for-block copy of the whole cluster: every database, every table and every index. With hot standby enabled it accepts read-only queries while it replays. A standby can also pass WAL on to other standbys; the documentation calls this cascading replication, notes that it reduces direct connections to the primary and bandwidth between sites, and says it is currently asynchronous.
Logical replication decodes the WAL into row changes and sends those. A publisher defines publications, a subscriber subscribes to them, and each row is identified by its replica identity, usually the primary key, rather than by where it lives on disk. The subscriber first copies a snapshot of each table, then applies changes in the publisher's commit order. Because the subscriber is an ordinary, writable database, logical replication can copy a subset of tables, filter rows and columns, consolidate several databases into one, and replicate between major versions, which is why it is often used for upgrades with little downtime. The same decoding machinery feeds change data capture pipelines.
Logical replication has gaps that physical replication does not. The documentation lists them: schema changes (DDL) are not replicated, sequence values are not replicated (so after a switchover you must set them yourself), large objects are not replicated, and only tables can be published, not views or materialized views. Plan schema changes so that the subscriber can accept rows from before and after the change; the documentation suggests applying additive changes to the subscriber first.
| Physical streaming | Logical | |
|---|---|---|
| What travels | WAL records, byte for byte | Decoded row changes per table |
| Scope | The whole cluster | Chosen tables, optionally filtered rows and columns |
| Replica writable | No, read-only hot standby | Yes, it is an ordinary database |
| Versions | Same major version and platform | Can differ, which is why it is used for upgrades |
| Schema changes | Replicated with everything else | Not replicated; apply them yourself |
| Typical use | Read replicas and failover standbys | Upgrades, partial copies, consolidation, CDC |
Synchronous, asynchronous and quorum commit
The question that matters for durability is what a commit waits for before it returns to the client. In PostgreSQL that is the synchronous_commit setting, together with synchronous_standby_names, which lists the standbys that count. With no synchronous standbys named, only on and off mean anything, and the replicas are asynchronous: the commit returns once the primary has flushed its own WAL, and replicas catch up afterward.
Once standbys are named, the levels describe how far along the standby must be:
| synchronous_commit | The commit waits until | Survives | A read on the standby right after commit |
|---|---|---|---|
off | Nothing; the local flush happens shortly after | Not even a primary crash: the latest commits can vanish, though the database stays consistent | May be stale |
local | The primary has flushed its WAL | A primary crash; not the loss of the primary | May be stale |
remote_write | Standbys have written the commit record to their file system | A standby PostgreSQL crash, not a standby OS crash | May be stale |
on (default) | Standbys have flushed the commit record to durable storage | Loss of the primary | May be stale: flushed is not yet replayed |
remote_apply | Standbys have replayed the commit, so queries there see it | Loss of the primary | Sees the write |
The documentation is plain about the cost: the minimum extra wait is the round trip between primary and standby, and careless use reduces performance through longer response times and more contention, because a transaction keeps its locks while it waits. Read-only transactions and rollbacks do not wait. The setting can be changed per user, per session and per transaction, so a common design keeps most traffic at a cheaper level and raises it only for writes that must not be lost, with SET LOCAL synchronous_commit = remote_apply inside that transaction.
synchronous_standby_names chooses which standbys count. FIRST 2 (s1, s2, s3) is priority-based: s1 and s2 are synchronous, and s3 takes over if one of them fails. ANY 2 (s1, s2, s3) is quorum commit: a commit waits for any two of the three, so one slow or lost standby does not stall writes. pg_stat_replication reports each standby's role in its sync_state column as async, potential, sync or quorum.
Synchronous replication has a sharp edge, and it is worth seeing once. On a local PostgreSQL 14 pair with synchronous_standby_names = 'ANY 1 (replica1)', a remote_apply insert was visible on the standby at once. Then the standby was stopped and another insert sent with a two-second statement_timeout:
-- primary: ALTER SYSTEM SET synchronous_standby_names = 'ANY 1 (replica1)'; then reload
application_name | sync_state
------------------+------------
replica1 | quorum
-- SET synchronous_commit = remote_apply; INSERT ... 'sync'
-- an immediate read on the standby found the row: count = 1
-- standby stopped, then on the primary:
SET statement_timeout = '2s';
INSERT INTO orders (note) VALUES ('standby down');
-- ... no reply. Two minutes later pg_stat_activity showed it waiting:
-- wait_event_type = IPC, wait_event = SyncRep, waited = 00:02:04.97
-- pg_cancel_backend() on that pid released it:
WARNING: canceling wait for synchronous replication due to user request
DETAIL: The transaction has already committed locally, but might not have been replicated to the standby.
INSERT 0 1
-- and the row was there on the primary afterward: count = 1The timeout did not end the wait; the insert sat in the SyncRep wait for over two minutes until it was canceled by hand, and the cancel warned that the row had already committed locally. That matches the documentation, which says such commits may never complete if a synchronous standby crashes, and that the fix is to lower the number of standbys commits wait for, or to fail over. Two lessons follow. Run at least one more synchronous candidate than the count you wait for, which is what ANY 1 (s1, s2) does. And treat a client-side error during a synchronous commit as "outcome unknown", not "failed", because the row may be there; an idempotency key makes the retry safe.
Replication lag and how to measure it
Lag is the WAL the primary has generated that a standby has not yet applied. It has stages, and each stage points at a different bottleneck. The documentation's guidance: a large gap between the primary's current WAL position and sent_lsn means the primary is under heavy load; a gap between sent_lsn and what the standby has received points at the network or a busy standby; and a gap between received and replayed means WAL is arriving faster than the standby can apply it.
pg_stat_replication on the primary has one row per WAL sender, with four positions (sent_lsn, write_lsn, flush_lsn, replay_lsn) and three times (write_lag, flush_lag, replay_lag). The times measure how long recent WAL took to be written, flushed and replayed and for the primary to hear about it, and they line up with the remote_write, on and remote_apply levels above. For an asynchronous standby, the documentation says replay_lag approximates how long it takes before recent transactions become visible to queries. pg_wal_lsn_diff turns two positions into bytes.
-- On the primary: one row per connected standby
SELECT application_name, state, sync_state,
pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS replay_lag_bytes,
write_lag, flush_lag, replay_lag
FROM pg_stat_replication;
-- On a standby: what has arrived, what has been applied, and how far apart they are
SELECT pg_is_in_recovery(),
pg_last_wal_receive_lsn(),
pg_last_wal_replay_lsn(),
pg_wal_lsn_diff(pg_last_wal_receive_lsn(), pg_last_wal_replay_lsn()) AS replay_backlog_bytes,
now() - pg_last_xact_replay_timestamp() AS since_last_replayed_xact;Run against a local primary and one streaming standby, these returned:
-- primary (PostgreSQL 14, one standby on the same machine, after a 50,000-row insert)
application_name | state | sync_state | replay_lag_bytes | write_lag | flush_lag | replay_lag
------------------+-----------+------------+------------------+-----------------+-----------------+-----------------
replica1 | streaming | async | 0 | 00:00:00.015057 | 00:00:00.015058 | 00:00:00.111653
-- standby
pg_is_in_recovery | pg_last_wal_receive_lsn | pg_last_wal_replay_lsn | replay_backlog_bytes | since_last_replayed_xact
-------------------+-------------------------+------------------------+----------------------+--------------------------
t | 0/36E87C8 | 0/36E87C8 | 0 | 00:00:01.543679
-- and a write sent to the standby
ERROR: cannot execute INSERT in a read-only transactionA few details make these numbers easy to misread:
- The time columns are not zero when a standby has caught up. The documentation says they show how long the most recent WAL took, then go blank once there is no more WAL activity. They are also not a prediction of how long a lagging standby needs to catch up.
now() - pg_last_xact_replay_timestamp()keeps growing on an idle primary, because the timestamp is when the last replayed commit was generated on the primary. Combine it with the byte gap before you alert on it.- Bytes and seconds answer different questions. Bytes say how much work is queued; seconds say how stale a read can be. Alert on both, and on a standby missing from
pg_stat_replicationaltogether. - Long-running queries on a hot standby can hold up replay. The standby either delays WAL replay or cancels the conflicting query;
max_standby_streaming_delaysets how long it waits.hot_standby_feedbackavoids many cancellations by stopping the primary from vacuuming rows a standby query still needs, at the price of table bloat on the primary. - Replication slots keep WAL on the primary until every slot's consumer has received it, even while that consumer is disconnected. A forgotten slot can fill the disk;
max_slot_wal_keep_sizecaps how much it can hold back.
Read-your-writes and monotonic reads
The hot standby documentation puts it directly: data on the standby is eventually consistent with the primary, and the same query on both can return different results. For many reads that is fine. Two cases are not, and both have names. Read-your-writes: a user saves a profile and the next page, served from a lagging replica, shows the old one. Monotonic reads: a user refreshes twice, the first request hits a fresh replica and the second a stale one, and a comment appears and then disappears.
Applications get these guarantees in three common ways, from simplest to most precise:
- Route after write. After a session writes, send its reads to the primary for a fixed window, longer than your normal replay lag. Simple and coarse: it costs primary load for writers and breaks when lag exceeds the window.
- Pin per request or per feature. Send reads that must be current, such as the page shown right after a form submit, a balance before a transfer, or a uniqueness check, to the primary always, and everything else to replicas.
- Track a log position. After the write commits, read the primary's WAL position and keep it with the session, in a cookie or a token. Before a replica serves that session, check that it has replayed at least that far; if no replica has, wait briefly or read the primary. Update the stored position after every read as well, and you get monotonic reads too.
The third method is a few lines of SQL. Here it is against the same local pair, with replay paused on the standby to make the lag visible:
-- Primary: the write, then the LSN to remember in the user's session
INSERT INTO orders (note) VALUES ('after pause') RETURNING id; -- 50001
SELECT pg_current_wal_lsn(); -- 0/36E8880
-- Replica: may this replica serve that user's next read?
SELECT pg_last_wal_replay_lsn() >= '0/36E8880'::pg_lsn AS caught_up;
-- caught_up = f while replay was paused with pg_wal_replay_pause();
-- the primary showed replay_lag_bytes 240, replay_lag 00:00:04.097572
-- caught_up = t about a second after pg_wal_replay_resume()pg_current_wal_lsn() returns the primary's current write position, which is at or past your commit, so the token is conservative: at worst a session waits for someone else's later write too. The routing logic around it is small. This simulation has two replicas with different lags and compares round-robin reads with token-checked reads for a user who has just written:
// Read-your-writes and monotonic reads with LSN tokens, simulated in memory.
// The primary numbers each commit (its LSN); each replica applies commits after its own lag.
type Row = { lsn: number; value: string };
type Entry = Row & { key: string; at: number };
const MISSING: Row = { lsn: 0, value: '(not found)' };
const log: Entry[] = [];
let primaryLsn = 0;
function write(key: string, value: string, now: number): number {
primaryLsn += 1;
log.push({ key, value, lsn: primaryLsn, at: now });
return primaryLsn; // the commit LSN: the token the session keeps
}
type Db = { name: string; lagMs: number; applied: number; data: Map<string, Row> };
const node = (name: string, lagMs: number): Db => ({ name, lagMs, applied: 0, data: new Map() });
function catchUp(n: Db, now: number) {
for (const e of log) {
if (e.lsn > n.applied && e.at + n.lagMs <= now) {
n.data.set(e.key, { lsn: e.lsn, value: e.value });
n.applied = e.lsn;
}
}
}
type Session = { minLsn: number }; // highest LSN this user has written or read
function pick(nodes: Db[], primary: Db, s: Session, now: number, useToken: boolean): Db {
const fresh = useToken ? nodes.filter((n) => n.applied >= s.minLsn) : nodes;
return fresh.length > 0 ? fresh[now % fresh.length] : primary; // nobody caught up: primary
}
for (const useToken of [false, true]) {
log.length = 0;
primaryLsn = 0;
const primary = node('primary', 0);
const replicas = [node('replica-a', 30), node('replica-b', 400)];
const s: Session = { minLsn: 0 };
console.log(useToken ? '-- with LSN token' : '-- round-robin, no token');
s.minLsn = Math.max(s.minLsn, write('profile:42', 'name=Ada', 0));
for (const t of [0, 5, 50, 51, 200, 201, 501]) {
[primary, ...replicas].forEach((n) => catchUp(n, t));
const n = pick(replicas, primary, s, t, useToken);
const row = n.data.get('profile:42') ?? MISSING;
if (useToken) s.minLsn = Math.max(s.minLsn, row.lsn); // monotonic reads
console.log('t=' + String(t).padStart(3) + 'ms ' + n.name.padEnd(9) + ' ' + row.value);
}
}Running it with Node.js 22 (node --experimental-strip-types) prints:
-- round-robin, no token
t= 0ms replica-a (not found)
t= 5ms replica-b (not found)
t= 50ms replica-a name=Ada
t= 51ms replica-b (not found)
t=200ms replica-a name=Ada
t=201ms replica-b (not found)
t=501ms replica-b name=Ada
-- with LSN token
t= 0ms primary name=Ada
t= 5ms primary name=Ada
t= 50ms replica-a name=Ada
t= 51ms replica-a name=Ada
t=200ms replica-a name=Ada
t=201ms replica-a name=Ada
t=501ms replica-b name=AdaRound-robin shows both anomalies: the user's own write is missing at first, and at 50 ms and 51 ms it appears and then disappears as reads alternate between a 30 ms replica and a 400 ms one. With the token, reads go to the primary until a replica has caught up, then only to replicas that are at least as fresh as anything the session has seen. In production the token is the LSN string, compared with pg_lsn on the replica or tracked by the router from periodic lag checks. MySQL offers the same idea with global transaction identifiers: WAIT_FOR_EXECUTED_GTID_SET(gtid_set, timeout) blocks on a replica until a set of transactions has been applied, returning 0 on success and 1 on timeout. Always pass a timeout; the default of 0 waits indefinitely.
Routing connections to the primary and the replicas
Read-your-writes logic needs somewhere to live. The usual layers, from closest to the database outward:
- The driver. libpq accepts several hosts in one connection string and a
target_session_attrsoption:read-writeorprimaryconnect only to a server that accepts writes,standbyonly to a hot standby, andprefer-standbytries standbys first and falls back to any server.load_balance_hosts=randomspreads connections across the listed hosts. This finds the primary after a failover without DNS changes, but it decides per connection, not per query. - The application. Keep two pools, a writer and a reader, and choose per query with the rules above. This is where session tokens and "pin this read to the primary" decisions belong, because only the application knows which reads must be current.
- A proxy or pooler. A pooler in front of each server caps connections, and a routing proxy can split reads from writes. A proxy that guesses from SQL text cannot know about read-your-writes, so send it hints or keep the decision in the app. Pool sizing and transaction mode are covered in Postgres connection pooling.
Whatever the layer, take lagging replicas out of rotation. A health check that reads replay_lag or the byte gap and drops any replica past a threshold keeps stale reads bounded for everything that does not carry a token. Leave the primary able to absorb the full read load for a while, because when every replica falls behind at once, after a large batch write for example, all reads land there.
Failover and split brain
Promotion itself is one command: pg_ctl promote or SELECT pg_promote() on the standby. The hard part is everything around it, and the PostgreSQL documentation says outright that PostgreSQL does not provide the system software to detect a failed primary and notify the standby. That is the job of an external failover manager or the managed service you run on.
- Decide the primary is really gone. A network blip between the monitor and the primary looks like a dead primary. Use several observers and a quorum, and accept that a short outage is better than a wrong failover.
- Pick the standby with the most WAL. With asynchronous replicas, compare
pg_last_wal_receive_lsn()across candidates; anything the primary committed beyond the chosen standby's position is lost. - Fence the old primary before promoting. The documentation names the technique STONITH (shoot the other node in the head) and says it is needed to avoid both systems thinking they are primary, which leads to confusion and data loss. Cut its network, stop its process, or revoke its storage.
- Promote, then move clients: update the address they use, or rely on
target_session_attrs=read-writeso drivers find the new primary. - Rebuild the old primary as a standby of the new one. It may hold commits no one else has, so it cannot rejoin as is.
pg_rewindexists for this: the documentation describes bringing an old primary back after failover as a standby that follows the new one. A fresh base backup also works.
Split brain is what happens when fencing fails: an isolated old primary keeps accepting writes from clients that can still reach it, while the new primary accepts others. The two histories cannot be merged automatically. The rule is the same as for any leader with a lease: whatever accepts writes must be able to tell that its leadership has ended. Synchronous replication helps here too. An isolated primary whose commits must be confirmed by a standby it can no longer reach stops returning successful commits, which is the hang shown earlier turned into a feature, as long as nothing cancels those waits.
For logical replication, failover has extra steps: subscribers do not get sequence values, so set them on the new primary before it takes writes, and recreate subscriptions or slots that pointed at the old one.
MySQL equivalents, briefly
MySQL replicates from its binary log rather than a WAL, but the shape is the same. Asynchronous replication is the default: the MySQL manual says the source does not know whether or when a replica has processed transactions, and that there is no guarantee any event reaches any replica. Semisynchronous replication makes the source wait until at least one replica (the count is configurable) has received the events and flushed them to its relay log, which is closest to PostgreSQL's on level: it is received and durable, not yet applied. If no replica acknowledges within the timeout, the source reverts to asynchronous replication and returns to semisynchronous once a replica catches up, so durability quietly weakens during exactly the incidents you care about. Monitor that switch.
Two more parallels. The manual warns that after a source crash and failover, the failed source should be discarded, not reused, because it may hold transactions no replica acknowledged: the same rule as rebuilding an old PostgreSQL primary. And global transaction identifiers play the role of LSNs for read-your-writes, through WAIT_FOR_EXECUTED_GTID_SET as shown above.
| Mode | Commit waits for | Data lost if the primary dies | Replica read right after commit | Write latency |
|---|---|---|---|---|
| PostgreSQL async streaming | Local WAL flush only | Whatever was not yet streamed | May be stale | Lowest |
PostgreSQL sync, remote_write | Standby wrote to its OS | Only if the standby's OS also crashes | May be stale | Plus one round trip |
PostgreSQL sync, on | Standby flushed to disk | None that was acknowledged | May be stale | Plus round trip and standby flush |
PostgreSQL sync, remote_apply | Standby replayed it | None that was acknowledged | Sees the write | Highest; also waits for replay |
PostgreSQL quorum, ANY k | Any k of the listed standbys | None that was acknowledged | Depends on which standby you read | Set by the k-th fastest standby |
| PostgreSQL logical | Publisher's own commit | Whatever the subscriber had not applied | May be stale | Unchanged on the publisher |
| MySQL async (default) | Source commit only | Whatever replicas had not fetched | May be stale | Lowest |
| MySQL semisynchronous | At least one replica logged it to its relay log | None that was acknowledged, unless it fell back to async | May be stale | Plus one round trip |
If you are building a product that needs read replicas, failover or a read-your-writes guarantee, see our web app development service: the code lives in your GitHub from day one, AI-assisted work is reviewed by an engineer, and the founders are on the calls.
Sources
Checked when this post was written.
- PostgreSQL documentation: 26.2. Log-Shipping Standby Servers (streaming replication, synchronous replication, slots, cascading)
- PostgreSQL documentation: 26.3. Failover
- PostgreSQL documentation: 26.4. Hot Standby
- PostgreSQL documentation: 19.5. Write Ahead Log (synchronous_commit)
- PostgreSQL documentation: 27.2. The Cumulative Statistics System (pg_stat_replication)
- PostgreSQL documentation: 9.28. System Administration Functions (WAL and recovery functions)
- PostgreSQL documentation: Chapter 29. Logical Replication
- PostgreSQL documentation: 29.8. Restrictions (logical replication)
- PostgreSQL documentation: pg_rewind
- PostgreSQL documentation: 32.1. Database Connection Control Functions (libpq, target_session_attrs)
- MySQL 8.4 Reference Manual: 19.4.10 Semisynchronous Replication
- MySQL 8.4 Reference Manual: 14.18.2 Functions Used with Global Transaction Identifiers (GTIDs)