Skip to content

Replication, Read Replicas & Failover ​

"Beware that replication slots can cause the server to retain so many WAL segments that they fill up the space allocated for pg_wal." — PostgreSQL documentation, Log-Shipping Standby Servers, section "Replication Slots"

Summary: Replication copies every committed change from one server to others; the copies give you read capacity and a standby to fail over to, at the price of lag, stale reads and a hard decision about who is primary. Focus: PostgreSQL physical and logical replication end to end (WAL shipping, streaming, slots, hot standby, synchronous commit, cascading and delayed replicas, promotion, timelines, pg_rewind), failover tooling and routing (Patroni, repmgr, pgpool-II, HAProxy, PgBouncer, DNS), read-your-writes, and how MySQL, MongoDB and the managed clouds do the same jobs. Learning goal: Design a primary + replicas setup with an explicit RPO and RTO, route reads so users never see their own writes disappear, measure lag correctly, and run a failover (and a switchover) without split brain.

This page is the complete reference for single-leader database replication and failover. It covers how a change travels from a primary's write-ahead log to a standby, every knob that decides how much you can lose (synchronous_commit, synchronous_standby_names), how standbys serve reads and why their queries get cancelled, how to measure lag in bytes and in seconds, how promotion and timelines work, how HA managers decide who is primary without split brain, and how applications in Go and Laravel route reads safely. It deliberately does not re-teach three neighbours: WAL records, checkpoints and crash recovery are in Durability, WAL & Crash Recovery; base backups, archiving and point-in-time recovery are in Backup, PITR & Disaster Recovery; and the consensus algorithms (Raft, Paxos) inside etcd, Group Replication or CockroachDB are in Distributed SQL, Consensus & 2PC. Consistency models in general (bounded staleness, causal, quorum reads) live in Eventual Consistency in Database Systems, and multi-leader and leaderless topologies are on the system-design path in Replication Topologies.

Page map ​

If you are looking forGo to
Tables you can memorise in one minuteEverything in one minute
Why replicate at all, and the trade-offWhy replication exists
How PostgreSQL and MySQL got here, version by versionWhere it comes from
WAL shipping, streaming, slots, hot standby, sync commit, cascading, delayed, logicalReplication mechanisms, one by one
Promotion, timelines, failover vs switchover, split brain, fencing, pg_rewindFailover, one concept at a time
Patroni, etcd, repmgr, pgpool-II, HAProxy, PgBouncer, DNSHA managers and routing
Stale reads, read-your-writes, monotonic reads, sticky sessions, lagReading from replicas
MySQL binlog, GTID, semi-sync, Group Replication; MongoDB; SQL Server; Oracle; RDS; AuroraPer-engine behaviour
Every knob, every monitoring view, every error messageMechanics
SQL + Go + Laravel for the classic problemsSolving the classic problems
Which errors to retry after a failoverRetries and failure handling
Which setup for which workloadChoosing a setup
Monolith to microservices to multi-regionIn architecture
Docker primary + replica, lag under load, promote, rewindLab
Wrong beliefs, cheat sheet, every term definedMisconceptions, Cheat sheet, Glossary

Everything in one minute ​

The mechanisms. Every row is unpacked in the mechanisms section.

MechanismIn plain wordsTiny exampleProduct
WAL shipping (file-based log shipping)Copy finished 16MB WAL files to the standbyarchive_command copies, standby restore_command readsPostgreSQL
Streaming replicationSend WAL bytes over a TCP connection as they are writtenwalsender on primary → walreceiver on standbyPostgreSQL
Replication slotPrimary promises to keep WAL until this consumer has itpg_basebackup -C -S replica1PostgreSQL
Hot standbyA standby that answers read-only queries while replayingReports run on the replicaPostgreSQL (hot_standby = on)
Synchronous replicationCommit waits for a standby's confirmationsynchronous_standby_names = 'ANY 1 (s1, s2)'PostgreSQL; MySQL semi-sync; MongoDB w: "majority"
Cascading replicationA standby feeds other standbysRemote DC replica relays to two local onesPostgreSQL
Delayed replicaA standby that stays N hours behind on purposerecovery_min_apply_delay = '4h' catches a bad DELETEPostgreSQL; MySQL SOURCE_DELAY
Logical replicationShip row changes per table, decoded from WALCREATE PUBLICATION / CREATE SUBSCRIPTIONPostgreSQL 10+; MySQL row binlog is similar
Binlog replicationReplica fetches the source's binary log and applies itCHANGE REPLICATION SOURCE TO ... SOURCE_AUTO_POSITION = 1MySQL

The commit levels (PostgreSQL synchronous_commit with a synchronous standby).

LevelCommit returns afterSurvives primary crash?Survives primary + standby OS crash?Standby read sees it at once?
offNothing flushed yetUp to 3 × wal_writer_delay of commits lostNoNo
localLocal WAL flushOnly if the standby got it in timeNoNo
remote_writeStandby wrote WAL to its OSYesNoNo
on (default)Standby flushed WAL to diskYesYesNo
remote_applyStandby replayed itYesYesYes

The failover vocabulary.

TermIn plain wordsWhat goes wrong without it
PromotionA standby becomes a read-write primary (pg_promote())Nothing accepts writes
TimelineA new history branch starts at each promotionOld and new primary cannot be told apart
Fencing / STONITHMake sure the old primary can no longer writeSplit brain: two primaries, two diverging histories
Leader lockOne key in etcd/Consul/ZooKeeper says who is primaryTwo managers promote two nodes
pg_rewindRewind the old primary to the branch point so it can followOld primary must be re-cloned from scratch
SwitchoverPlanned, lossless role swapMaintenance means data loss risk
RPO / RTOHow much data / how much time you may loseNobody knows if async is acceptable

The three things to do.

SituationDo this
A user must see what they just wrotePin their reads to the primary after a write (time window or LSN token), or remote_apply on that commit
A replica must never lose your data on failoverQuorum synchronous replication + an HA manager that only promotes a synchronous standby
A replica is down for hoursBound the slot: max_slot_wal_keep_size, and alert on pg_replication_slots.wal_status

Why replication exists ​

One database server is one disk, one machine, one data centre. Replication keeps live copies elsewhere for three different reasons, and the reasons pull in different directions:

  1. Availability: when the primary dies, a standby takes over in seconds instead of a restore taking hours.
  2. Read scaling: reports, search pages and analytics run on replicas instead of competing with writes.
  3. Locality and migration: a copy near users in another region, or a copy on a newer major version you are about to switch to.

The fundamental trade-off is between the latency of a commit and how much a failover may lose:

Asynchronous replicationSynchronous replication
Commit returns after the local flushCommit waits for at least one standby
Commit latency unchangedEach commit pays a network round trip (or more)
Failover may lose the last seconds of commits (RPO > 0)Failover to a synchronous standby loses nothing (RPO = 0)
A dead standby never blocks writesA dead synchronous standby blocks commits unless there is a spare
Default in PostgreSQL, MySQL, RedisMySQL semi-sync, PostgreSQL synchronous_standby_names, MongoDB w: "majority" (default), RDS Multi-AZ

PostgreSQL's high-availability chapter states it directly: "a fully synchronous solution over a slow network might cut performance by more than half, while an asynchronous one might have a minimal performance impact."

The picture we reuse on this page: a newspaper with one editor and several print shops. The editor phones every change to each shop. Async: the editor hangs up after dictating; a shop may still be typing when the editor's office burns down. Sync: the editor waits until a shop confirms it has the text. Quorum: any two of three shops confirming is enough. A reader at a far shop sees yesterday's headline for a while: that is replica lag. Failover is choosing the new editor while making sure the old one has really left the building and cannot phone in more changes.

Three common misunderstandings, up front ​

  • "A replica is a backup." A replica replays your DROP TABLE within milliseconds. Backups and PITR are a separate system (Backup, PITR & DR); a delayed replica is the only replica that helps with human error.
  • "Synchronous means zero data loss, full stop." Only when the HA manager promotes a node that was synchronous at the moment of failure, and only for levels on or stronger. With remote_write, a crash of both machines can still lose data; with a single sync standby, losing it blocks writes.
  • "Reading from a replica is the same as reading from the primary, just a bit later." Later is the whole problem: read-your-writes, monotonic reads and every read-decide-write built on a replica read break. Replica reads are a separate, weaker consistency tier.

Where it comes from ​

PostgreSQL. The docs name the primitive: "Directly moving WAL records from one database server to another is typically described as log shipping." File-based log shipping (warm standby) came first; streaming replication and hot standby arrived together in PostgreSQL 9.0, synchronous replication in 9.1, cascading replication in 9.2, replication slots, logical decoding and recovery_min_apply_delay in 9.4, pg_rewind in core in 9.5, remote_apply and multiple synchronous standbys in 9.6, built-in logical replication (publications/subscriptions) and quorum ANY in 10. Version 12 removed recovery.conf (standby mode is now a standby.signal file plus normal settings), 13 added max_slot_wal_keep_size, 16 added the subscription origin parameter that makes bidirectional logical replication possible and logical decoding on standbys, 17 added failover slots for logical replication and pg_createsubscriber, and the current documentation (PostgreSQL 19) adds ALTER SUBSCRIPTION ... REFRESH SEQUENCES and the retain_dead_tuples subscription option for conflict detection.

A standby that also accepts queries is defined in the docs: "A standby server can also be used for read-only queries, in which case it is called a hot standby server." Logical replication is defined against physical: "a method of replicating data objects and their changes, based upon their replication identity (usually a primary key). We use the term logical replication in contrast to physical replication, which uses exact block addresses and byte-by-byte replication."

MySQL. Binlog replication is older than any of this and starts from the same default: "Replication is asynchronous by default; replicas do not need to be connected permanently to receive updates from a source." (MySQL 8.4 Reference Manual). Semisynchronous replication (5.5), GTIDs (5.6) and Group Replication (5.7) followed; MySQL 8.0 renamed master/slave to source/replica in commands and variables, and 8.4 is the current LTS.

Failover tooling lives outside both servers. Patroni describes itself as "a template for high availability (HA) PostgreSQL solutions using Python" that "supports a variety of distributed configuration stores like ZooKeeper, etcd, Consul or Kubernetes." The vocabulary of leaders and followers, replication lag anomalies and failover pitfalls was consolidated for application developers by Kleppmann's Designing Data-Intensive Applications, chapter 5, which this page's replica-reads section follows in naming.

Replication mechanisms, one by one ​

Each block follows the same order: plain words, the usual wrong belief, the precise definition, a step-by-step timeline, real scenarios, what each product offers, and the configuration or code.

WAL shipping (file-based log shipping) Important ​

In plain words: the primary copies each finished WAL file to an archive; the standby keeps fetching files from the archive and replaying them.

Common misunderstanding: "WAL shipping is obsolete now that we have streaming." It is the fallback that saves a standby when streaming fell too far behind, and the same archive is your PITR source. Most production setups run both.

Definition: the primary's archive_command (or archive_library) runs once per completed 16MB WAL segment; a standby with restore_command set reads segments from the archive. Lag is at least one segment unless archive_timeout forces a switch. The docs contrast it with streaming, which "is more granular and streams WAL changes incrementally over a network connection".

text
     Primary                                  Archive (S3, NFS)            Standby
1    COMMIT writes WAL into segment ...0A
2    segment ...0A fills (16MB) / archive_timeout
3    archive_command copies ...0A  ─▶         000000010000000000000A0A
4                                                                          restore_command fetches ...0A
5                                                                          startup process replays it
     -- anything still in segment ...0B on the primary is NOT on the standby

Real scenario: a disaster-recovery standby in another region that only reads from object storage; a standby that was offline for a day catching up from the archive before switching to streaming; tools such as pgBackRest and WAL-G implementing archive_command/restore_command.

ProductFile/log shipping equivalent
PostgreSQLarchive_mode, archive_command/archive_library, restore_command, archive_timeout
MySQLCopying binlog files with mysqlbinlog --read-from-remote-server --raw (binlog server)
SQL ServerLog shipping (backup/copy/restore jobs)
OracleData Guard redo transport (ARCH mode)

Configuration: see the archive settings in Backup, PITR & DR; the replication-specific part is that a standby uses both: restore_command for anything streaming cannot supply.

Streaming replication Must-know ​

In plain words: the standby keeps a connection open to the primary and receives WAL bytes as soon as they are written, then replays them. It is a byte-for-byte copy of the whole cluster.

Common misunderstanding: "I can replicate one database, or replicate from PostgreSQL 16 to 17." Physical streaming copies the whole cluster (every database), only between identical major versions and architectures. Selective or cross-version copies are logical replication.

Definition: the standby has primary_conninfo (and usually primary_slot_name) and a standby.signal file in its data directory. Its walreceiver process connects with the replication protocol; the primary forks a walsender. The walreceiver writes and fsyncs WAL into the standby's pg_wal; the startup process replays it. The walreceiver reports its write, flush and apply positions back every wal_receiver_status_interval (10s) and after each batch. The primary needs a role with REPLICATION (or superuser), a pg_hba.conf line for the replication pseudo-database, and a free slot in max_wal_senders (default 10). wal_level must be replica (the default) or logical.

Primary (read-write)Hot standby (read-only)backend: COMMITwrites WAL recordpg_wal/ segments(16MB files, LSN)replication slotpins restart_lsnwalsenderwalreceiverwrite + fsyncstartup processreplays WALpg_wal/ on standby(received WAL)TCP streamfeedback: write/flush/apply LSNLSN growscurrent_wal_lsn0/5A00F000sent_lsnwrite_lsnflush_lsnreplay_lsn0/59FF2000pg_wal_lsn_diff(current, replay) = bytes a read on the standby is behindwrite_lag / flush_lag / replay_lag in pg_stat_replication = the same gaps as time

The picture shows the data path and the five positions you will see in monitoring. An LSN (log sequence number, type pg_lsn, written like 0/5A00F000) is a byte position in the WAL stream; subtracting two with pg_wal_lsn_diff() gives bytes of lag.

text
     Primary                                  Standby
1    COMMIT; WAL flushed up to 0/5A00F000
2    walsender sends ─▶  sent_lsn = 0/5A00F000
3                                             walreceiver write()     -> write_lsn
4                                             walreceiver fsync()     -> flush_lsn
5                                             startup replays         -> replay_lsn
6    pg_stat_replication shows all four, plus write_lag / flush_lag / replay_lag
7                                             a SELECT on the standby sees data up to replay_lsn only

Real scenario: the default HA pair; read replicas for a dashboard; a reporting replica that may be minutes behind under a nightly batch; a standby in a second availability zone for Patroni to promote.

ProductPhysical/stream equivalentCopies
PostgreSQLStreaming replication (walsender/walreceiver)Whole cluster, byte-identical
MySQLBinlog replication (I/O thread + applier threads)Logical events (rows or statements), per server
SQL ServerAlways On availability groupsLog blocks, per database group
OracleData Guard physical standby (redo apply)Redo, whole database
MongoDBReplica set oplog tailingLogical oplog entries
RedisREPLICAOF, async command streamWhole dataset

How to set it up (PostgreSQL):

sql
-- on the primary
CREATE ROLE replicator WITH REPLICATION LOGIN PASSWORD 'change-me';
-- pg_hba.conf:  host  replication  replicator  10.0.0.0/24  scram-sha-256
SELECT pg_reload_conf();
bash
# on the new standby host, empty data directory:
pg_basebackup -h primary -U replicator -D "$PGDATA" -X stream -R -C -S replica1 -P
# -R writes primary_conninfo + primary_slot_name to postgresql.auto.conf and creates standby.signal
# -C -S creates the physical replication slot replica1 on the primary
pg_ctl -D "$PGDATA" start

Replication slots Must-know ​

In plain words: a slot is the primary's promise "I will keep every WAL file this consumer has not received yet". It protects the standby and endangers the primary's disk.

Common misunderstanding: "Slots are free safety." A slot whose consumer is gone (a decommissioned replica, a crashed Debezium connector, a test subscription) holds WAL forever. The quote at the top of this page is the documented consequence: pg_wal fills, the primary cannot write WAL and shuts down. This is one of the most common PostgreSQL outages.

Definition: a physical slot (pg_create_physical_replication_slot) or logical slot (pg_create_logical_replication_slot, created by CREATE SUBSCRIPTION or CDC tools) has a restart_lsn; checkpoints never remove WAL newer than the oldest restart_lsn. Slots "provide an automated way to ensure that the primary server does not remove WAL segments until they have been received by all standbys". max_slot_wal_keep_size (default -1, unlimited) caps the retention: a slot that falls further behind is invalidated and its wal_status becomes lost ("this slot is no longer usable"). Without slots, wal_keep_size keeps a fixed amount and a standby that falls further behind fails with "requested WAL segment ... has already been removed" and must be re-cloned or fed from the archive. Logical slots additionally hold back catalog_xmin, and with hot_standby_feedback a physical slot carries the standby's xmin, so an abandoned slot also blocks VACUUM.

text
     Primary (pg_wal size)               Standby replica1 (slot replica1)
1    10 GB/h of WAL; slot restart_lsn advancing
2                                         host dies at 02:00
3    03:00  pg_wal 12 GB  wal_status = reserved
4    06:00  pg_wal 52 GB  wal_status = extended    -- beyond max_wal_size, still kept
5    without cap: 09:00  disk full -> PANIC: could not write to file "pg_wal/xlogtemp..."
5'   with max_slot_wal_keep_size = 50GB: slot invalidated, wal_status = lost, primary keeps running
6'                                        replica1 must be re-cloned with pg_basebackup

Real scenario: a replica that was shut down for a weekend; a staging subscription nobody dropped; a Debezium connector stuck on a poison message; a logical slot left behind after a failed major-version upgrade.

ProductRetention mechanismDanger
PostgreSQLReplication slots; wal_keep_size; max_slot_wal_keep_size; PostgreSQL 18+ idle_replication_slot_timeoutDisk full, VACUUM blocked
MySQLbinlog_expire_logs_seconds (default 30 days); no per-replica pinReplica that falls behind expiry gets error 1236 and needs re-provisioning
MongoDBFixed-size oplog (oplogSizeMB, minRetentionHours)Secondary that falls off the oplog needs initial sync
Kafka/Debezium consumers on PostgreSQLLogical slot per connectorSame as PostgreSQL

Fix / monitor:

sql
-- on the primary: alert when retained WAL grows or a slot is inactive
SELECT slot_name, slot_type, active, wal_status, safe_wal_size,
       pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained
FROM pg_replication_slots
ORDER BY pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn) DESC;

ALTER SYSTEM SET max_slot_wal_keep_size = '50GB';
SELECT pg_reload_conf();
SELECT pg_drop_replication_slot('replica_old');   -- only when the consumer is really gone

Hot standby and replay conflicts Must-know ​

In plain words: a hot standby answers read-only queries while it keeps replaying WAL. Sometimes replay must change data a running query still needs, and then either replay waits or the query is cancelled.

Common misunderstanding: "A read replica runs my long reports exactly like the primary." On the primary, VACUUM waits for your report's snapshot. On a standby, VACUUM already ran on the primary; when its cleanup record arrives, the standby must choose between delaying replay (lag grows) and cancelling your query.

Definition: hot_standby = on (default). A recovery conflict happens when replayed WAL removes row versions a standby query can still see (snapshot conflict), takes an ACCESS EXCLUSIVE lock it needs (lock conflict, e.g. DROP TABLE, TRUNCATE, some ALTER TABLE), drops a tablespace or database, or meets a buffer pin. The standby waits up to max_standby_streaming_delay (default 30s; max_standby_archive_delay for WAL from the archive), then cancels the query with ERROR: canceling statement due to conflict with recovery (SQLSTATE 40001). pg_stat_database_conflicts counts them by type. Remedies from the docs: hot_standby_feedback = on "prevents VACUUM from removing recently-dead rows and so cleanup conflicts do not occur", at the price that it "will delay cleanup of dead rows on the primary, which may result in undesirable table bloat"; or raise the delay (more lag); or run long reports on a dedicated replica with a large delay.

text
     Primary                                Hot standby
1                                           BEGIN; report SELECT ... (snapshot S, 5 min)
2    UPDATE orders ... (old versions dead)
3    VACUUM orders -> removes dead versions
4    WAL record "prune page 812" ─▶         replay needs to remove versions S can still see
5                                           replay waits ... max_standby_streaming_delay = 30s
6                                           ERROR:  canceling statement due to conflict with recovery
                                            DETAIL:  User query might have needed to see row versions that must be removed.
     -- with hot_standby_feedback = on: step 3 keeps the versions, the report finishes, the primary bloats a little

Real scenario: a nightly finance export on the replica fails every night at 30 seconds of conflict; a BI tool's 20-minute query is cancelled during peak write hours; a migration's ALTER TABLE on the primary cancels every standby query on that table.

ProductRead on a replica during replayConflict behaviour
PostgreSQLHot standbyCancel after max_standby_*_delay, or hot_standby_feedback (bloat on primary)
MySQL InnoDBReplica is a normal server (super_read_only = ON)No cancellation; long reads block purge on the replica, applier waits on metadata locks
SQL ServerReadable secondary (snapshot isolation mapped)Version store on the secondary; redo can be blocked by schema locks
OracleActive Data Guard (licensed option)Real-time query with consistent reads from undo
MongoDBreadPreference: secondaryNo cancellation; reads see the secondary's applied oplog point

Fix: keep OLTP replicas with hot_standby_feedback = on and short queries; give reporting its own replica with max_standby_streaming_delay = -1 (wait forever, accept lag) and never fail over to it; retry 40001 from conflicts like a serialization failure (Laravel's lost-connection detector already lists "canceling statement due to conflict with recovery", see the Laravel retry note).

Synchronous replication: synchronous_commit and synchronous_standby_names Must-know ​

In plain words: with synchronous replication, the primary does not tell the client "committed" until one or more standbys confirm they have the commit. How far the standby must get is your choice.

Common misunderstanding: "Setting synchronous_commit = on makes replication synchronous." On its own, on only means "flush locally". Replication becomes synchronous only when synchronous_standby_names names at least one connected standby; then on means "wait for the standby's flush".

Definition: synchronous_commit "Specifies how much WAL processing must complete before the database server returns a “success” indication to the client. Valid values are remote_apply, on (the default), remote_write, local, and off." It can be set per session or per transaction (SET LOCAL synchronous_commit = remote_apply). synchronous_standby_names chooses the standbys by their application_name (from primary_conninfo or cluster_name):

  • FIRST n (s1, s2, s3): priority-based; wait for the first n connected standbys in list order. A bare list s1, s2 means FIRST 1 (s1, s2).
  • ANY n (s1, s2, s3): quorum-based; "makes transaction commits wait until their WAL records are replicated to at least num_sync listed standbys".
  • * matches any standby name.

The sync_state column of pg_stat_replication shows sync, potential (next in line for FIRST), quorum (candidate for ANY) or async. If too few synchronous standbys are connected, commits wait indefinitely; cancelling the wait produces a warning, not a rollback (see the timeline).

ClientPrimarySync standbyCOMMIT1. WAL flushedon primary (fsync)walsender streams2. written to OS3. flushed to disk4. replayed (visible)async / localremote_writeon (default)remote_applyAsync: the client got OK at step 1. If the primarydies before step 3, the promoted standby lacks it:RPO = replication lag. remote_write survives aprimary crash, not a standby OS crash.off: returns beforeeven step 1 (up to3 x wal_writer_delayof commits at risk)
text
     Client                Primary (synchronous_standby_names = 's1')          Standby s1
1    INSERT ...; COMMIT;   WAL flushed locally
2                          waits for s1 flush ...                              (s1 is down)
3    ^C (cancel)
4    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.
5    -- the row IS committed on the primary; the client saw a warning, not an error
6    -- a failover to s1 now would lose it: "synchronous" was never guaranteed for this row

Real scenario: a payments ledger with ANY 1 (az_b, az_c) so losing one zone neither loses data nor blocks writes; a single sync standby that took the site down when it was rebooted for patching; remote_apply on the "change password" transaction so the next login, served by a replica, sees the new hash; synchronous_commit = off for a high-volume clickstream table where losing the last 600ms is fine.

ProductSynchronous optionWaits forFailure mode
PostgreSQLsynchronous_standby_names + synchronous_commitwrite / flush / apply on FIRST or ANY n standbysCommits hang if too few sync standbys
MySQLSemisynchronous replication (rpl_semi_sync_source_wait_point = AFTER_SYNC)Replica received and logged the events (relay log)Falls back to async after rpl_semi_sync_source_timeout (10s)
MySQL Group ReplicationConsensus on every transactionMajority of the group certified itMinority partition blocks
MongoDBWrite concern w: "majority" (default) + j: trueMajority of voting members wrote it to their oplogwtimeout error, write may still apply
SQL Server AGSynchronous-commit availability modeSecondary hardened the logSecondary drops to not-synchronized after session timeout
Oracle Data GuardMaximum Availability / Maximum ProtectionStandby redo log writtenProtection mode stops the primary if no standby
RedisWAIT numreplicas timeoutReplicas acknowledged the write streamNot a durability guarantee (async persistence)

Configuration:

sql
-- quorum: commit when any 1 of 2 zone replicas has flushed
ALTER SYSTEM SET synchronous_standby_names = 'ANY 1 (az_b, az_c)';
SELECT pg_reload_conf();

-- per transaction: stronger for the critical write, weaker for the bulk write
BEGIN; SET LOCAL synchronous_commit = remote_apply; UPDATE users SET password_hash = $1 WHERE id = $2; COMMIT;
BEGIN; SET LOCAL synchronous_commit = local;        INSERT INTO page_views ...;                     COMMIT;

SELECT application_name, sync_state, sync_priority FROM pg_stat_replication;

Cascading replication Good to know ​

In plain words: a standby that receives WAL can itself send it to further standbys, so the primary feeds one remote copy instead of many.

Common misunderstanding: "A cascaded standby can be synchronous." In PostgreSQL synchronous replication applies only to standbys directly connected to the primary; cascaded standbys are always asynchronous and lag at least as much as their upstream.

Definition: set primary_conninfo on the downstream standby to point at an upstream standby; the upstream needs max_wal_senders and pg_hba.conf entries like a primary. The docs: "When cascading replication ... is used, standby servers can also be senders, as well as receivers." After a promotion, downstream standbys follow the new timeline automatically when recovery_target_timeline = 'latest' (the default).

text
1    Primary (Frankfurt) ─▶ Standby A (Dublin)              -- one WAN stream
2                            Standby A ─▶ Standby B (Dublin)  -- LAN
3                            Standby A ─▶ Standby C (Dublin)  -- LAN
4    replay_lsn(B) <= replay_lsn(A) <= primary current LSN

Real scenario: a DR region with three replicas fed over one cross-region link; offloading many read replicas from a busy primary's walsender CPU and bandwidth; MySQL and Redis do the same with chained replicas (log_replica_updates = ON in MySQL, the default).

Delayed replicas Good to know ​

In plain words: a standby that applies changes N hours late, so when someone runs a bad DELETE, you still have a copy from before it.

Common misunderstanding: "A delayed replica replaces backups." It covers only the window of its delay and only if someone notices in time; it does not cover corruption that was already present.

Definition: recovery_min_apply_delay (PostgreSQL) delays applying each commit record until its commit time plus the delay; WAL is still received and flushed immediately, so it is safe. The docs warn that hot_standby_feedback "will be delayed by use of this feature which could lead to bloat on the primary". To recover: pause replay (pg_wal_replay_pause()), set recovery_target_time before the mistake, restart, then extract the rows. MySQL: CHANGE REPLICATION SOURCE TO SOURCE_DELAY = 14400.

text
1    10:00  primary: DELETE FROM invoices;  -- missing WHERE, committed
2    10:00  normal replicas: invoices empty within 50 ms
3    10:00  delayed replica (4h): still has all invoices until 14:00
4    10:20  on-call: SELECT pg_wal_replay_pause();  on the delayed replica
5    10:30  COPY invoices TO ...  -> restore into the primary

Real scenario: protection against a broken migration or an operator mistake in a database whose PITR restore takes many hours; must never be a failover candidate (Patroni: nofailover: true tag).

Logical replication Important ​

In plain words: instead of copying bytes, the primary decodes its WAL into "insert this row, update that row" for chosen tables, and a subscriber applies those changes with normal SQL. The subscriber is a normal read-write database.

Common misunderstanding: "Logical replication is a drop-in HA standby." Its documented restrictions say "The database schema and DDL commands are not replicated" and "Incremental sequence changes are not replicated"; large objects are not replicated either. Failing over to a subscriber needs schema already in place, sequences advanced, and slots handled.

Definition: wal_level = logical on the publisher. A publication (CREATE PUBLICATION ... FOR TABLE t1, t2 or FOR ALL TABLES, with row filters and column lists since PostgreSQL 15) defines what is sent. A subscription (CREATE SUBSCRIPTION ... CONNECTION '...' PUBLICATION ...) creates a logical slot on the publisher, copies initial data (copy_data = true), then streams changes using the pgoutput plugin. UPDATE and DELETE need a replica identity to find the row on the subscriber: the primary key by default, or REPLICA IDENTITY USING INDEX, or FULL (whole old row, slow); a table without one that publishes updates rejects them with ERROR: cannot update table "t" because it does not have a replica identity and publishes updates. Since PostgreSQL 16, the subscription option origin = none sends only changes that did not themselves come from replication, which makes bidirectional (two-way, multi-master-style) setups possible without loops; there is still no automatic conflict resolution, so writers must not touch the same rows. PostgreSQL 17 added failover = true to keep a subscription's slot synchronised to physical standbys; the current docs (19) add ALTER SUBSCRIPTION ... REFRESH SEQUENCES (publisher 19+) to re-sync sequences before a switchover.

text
     Publisher (PG 15)                           Subscriber (PG 17)
1    CREATE PUBLICATION app FOR ALL TABLES;
2                                                CREATE SUBSCRIPTION app_sub CONNECTION 'host=old ...' PUBLICATION app;
3    logical slot app_sub created; initial COPY of each table ─▶
4    INSERT INTO orders ... COMMIT ─▶            apply worker: INSERT INTO orders ...
5    ALTER TABLE orders ADD COLUMN note text;    -- NOT replicated
6    UPDATE orders SET note = 'x' ...  ─▶        ERROR: logical replication target relation "public.orders" is missing replicated column: "note"
                                                 -- apply worker retries in a loop until you add the column on the subscriber

Real scenario: a zero-downtime major-version upgrade (subscribe the new version, cut over, done); copying a few tables to an analytics database; consolidating many tenant databases into one; feeding Debezium/Kafka through a logical slot (Change Data Capture); two regions each writing their own rows with origin = none.

NeedPhysical streamingLogical replication
Whole cluster, byte-identicalYesNo (per table)
Different major versions / platformsNoYes
Subscriber writableNo (read-only)Yes
DDL replicatedYes (it is just WAL)No
SequencesYesNot incrementally; REFRESH SEQUENCES (19) or manual setval
Failover targetYes, the standardPossible after preparation
Overhead on the sourceLowDecoding CPU, wal_level = logical, replica identity

Configuration:

sql
-- publisher
ALTER SYSTEM SET wal_level = logical;              -- restart required
CREATE PUBLICATION app FOR TABLE orders, customers WHERE (region = 'eu');  -- row filter needs PG 15+
-- subscriber (schema created first, e.g. pg_dump --schema-only)
CREATE SUBSCRIPTION app_sub
  CONNECTION 'host=pub dbname=shop user=repl password=...'
  PUBLICATION app
  WITH (copy_data = true, origin = none, disable_on_error = true, failover = true);
SELECT subname, received_lsn, latest_end_lsn, last_msg_receipt_time FROM pg_stat_subscription;
-- skip one failing transaction (PG 15+), LSN from the subscriber log:
ALTER SUBSCRIPTION app_sub SKIP (lsn = '0/14C0378');

Failover, one concept at a time ​

Promotion itself is one function call: "To trigger failover of a log-shipping standby server, run pg_ctl promote or call pg_promote()." Everything else in this section is about doing it safely.

Promotion and timelines Must-know ​

In plain words: promotion ends replay, makes the standby writable, and starts a new numbered history (timeline) so that its future WAL can never be confused with the old primary's.

Common misunderstanding: "After failover I can restart the old primary as a replica of the new one." The old primary may have written WAL that never reached the new primary; its history has forked. It must be rewound (pg_rewind) or rebuilt first, otherwise it refuses to follow or, worse, a manual hack produces silent corruption.

Definition: pg_promote(wait => true, wait_seconds => 60) or pg_ctl promote removes standby.signal, replays what has been received (it does not fetch more), writes an end-of-recovery checkpoint, and switches to timeline N+1. It writes a history file 0000000N+1.history recording the switch point LSN. WAL segment names start with the timeline (00000002...). Standbys and archive recovery follow the newest timeline when recovery_target_timeline = 'latest' (default since PostgreSQL 12).

text
     Old primary A (TLI 1)                      Standby B (TLI 1)
1    writes up to 0/9000100                     replayed up to 0/9000000 (async lag 256 bytes)
2    A crashes
3                                               SELECT pg_promote();   -> TLI 2, switch point 0/9000000
4                                               00000002.history: "1  0/9000000  no recovery target specified"
5    A restarts: its WAL 0/9000000..0/9000100 on TLI 1 exists nowhere else  -- the lost tail = RPO
6    A must run pg_rewind against B before it can follow TLI 2

Real scenario: an AZ outage promotes the replica and the last 300ms of orders are gone (async); a standby that followed an archive with two timelines picked the wrong one before latest became the default; SELECT timeline_id FROM pg_control_checkpoint() used in runbooks to confirm which node is on the new history.

Failover vs switchover Must-know ​

In plain words: failover is the emergency (the primary is gone, promote someone now); switchover is the planned swap (stop writes, let the standby catch up fully, swap roles, lose nothing).

Common misunderstanding: "A switchover is just a failover I trigger myself." A switchover first demotes the primary cleanly and waits until the target has replayed everything, so RPO is zero even with async replication, and the old primary can rejoin without pg_rewind. A forced failover skips both steps.

Definition: switchover = clean shutdown of the primary (its final WAL is sent to standbys on shutdown) → confirm target replay_lsn equals the old primary's last LSN → promote → reconfigure others. Patroni: patronictl switchover --candidate node2 --scheduled 2026-12-01T03:00; repmgr: repmgr standby switchover; RDS: "reboot with failover"; MySQL InnoDB Cluster: cluster.setPrimaryInstance().

text
     Switchover (planned)                          Failover (unplanned)
1    pause writers / drain pool                     primary unreachable
2    stop primary cleanly (final WAL sent)          wait for TTL / failure detection (seconds)
3    target replay_lsn == old last LSN              pick most advanced standby; maybe lose the tail
4    promote target                                 fence old primary, promote
5    old primary starts as standby (same history)   old primary needs pg_rewind or re-clone
     RPO = 0, RTO = seconds                         RPO = lag (async), RTO = detection + promotion + routing

Real scenario: monthly kernel patching by switching over to each replica in turn; a major cloud's maintenance event that triggers a switchover you did not schedule; rehearsing failover quarterly by doing switchovers in production hours.

Split brain and fencing (STONITH) Must-know ​

In plain words: split brain is two servers both believing they are the primary and both accepting writes. Fencing is whatever guarantees the old one cannot write any more before the new one starts.

Common misunderstanding: "If the old primary is unreachable, it is dead." Unreachable from the monitor is not the same as unreachable from the application. A network partition can leave the old primary happily serving the app servers in its own zone.

Definition: the PostgreSQL docs: "you must have a mechanism for informing the old primary that it is no longer the primary. This is sometimes known as STONITH (Shoot The Other Node In The Head), which is necessary to avoid situations where both systems think they are the primary, which will lead to confusion and ultimately data loss." Fencing methods: power off through an IPMI/cloud API, revoke the old node's storage or security-group access, remove it from the load balancer, a hardware or software watchdog that reboots the node if its HA agent stops renewing, or self-fencing (the node demotes itself when it loses the leader lock). The decision itself must come from a single authority, typically a leader lock in a consensus store (etcd, Consul, ZooKeeper, Kubernetes API) that needs a majority, so a minority side can never elect a second leader.

etcd (DCS)Node ANode BHAProxyClients1 renew leader key(ttl 30s, every loop_wait 10s)2 A partitioned:cannot reach etcd3 FENCE: A demotes itselfor watchdog reboots it4 key expires (no renewal)5 B: highest LSN, lagunder maximum_lag_on_failover6 pg_promote()timeline 1 to 2GET /primary7 200 from B, 503 from A8 reconnect,retry writes9 A: pg_rewind to B,rejoin as replica
text
     Zone A                                         Zone B
1    Primary A + app servers A                      Standby B + app servers B + etcd majority
2    ── network partition between zones ──
3    A cannot renew leader key; Patroni on A demotes A to read-only after ttl
4    (without Patroni: A keeps accepting writes from app servers A)
5                                                   key expires; B takes the key and promotes
6    app servers A get: ERROR: cannot execute INSERT in a read-only transaction (25006) -> retry via HAProxy -> B
     -- without step 3, orders written to A after step 2 conflict with orders written to B: split brain

Real scenario: a two-node setup with a "ping the other node" script that promoted the standby during a switch reboot while the primary stayed up; an Orchestrator-managed MySQL cluster where the old source was not set read_only and kept taking writes for 40 seconds; a VM pause (live migration, long GC-like stall) longer than the TTL: when it resumes it must notice it lost the lock before writing.

ToolSingle authorityFencing
PatroniLeader key in etcd/Consul/ZooKeeper/Kubernetes with TTLSelf-demotion when the key cannot be renewed; optional Linux watchdog (/dev/watchdog)
repmgrrepmgrd voting + optional witness nodeUser-supplied scripts; no built-in DCS
pgpool-IIIts watchdog quorumfailover_command scripts; virtual IP
Pacemaker + CorosyncCluster quorumReal STONITH devices (IPMI, cloud fencing agents)
MySQL InnoDB ClusterGroup Replication majorityMinority members become unable to write; Router stops sending
MongoDB replica setRaft-style election, majorityOld primary steps down when it cannot see a majority
RDS / AuroraAWS control planeManaged; DNS endpoint moves

pg_rewind: bringing the old primary back Important ​

In plain words: instead of copying the whole database again, pg_rewind copies only the blocks the old primary changed after the fork from the new primary, so it can follow the new timeline.

Common misunderstanding: "pg_rewind merges the lost writes." It throws them away. The writes the old primary made after the divergence point are gone (save them first if they matter, for example by dumping from the old primary before rewinding).

Definition: the docs: "pg_rewind is a tool for synchronizing a PostgreSQL cluster with another copy of the same cluster, after the clusters' timelines have diverged. A typical scenario is to bring an old primary server back online after failover as a standby that follows the new primary." It needs the target stopped cleanly, and "requires that the target server either has the wal_log_hints option enabled in postgresql.conf or data checksums enabled when the cluster was initialized with initdb (the default)". It needs the target's WAL back to the divergence point (--restore-target-wal fetches it from the archive). -R writes standby.signal and primary_conninfo pointing at the source.

text
1    new primary B on TLI 2; old primary A stopped (clean shutdown)
2    pg_rewind --target-pgdata=/data/A --source-server='host=B user=postgres' -R --progress
3    pg_rewind: servers diverged at WAL location 0/9000000 on timeline 1
4    pg_rewind: rewinding from last common checkpoint at 0/8000060 on timeline 1
5    pg_rewind: Done!
6    start A -> it replays from B on TLI 2 as a standby

Real scenario: Patroni with use_pg_rewind: true does this automatically for the old leader; repmgr node rejoin --force-rewind; a 2 TB cluster that rejoins in two minutes instead of a six-hour pg_basebackup.

HA managers and routing ​

Patroni, etcd and the leader lock Must-know ​

In plain words: Patroni runs next to each PostgreSQL node, keeps one "leader" key in a consensus store, and only the node holding that key may be primary. Everything else (promotion, demotion, rewinding, configuration) follows from who holds the key.

Common misunderstanding: "Two Patroni nodes are enough for HA." Patroni can be two PostgreSQL nodes, but the consensus store (etcd) needs three or more members in separate failure domains, or a partition can leave no majority and no leader.

Definition: each Patroni agent runs an HA loop every loop_wait (10s). The leader updates its key with TTL ttl (30s); per the Patroni docs on multi-site setups, a node acts as "leader only when it owns the leading key and can update the leading key". If the leader cannot update the key within retry_timeout, it demotes itself. When the key expires, healthy replicas race for it; a replica whose lag exceeds maximum_lag_on_failover (default 1MB) does not take part. Patroni "is asynchronous by default"; synchronous_mode: true makes it manage synchronous_standby_names and promote only a synchronous standby (synchronous_mode_strict blocks writes instead of falling back to async when none is available). Its REST API on port 8008 answers GET /primary with 200 only on the leader and GET /replica with 200 on healthy replicas, which load balancers use as health checks. patronictl list, switchover, failover, edit-config are the operator commands. Tags: nofailover, noloadbalance, clonefrom, replicatefrom (cascading).

text
     t=0     A holds /service/shop/leader (ttl 30s), renews every 10s
     t=12    A loses etcd; retries
     t=22    retry_timeout passed: A demotes itself to read-only (self-fencing)
     t=30+   key expires; B (lag 120 KB < 1 MB) and C (lag 9 MB) see no leader; C excluded
     t=31    B writes the key (etcd compare-and-swap), pg_promote(), TLI 2
     t=33    HAProxy check GET /primary: B 200, A 503 -> traffic to B
     t=40    A reachable again: Patroni runs pg_rewind, A follows B

Real scenario: the standard Kubernetes operators (Zalando postgres-operator, Crunchy PGO) and many VM fleets run Patroni; a three-node etcd across three zones with PostgreSQL in two; maximum_lag_on_failover set so a replica 2 GB behind after a long VACUUM FULL is never promoted.

repmgr, pgpool-II and the others Important ​

In plain words: they are other ways to answer "who is primary" and "where do I send this query". They differ in whether they have a real consensus authority and whether they sit in the query path.

Common misunderstanding: "pgpool-II is just a connection pooler." It also parses SQL to load-balance reads, can run failover scripts and manage a virtual IP. That power is also complexity; many teams use PgBouncer for pooling and Patroni for failover instead.

Definition and comparison:

ToolWhat it isFailure detection / authorityIn the query path?
PatroniHA template managing PostgreSQL via a DCSetcd/Consul/ZooKeeper/Kubernetes leader keyNo (HAProxy/PgBouncer in front)
repmgrReplication setup + repmgrd failover daemonNode voting, optional witness server, location awarenessNo
pgpool-IIMiddleware: pooling, read load balancing, failover, watchdog VIPIts own watchdog quorumYes
pg_auto_failoverMonitor node + keepersA single monitor (itself a SPOF unless replicated)No
StolonKeeper/sentinel/proxy on a DCSetcd/Consul/KubernetesYes (stolon-proxy)
CloudNativePGKubernetes operatorKubernetes API (leases)No (Services)
Orchestrator (MySQL)Topology discovery and recoveryRaft among orchestrator nodes (optional)No
MySQL RouterRouter for InnoDB Cluster / ReplicaSetReads Group Replication metadataYes (ports 6446 RW / 6447 RO)
text
1    pgpool-II receives SELECT ... -> sends to a replica (load balance)
2    pgpool-II receives UPDATE ...  -> sends to primary; with disable_load_balance_on_write = transaction, later SELECTs in that transaction go to the primary
3    primary health check fails x N -> failover_command promote.sh, VIP moves

Client routing: HAProxy, PgBouncer, DNS, VIP, multi-host connection strings Must-know ​

In plain words: after promotion, every client must start talking to the new primary. Something has to tell them, and existing connections to the old primary must die.

Common misunderstanding: "We use DNS, so failover is automatic." DNS caches (resolver TTLs, the JVM's own cache, connection pools that never re-resolve) can keep clients on the old address for minutes. And long-lived pooled connections never re-resolve anyway until they are closed.

Definition: the options, from simplest to most robust:

MethodHow it movesTypical delayGotchas
DNS name with low TTLUpdate the record on failover (RDS endpoints do this)TTL + client cachingPools hold old connections; negative caching; resolver ignoring TTL
Virtual IP (keepalived/VRRP, pgpool watchdog, cloud secondary IP)IP moves to the new nodeSecondsSame L2 network or cloud API; ARP caches
HAProxy with Patroni health checksoption httpchk GET /primary, http-check expect status 200 on port 8008Check interval × fall count (e.g. 3 × 1s)HAProxy itself needs HA (two + VIP); set on-marked-down shutdown-sessions to cut old sessions
PgBouncer pointed at HAProxy/VIPReconnects when server connections fail; PAUSE/RESUME for switchoversSecondsTransaction pooling breaks session state; server_check_query
libpq / pgx multi-host DSNhost=a,b,c target_session_attrs=read-write tries each host until one accepts writesConnect time per hostOnly at connect time; existing connections still need to fail
MySQL Router / ProxySQLReads cluster metadata or checks read_onlySecondsAnother tier to run
Driver-level discovery (MongoDB drivers, Aurora/RDS JDBC wrapper)Driver monitors topologyElection time + driver heartbeatMust retry the failed operation
text
     App (PgBouncer)            HAProxy (5000 = RW, 5001 = RO)          Node A / Node B
1    pool → 5000                checks A: /primary 200 → A is backend
2                                                                        A demoted, B promoted
3                               checks A: 503 ×3 → A down, sessions shut down; B: 200 → B up
4    server conn error → PgBouncer reconnects → 5000 → B
5    app sees one failed query per in-flight transaction → retries (idempotent)
ini
# haproxy.cfg excerpt (from the Patroni example pattern)
listen primary
    bind *:5000
    option httpchk OPTIONS /primary
    http-check expect status 200
    default-server inter 1s fall 3 rise 2 on-marked-down shutdown-sessions
    server node1 10.0.0.11:5432 maxconn 100 check port 8008
    server node2 10.0.0.12:5432 maxconn 100 check port 8008
listen replicas
    bind *:5001
    balance roundrobin
    option httpchk OPTIONS /replica
    http-check expect status 200
    default-server inter 1s fall 3 rise 2
    server node1 10.0.0.11:5432 check port 8008
    server node2 10.0.0.12:5432 check port 8008

Reading from replicas ​

A replica shows the primary's data as of replay_lsn. Every anomaly below is that one fact meeting a user.

Read-your-writes (read-after-write consistency) Must-know ​

In plain words: after I save something, I must see it on the next page. With replicas, my save went to the primary and my next read went to a replica that has not replayed it yet.

Common misunderstanding: "Replica lag is milliseconds, nobody will notice." Lag is milliseconds on average and seconds-to-minutes at the tail: a bulk import, a long ALTER TABLE replaying, a vacuum conflict pausing replay. Users notice the tail, and they click "save" again (duplicate orders, duplicate tickets).

Definition: read-your-writes guarantees that a client's reads reflect all of that client's previous writes. It is a per-client guarantee; other users may still see stale data. Implementations: (1) time-window pinning (route a user's reads to the primary for N seconds after a write; Laravel's sticky within a request and PreventStaleDatabaseReads across requests); (2) LSN/GTID token (remember the primary's WAL position after the write; read from a replica only once its pg_last_wal_replay_lsn() has passed it, else wait briefly or use the primary; MySQL: WAIT_FOR_EXECUTED_GTID_SET(gtid_set, timeout); MongoDB: causally consistent sessions); (3) synchronous_commit = remote_apply for that transaction, which makes the write visible on synchronous standbys before COMMIT returns.

text
     User browser          App                    Primary            Replica (lag 900 ms)
1    POST /profile  ─▶     UPDATE users ...  ─▶   COMMIT (0/7A0)
2    302 → GET /profile ─▶ SELECT ... (read conn) ──────────────────▶ replay_lsn 0/790  -> OLD name
3    "my change is gone!" → clicks save again
     -- fix (LSN token): step 1 stores lsn 0/7A0 in the session;
     -- step 2 asks replica "replay_lsn >= 0/7A0?" -> no -> reads from primary -> NEW name

Real scenario: profile edits; "your order has been placed" pages that list orders from a replica; an admin who disables a user and still sees them active; an API client that POSTs and immediately GETs the resource and receives 404.

Product / frameworkBuilt-in read-your-writes
PostgreSQLNo routing; primitives: pg_last_wal_replay_lsn(), remote_apply; PostgreSQL 19 does not route reads itself
MySQLWAIT_FOR_EXECUTED_GTID_SET; Group Replication group_replication_consistency = AFTER/BEFORE; ProxySQL GTID-aware routing
MongoDBCausally consistent client sessions with readConcern: "majority" and writeConcern: "majority"
AuroraReplicas share storage; lag "usually much less than 100 milliseconds", still not zero
Laravel'sticky' => true (same request); PreventStaleDatabaseReads middleware (same session, time window)
Go database/sqlNone; route yourself (Go solution)

Fix: see Stale read after write for SQL, Go and Laravel.

Monotonic reads and consistent prefix Important ​

In plain words: monotonic reads means time never goes backwards for me: once I have seen a comment, a refresh must not make it disappear. That happens when two requests hit two replicas with different lag.

Common misunderstanding: "Read-your-writes covers this." It covers only your own writes. Monotonic reads is about everyone's writes you have already seen.

Definition: monotonic reads: if a client read a value at position X, its later reads are from position ≥ X. Implementations: sticky sessions to one replica (hash the user ID to a replica; fall back to the primary if it fails), or carry the highest LSN you have seen and require replicas to be past it (same token as read-your-writes, updated on reads too). Consistent prefix (reads see writes in the order they happened) holds automatically on a single PostgreSQL or MySQL replica because replay is in commit order; it breaks across shards or with multi-threaded appliers that do not preserve order (MySQL replica_preserve_commit_order = ON, the default since 8.0.27, keeps it).

text
     User                 Replica R1 (lag 0.1 s)      Replica R2 (lag 5 s)
1    GET /thread  ─▶      sees comments 1..10
2    GET /thread (refresh) ─────────────────────────▶ sees comments 1..7   -- 3 comments "vanished"
     -- fix: hash(user_id) -> R1 always; or token "seen up to LSN of R1's replay" checked on R2

Real scenario: a chat app where messages flicker; a ticket status that goes from "closed" back to "open" on refresh; pagination across replicas that duplicates or skips rows.

Measuring replication lag Must-know ​

In plain words: lag can be measured in bytes (how much WAL the replica has not applied) or in time (how old the replica's newest visible data is). Both lie in different situations.

Common misunderstanding: "now() - pg_last_xact_replay_timestamp() is the lag." On an idle primary no new transactions arrive, so this number grows forever even though the replica is fully caught up. Conversely, byte lag says nothing about how long replay of those bytes will take.

Definition: the docs give the byte recipe: compare "the current WAL write location on the primary with the last WAL location received by the standby". On the primary, pg_stat_replication shows sent_lsn, write_lsn, flush_lsn, replay_lsn and the time columns write_lag, flush_lag, replay_lag; for an async standby replay_lag "approximates the delay before recent transactions became visible to queries". On the standby, pg_last_wal_receive_lsn(), pg_last_wal_replay_lsn(), pg_last_xact_replay_timestamp(), pg_is_wal_replay_paused() and the pg_stat_wal_receiver view; "a large difference between pg_last_wal_replay_lsn and ... flushed_lsn indicates that WAL is being received faster than it can be replayed". MySQL: SHOW REPLICA STATUS → Seconds_Behind_Source (based on event timestamps; misleading with parallel appliers and after idle periods), better the Performance Schema replication_applier_status_by_worker timestamps or a heartbeat table (pt-heartbeat). MongoDB: rs.printSecondaryReplicationInfo().

text
     Gap                                   Meaning                                     Typical cause
1    current_wal_lsn - sent_lsn            primary cannot send fast enough               walsender CPU, network
2    sent_lsn - flush_lsn                  network / standby disk                        WAN latency, slow standby disk
3    flush_lsn - replay_lsn                standby replay behind                         single-threaded replay, recovery conflict wait, replay paused
4    now() - pg_last_xact_replay_timestamp() age of newest visible commit                 real lag OR an idle primary

Real scenario: a dashboard alert on replay_lag > 30s that never fired because the replica was disconnected (no row in pg_stat_replication at all); a heartbeat table updated every second by a cron job so time-lag is meaningful even when idle; byte lag spiking during CREATE INDEX replay.

SQL:

sql
-- on the primary: one row per connected standby
SELECT application_name, client_addr, state, sync_state,
       pg_wal_lsn_diff(pg_current_wal_lsn(), sent_lsn)   AS send_backlog_bytes,
       pg_wal_lsn_diff(sent_lsn, flush_lsn)              AS network_backlog_bytes,
       pg_wal_lsn_diff(flush_lsn, replay_lsn)            AS replay_backlog_bytes,
       write_lag, flush_lag, replay_lag
FROM pg_stat_replication;

-- on the standby: idle-safe time lag
SELECT CASE WHEN pg_last_wal_receive_lsn() = pg_last_wal_replay_lsn() THEN 0
            ELSE extract(epoch FROM now() - pg_last_xact_replay_timestamp()) END AS lag_seconds,
       pg_is_wal_replay_paused() AS paused;

RPO and RTO under asynchronous replication Must-know ​

In plain words: RPO is how much recent data you can lose; RTO is how long you can be down. Asynchronous replication sets RPO to "whatever the lag was at the moment of failure", and failover machinery sets RTO.

Common misunderstanding: "Our lag is 50ms, so our RPO is 50ms." RPO is set by the worst lag at the worst moment, typically during the incident that caused the failover (a saturated disk, a network brown-out). Patroni's maximum_lag_on_failover is the honest version: a stated bound beyond which you prefer downtime to data loss.

Definition: RPO (Recovery Point Objective) = maximum acceptable data loss measured in time. RTO (Recovery Time Objective) = maximum acceptable time to restore service. With async: RPO ≈ replay lag at failure (unreceived WAL is lost; received-but-unreplayed WAL is kept, because promotion replays it). With quorum sync and a manager that promotes only a synchronous standby: RPO = 0. RTO = failure detection (Patroni TTL ~30s; MongoDB median election "should not typically exceed 12 seconds"; RDS DNS flip) + promotion (seconds) + routing (health check interval, DNS TTL) + application reconnect and warm-up.

SetupRPORTO (typical order)
Async streaming + manual failoverLag at failure (ms to minutes)Minutes to hours (a human)
Async + Patroni, maximum_lag_on_failover = 1MB≤ ~1MB of WAL, or no failover~30–60 s
Patroni synchronous_mode / quorum sync0~30–60 s
RDS Multi-AZ instance (synchronous standby)0DNS failover, typically one to two minutes
Aurora (shared storage)0 for committed dataReplica promotion, usually under a minute
Delayed replica / PITRUp to the target time you chooseHours (restore + replay)

Per-engine behaviour ​

MySQL: binlog, formats, GTID, semi-sync, Group Replication Important ​

In plain words: the MySQL source writes every committed transaction to its binary log; each replica's I/O (receiver) thread copies it into a relay log, and applier (SQL) threads execute it.

Common misunderstanding: "Statement-based replication is fine because it is smaller." Non-deterministic statements (UUID(), NOW() in some forms, LIMIT without ORDER BY, triggers) can produce different data on the replica. Row-based is the default for a reason.

Definition:

  • Binlog formats (binlog_format): ROW (default; the changed rows), STATEMENT (the SQL text), MIXED (the docs: "a statement-based log is used by default" and switched "to row-based in particular cases"). binlog_row_image = FULL|MINIMAL|NOBLOB. binlog_format is deprecated as a variable in recent 8.x but still controls behaviour.
  • GTID (gtid_mode = ON, enforce_gtid_consistency = ON): each transaction gets source_uuid:sequence; replicas track gtid_executed, and CHANGE REPLICATION SOURCE TO ... SOURCE_AUTO_POSITION = 1 lets any replica follow any new source without file/position math. The manual says GTIDs "greatly simplify" "failing over to a new source".
  • Semisynchronous (plugins rpl_semi_sync_source / rpl_semi_sync_replica): "The source waits until at least one replica has received and logged the events (the required number of replicas is configurable), and then commits the transaction." rpl_semi_sync_source_wait_point = AFTER_SYNC (default, "lossless": other sessions do not see the commit before a replica has it) vs AFTER_COMMIT. If no ack within rpl_semi_sync_source_timeout (10000ms), it silently falls back to async. The manual also warns that after a crash "the failed source should not be reused as the replication source, and should be discarded".
  • Parallel apply: replica_parallel_workers (default 4 in 8.4), replica_preserve_commit_order = ON.
  • Group Replication (single-primary mode by default; multi-primary optional): members certify each transaction through a Paxos-based group communication system; a minority cannot commit. group_replication_consistency (EVENTUAL, BEFORE_ON_PRIMARY_FAILOVER, BEFORE, AFTER, BEFORE_AND_AFTER) controls read-your-writes across members. InnoDB Cluster = Group Replication + MySQL Shell (AdminAPI) + MySQL Router (RW port 6446, RO port 6447). InnoDB ReplicaSet = the async version managed the same way. Older stacks: MHA, Orchestrator, ProxySQL.
  • Read-only fencing: super_read_only = ON on replicas; a write fails with error 1290: "The MySQL server is running with the --super-read-only option so it cannot execute this statement".
text
     Source                                   Replica
1    COMMIT -> binlog event GTID 3E11FA47...:1042  (AFTER_SYNC: wait for ack here)
2                                             receiver thread -> relay log, ack (semi-sync)
3    commit visible to other sessions
4                                             applier worker executes rows; gtid_executed += :1042
5    failover: new source chosen by highest gtid_executed; others: SOURCE_AUTO_POSITION = 1
sql
-- MySQL 8.4 replica setup with GTID
CHANGE REPLICATION SOURCE TO SOURCE_HOST = 'db1', SOURCE_USER = 'repl', SOURCE_PASSWORD = '...',
  SOURCE_AUTO_POSITION = 1, SOURCE_SSL = 1;
START REPLICA;
SHOW REPLICA STATUS\G                         -- Replica_IO_Running, Replica_SQL_Running, Seconds_Behind_Source
SELECT WAIT_FOR_EXECUTED_GTID_SET('3E11FA47-71CA-11E1-9E33-C80AA9429562:1-1042', 1);  -- 0 = caught up, 1 = timeout

MongoDB replica sets, by comparison Good to know ​

MongoDB builds failover into the database. A replica set has one primary and secondaries that tail its oplog. "Replica sets use elections to determine which set member becomes primary"; the median election "should not typically exceed 12 seconds, assuming default replica configuration settings" (electionTimeoutMillis, default 10s). Write concern decides durability: w: 1 returns after the primary; w: "majority" "Requests acknowledgment that the calculated majority of data-bearing voting members have durably written the change to their local oplog", and "The default global write concern is majority". A write acknowledged only by w: 1 can be rolled back when a new primary is elected without it. Read side: readPreference (primary, primaryPreferred, secondary, secondaryPreferred, nearest, with maxStalenessSeconds), readConcern (local, majority, linearizable, snapshot), and causally consistent sessions give read-your-writes. Errors after an election: NotWritablePrimary and PrimarySteppedDown; drivers retry once with retryable writes (retryWrites=true, the default). Deep dive: MongoDB.

What each product really does ​

ProductReplication modelDefault sync levelBuilt-in failoverRead replicasNotes
PostgreSQLPhysical streaming (whole cluster) + logical (per table)AsyncNo (Patroni, repmgr, CloudNativePG)Hot standbyRecovery conflicts; slots; timelines; pg_rewind
MySQL / InnoDBBinlog (row) + GTID; Group ReplicationAsync; semi-sync optionalGroup Replication / InnoDB Cluster; otherwise OrchestratorNormal servers with super_read_onlySeconds_Behind_Source is unreliable
SQL ServerAlways On availability groupsSync or async per replicaYes (WSFC / Pacemaker on Linux)Readable secondariesListener name for routing; read-only routing via ApplicationIntent=ReadOnly
OracleData Guard (physical/logical standby), GoldenGateMax Performance (async) by defaultFast-Start Failover with an observerActive Data Guard (option)Protection modes: Performance, Availability, Protection
SQLiteNone built inn/aNoLitestream (stream WAL to S3), LiteFS (FUSE, single writer)Single writer by design
MongoDBReplica set, oplogw: "majority"Yes (elections)readPreferenceRollback of non-majority writes
CockroachDBRaft per range (consensus, not leader-follower)Majority (sync)Automatic per rangeFollower reads (AS OF SYSTEM TIME follower_read_timestamp())No "replica lag" in the usual sense; see Distributed SQL
RedisAsync replication (REPLICAOF)Async; WAIT per commandRedis Sentinel or Redis ClusterReplicas (READONLY in cluster)Acknowledged writes can be lost on failover
Amazon RDS Multi-AZ (instance)Synchronous standby in another AZSyncYes, DNS flipNo: "You can't use a standby replica to serve read traffic"Read replicas are separate, async
Amazon RDS Multi-AZ DB clusterTwo readable standbysSemi-syncYesYes (reader endpoint)MySQL and PostgreSQL
Amazon AuroraShared distributed storage volumeQuorum writes in storageYes, promotes a replicaUp to 15 replicas, lag "usually much less than 100 milliseconds"Not WAL streaming between instances
Google Cloud SQL / Azure Flexible ServerRegional disk / zone-redundant standbySyncYesSeparate read replicas (async)Managed; endpoints stay the same

Mechanics ​

Every PostgreSQL knob Must-know ​

ParameterWhereDefaultWhat it does
wal_levelprimaryreplicalogical needed for logical replication/decoding
max_wal_sendersprimary (and cascading standby)10Max concurrent walsender processes
max_replication_slotsprimary10Max slots
wal_keep_sizeprimary0Extra WAL kept for standbys without slots (replaced wal_keep_segments in 13)
max_slot_wal_keep_sizeprimary-1Cap on WAL retained by slots; slot is invalidated beyond it
idle_replication_slot_timeoutprimary0 (off)PostgreSQL 18+: invalidate slots idle this long
wal_sender_timeoutprimary60sDrop a standby connection that stopped responding
synchronous_standby_namesprimaryemptyWhich standbys are synchronous (FIRST/ANY)
synchronous_commitprimary, per transactiononHow far a commit must get before returning
wal_log_hintsprimaryoffNeeded by pg_rewind if data checksums are off
archive_mode, archive_command, archive_timeoutprimaryoffWAL shipping / PITR archive
primary_conninfostandbyemptyHow to reach the upstream
primary_slot_namestandbyemptyWhich slot to use upstream
restore_commandstandbyemptyFetch WAL from the archive
hot_standbystandbyonAllow read-only queries
hot_standby_feedbackstandbyoffSend xmin upstream to avoid cleanup conflicts
max_standby_streaming_delay / max_standby_archive_delaystandby30s / 30sWait before cancelling conflicting queries (-1 = forever)
wal_receiver_status_intervalstandby10sHow often positions are reported
wal_receiver_timeoutstandby60sReconnect if the primary is silent
recovery_min_apply_delaystandby0Delayed replica
recovery_target_timelinestandbylatestFollow promotions automatically
sync_replication_slotsstandbyoffPostgreSQL 17+: sync failover-enabled logical slots
cluster_nameanyemptyDefault application_name of the walreceiver
standby.signal / recovery.signalfile in data dir—Start as standby / as one-off archive recovery

Monitoring views and functions ​

WhereView / functionUse
Primarypg_stat_replicationOne row per walsender: LSNs, lags, sync_state
Primarypg_replication_slotsactive, restart_lsn, wal_status, safe_wal_size, inactive_since (17+)
Standbypg_stat_wal_receiverStatus of the walreceiver, flushed_lsn, latest_end_time
Standbypg_last_wal_receive_lsn(), pg_last_wal_replay_lsn(), pg_last_xact_replay_timestamp()Lag on the standby side
Standbypg_is_in_recovery()true on a standby (use in health checks)
Standbypg_stat_database_conflictsCancelled queries by conflict type
Standbypg_wal_replay_pause(), pg_wal_replay_resume(), pg_is_wal_replay_paused()Freeze replay (delayed replica recovery, lab)
Anypg_control_checkpoint()timeline_id of the latest checkpoint
Subscriberpg_stat_subscription, pg_stat_subscription_statsLogical apply progress, errors and conflict counts

Error messages you will see ​

Message (verbatim)SQLSTATE / codeWhereMeaning
canceling statement due to conflict with recovery40001 (most types)Standby queryReplay needed to remove/lock what your query uses
cannot execute INSERT in a read-only transaction25006Write sent to a standby or demoted primaryRouting points at a non-primary
the database system is starting up / ... is in recovery mode57P03Connect during startup/recoveryRetry after a delay
terminating connection due to administrator command57P01During shutdown or demotionReconnect and retry
canceling wait for synchronous replication due to user requestWARNINGPrimary, cancelled sync commitCommitted locally, maybe not replicated
requested WAL segment ... has already been removedstandby logStandby too far behind without slotRe-clone or use the archive
invalidating obsolete replication slot "..."LOGPrimarymax_slot_wal_keep_size exceeded
cannot update table "..." because it does not have a replica identity and publishes updates55000PublisherAdd a primary key or REPLICA IDENTITY
target server needs to use either data checksums or "wal_log_hints = on"pg_rewindRejoinEnable wal_log_hints (restart) or re-clone
MySQL Got fatal error 1236 from source when reading data from binary log1236ReplicaNeeded binlog purged; re-provision
MySQL ... running with the --super-read-only option so it cannot execute this statement1290Write to replicaRouting points at a replica
MongoDB NotWritablePrimary / PrimarySteppedDown10107 / 189Write during electionRetry (retryable writes)

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limitation
Stale read after writeTime-window pinPrimary for N s after a writeTrivialN is a guess; extra primary load
Stale read after writeLSN / GTID tokenReplica only once replayed past the tokenExact, minimal primary loadA query per read (cacheable), session plumbing
Stale read after writeremote_applyCommit waits for replay on sync standbysNo app routingLatency on every such commit; only sync standbys
Stale replica overallLag guardSkip replicas above X seconds lagProtects all readsNeeds a reliable lag metric
Slot fills diskCap + alertmax_slot_wal_keep_size, alert on wal_statusPrimary survivesConsumer must be rebuilt
Writes fail during failoverRetry idempotent writesClassify errors, backoff, idempotency keySurvives seconds-long failoverRequires idempotency design
Major upgrade without downtimeLogical replicationSubscribe new version, cut overMinutes of downtimeDDL freeze, sequences, slots
Reports cancelled on replicaDedicated reporting replicamax_standby_streaming_delay = -1Reports finishThat replica lags; never promote it

Stale read after write ​

SQL (PostgreSQL). After the write, on the primary:

sql
SELECT pg_current_wal_lsn();                                    -- e.g. 0/3000148, store it with the session

Before a read, on the replica:

sql
SELECT coalesce(pg_last_wal_replay_lsn() >= '0/3000148'::pg_lsn, false) AS caught_up;

Go: before and after (time-window pin). The before code sends every read to the replica; the after code pins a session to the primary for a few seconds after it writes and measures lag in bytes.

go
// Package main shows the classic replica read-your-writes bug.
// Writes go to the primary and every read goes to the replica.
package main

import (
	"context"
	"database/sql"
	"fmt"
	"os"
)

type Store struct {
	primary *sql.DB
	replica *sql.DB
}

func (s *Store) Rename(ctx context.Context, id int64, name string) error {
	_, err := s.primary.ExecContext(ctx,
		`UPDATE users SET name = $1 WHERE id = $2`, name, id)
	return err
}

func (s *Store) Name(ctx context.Context, id int64) (string, error) {
	var name string
	// The replica may not have replayed the UPDATE yet.
	err := s.replica.QueryRowContext(ctx,
		`SELECT name FROM users WHERE id = $1`, id).Scan(&name)
	return name, err
}

func main() {
	// A driver such as pgx's database/sql adapter must be registered by a
	// blank import; it is omitted to keep this module dependency-free.
	primary, err := sql.Open("pgx", os.Getenv("PRIMARY_DSN"))
	if err != nil {
		panic(err)
	}
	replica, err := sql.Open("pgx", os.Getenv("REPLICA_DSN"))
	if err != nil {
		panic(err)
	}
	s := &Store{primary: primary, replica: replica}
	ctx := context.Background()

	if err := s.Rename(ctx, 1, "Ada"); err != nil {
		panic(err)
	}
	// Immediately after the write: may print the old name.
	name, err := s.Name(ctx, 1)
	fmt.Println(name, err)
}
go
// Package main pairs a primary and a replica, measures replication lag in
// bytes, and pins a session to the primary for a short window after it writes.
package main

import (
	"context"
	"database/sql"
	"fmt"
	"os"
	"sync"
	"time"
)

type Router struct {
	primary *sql.DB
	replica *sql.DB

	pinFor time.Duration
	mu     sync.Mutex
	pinned map[string]time.Time // session ID -> pinned until
}

func NewRouter(primary, replica *sql.DB, pinFor time.Duration) *Router {
	return &Router{
		primary: primary,
		replica: replica,
		pinFor:  pinFor,
		pinned:  make(map[string]time.Time),
	}
}

// MarkWrite pins the session to the primary for pinFor after a write.
func (r *Router) MarkWrite(session string) {
	r.mu.Lock()
	defer r.mu.Unlock()
	r.pinned[session] = time.Now().Add(r.pinFor)
}

// ForRead returns the primary while the session is pinned, otherwise the replica.
func (r *Router) ForRead(session string) *sql.DB {
	r.mu.Lock()
	defer r.mu.Unlock()
	if until, ok := r.pinned[session]; ok {
		if time.Now().Before(until) {
			return r.primary
		}
		delete(r.pinned, session)
	}
	return r.replica
}

// LagBytes compares the primary's current WAL position with what the replica
// has received and replayed. It returns (receiveLag, replayLag) in bytes.
func (r *Router) LagBytes(ctx context.Context) (receive, replay int64, err error) {
	var current string
	err = r.primary.QueryRowContext(ctx, `SELECT pg_current_wal_lsn()::text`).Scan(&current)
	if err != nil {
		return 0, 0, err
	}
	// pg_wal_lsn_diff runs on the replica; both LSNs are passed as text.
	err = r.replica.QueryRowContext(ctx, `
		SELECT
		  pg_wal_lsn_diff($1::pg_lsn, pg_last_wal_receive_lsn())::bigint,
		  pg_wal_lsn_diff($1::pg_lsn, pg_last_wal_replay_lsn())::bigint`,
		current).Scan(&receive, &replay)
	return receive, replay, err
}

func main() {
	// Register a driver (for example pgx's database/sql adapter) with a blank
	// import before running this.
	primary, err := sql.Open("pgx", os.Getenv("PRIMARY_DSN"))
	if err != nil {
		panic(err)
	}
	replica, err := sql.Open("pgx", os.Getenv("REPLICA_DSN"))
	if err != nil {
		panic(err)
	}
	r := NewRouter(primary, replica, 5*time.Second)
	ctx := context.Background()

	if _, err := primary.ExecContext(ctx,
		`UPDATE users SET name = $1 WHERE id = $2`, "Ada", 1); err != nil {
		panic(err)
	}
	r.MarkWrite("session-42")

	var name string
	err = r.ForRead("session-42").QueryRowContext(ctx,
		`SELECT name FROM users WHERE id = $1`, 1).Scan(&name)
	fmt.Println(name, err)

	recv, replay, err := r.LagBytes(ctx)
	fmt.Println("receive lag:", recv, "replay lag:", replay, err)
}

Go: LSN token routing, lag guard and failover-safe writes. The core of the token approach is a single comparison on the replica:

go
func (r *Router) replayed(ctx context.Context, tok Token) (bool, error) {
	var ok bool
	err := r.Replica.QueryRowContext(ctx,
		`SELECT coalesce(pg_last_wal_replay_lsn() >= $1::pg_lsn, false)`,
		string(tok)).Scan(&ok)
	return ok, err
}

and the lag check that does not lie on an idle primary:

go
	err := r.Replica.QueryRowContext(ctx, `
		SELECT CASE
		  WHEN pg_last_wal_receive_lsn() = pg_last_wal_replay_lsn() THEN 0
		  ELSE extract(epoch FROM now() - pg_last_xact_replay_timestamp())
		END`).Scan(&secs)

The full, vet-clean program (Write returns the token, ForRead waits up to Wait for the replica and otherwise uses the primary, WriteWithRetry retries idempotent writes on failover errors):

go
// Package main routes reads with a causal LSN token: after a write the caller
// keeps the primary's WAL position, and a later read goes to the replica only
// once the replica has replayed past that position. It also skips a replica
// whose replay delay is above a limit and retries writes that hit a failover.
package main

import (
	"context"
	"database/sql"
	"database/sql/driver"
	"errors"
	"fmt"
	"os"
	"time"
)

// Token is a pg_lsn in text form, for example "0/3000148". Store it in the
// user's session or a cookie; empty means "no recent write".
type Token string

type Router struct {
	Primary  *sql.DB
	Replica  *sql.DB
	MaxDelay time.Duration // replica replay delay above this: read the primary
	Wait     time.Duration // how long a read may wait for the replica to catch up
	Poll     time.Duration
}

// Write runs fn in a transaction on the primary and returns the WAL position
// after the commit. pg_current_wal_lsn() is read after COMMIT returned, so it
// is at or past the commit record.
func (r *Router) Write(ctx context.Context, fn func(*sql.Tx) error) (Token, error) {
	tx, err := r.Primary.BeginTx(ctx, nil)
	if err != nil {
		return "", err
	}
	if err := fn(tx); err != nil {
		_ = tx.Rollback()
		return "", err
	}
	if err := tx.Commit(); err != nil {
		return "", err
	}
	var lsn string
	err = r.Primary.QueryRowContext(ctx, `SELECT pg_current_wal_lsn()::text`).Scan(&lsn)
	return Token(lsn), err
}

// ForRead returns the replica when it is fresh enough for this caller,
// otherwise the primary. It never returns a replica that has not replayed tok.
func (r *Router) ForRead(ctx context.Context, tok Token) *sql.DB {
	if tok == "" {
		if d, err := r.ReplayDelay(ctx); err == nil && d <= r.MaxDelay {
			return r.Replica
		}
		return r.Primary
	}
	deadline := time.Now().Add(r.Wait)
	for {
		ok, err := r.replayed(ctx, tok)
		if err == nil && ok {
			return r.Replica
		}
		if err != nil || time.Now().After(deadline) {
			return r.Primary
		}
		select {
		case <-ctx.Done():
			return r.Primary
		case <-time.After(r.Poll):
		}
	}
}

func (r *Router) replayed(ctx context.Context, tok Token) (bool, error) {
	var ok bool
	err := r.Replica.QueryRowContext(ctx,
		`SELECT coalesce(pg_last_wal_replay_lsn() >= $1::pg_lsn, false)`,
		string(tok)).Scan(&ok)
	return ok, err
}

// ReplayDelay is how far behind the replica's visible data is. When everything
// received has been replayed the replica is current, even if the primary has
// been idle and pg_last_xact_replay_timestamp() is old.
func (r *Router) ReplayDelay(ctx context.Context) (time.Duration, error) {
	var secs sql.NullFloat64
	err := r.Replica.QueryRowContext(ctx, `
		SELECT CASE
		  WHEN pg_last_wal_receive_lsn() = pg_last_wal_replay_lsn() THEN 0
		  ELSE extract(epoch FROM now() - pg_last_xact_replay_timestamp())
		END`).Scan(&secs)
	if err != nil {
		return 0, err
	}
	if !secs.Valid {
		return 0, errors.New("not a standby, or nothing replayed yet")
	}
	return time.Duration(secs.Float64 * float64(time.Second)), nil
}

// failoverRetryable reports errors that a failover produces: a dropped
// connection, the old primary now read-only (25006), shutdown (57P01),
// "the database system is starting up" (57P03) and connection failures (08xxx).
func failoverRetryable(err error) bool {
	if errors.Is(err, driver.ErrBadConn) {
		return true
	}
	var se interface{ SQLState() string } // implemented by pgconn.PgError
	if errors.As(err, &se) {
		switch code := se.SQLState(); {
		case code == "25006", code == "57P01", code == "57P03":
			return true
		case len(code) == 5 && code[:2] == "08":
			return true
		}
	}
	return false
}

// WriteWithRetry retries an idempotent write across a failover with backoff.
// fn must be safe to run twice (use an idempotency key or an upsert).
func (r *Router) WriteWithRetry(ctx context.Context, fn func(*sql.Tx) error) (Token, error) {
	backoff := 200 * time.Millisecond
	for attempt := 1; ; attempt++ {
		tok, err := r.Write(ctx, fn)
		if err == nil || !failoverRetryable(err) || attempt == 6 {
			return tok, err
		}
		select {
		case <-ctx.Done():
			return "", ctx.Err()
		case <-time.After(backoff):
		}
		backoff *= 2
	}
}

func main() {
	// Register a driver (for example pgx's database/sql adapter) with a blank
	// import before running this; it is omitted to keep the module dependency-free.
	primary, err := sql.Open("pgx", os.Getenv("PRIMARY_DSN"))
	if err != nil {
		panic(err)
	}
	replica, err := sql.Open("pgx", os.Getenv("REPLICA_DSN"))
	if err != nil {
		panic(err)
	}
	r := &Router{Primary: primary, Replica: replica,
		MaxDelay: 2 * time.Second, Wait: 300 * time.Millisecond, Poll: 20 * time.Millisecond}
	ctx := context.Background()

	tok, err := r.WriteWithRetry(ctx, func(tx *sql.Tx) error {
		_, err := tx.ExecContext(ctx,
			`INSERT INTO profiles (user_id, name) VALUES ($1, $2)
			 ON CONFLICT (user_id) DO UPDATE SET name = EXCLUDED.name`, 1, "Ada")
		return err
	})
	if err != nil {
		panic(err)
	}

	var name string
	err = r.ForRead(ctx, tok).QueryRowContext(ctx,
		`SELECT name FROM profiles WHERE user_id = $1`, 1).Scan(&name)
	fmt.Println(name, err)
}

The Go angle. database/sql has no notion of replicas: a *sql.DB is a pool for one DSN, so a primary/replica pair is two pools you route yourself. A transaction is bound to the connection it began on, so a read-write transaction must start on the primary pool; never read from a replica inside logic that then writes to the primary. With pgx you can let the driver find the primary at connect time with a multi-host DSN (postgres://a,b,c/db?target_session_attrs=read-write), and target_session_attrs=prefer-standby for read pools; existing connections still break on failover and must be retried. database/sql retries only driver.ErrBadConn before a query was sent, so write paths need the explicit, idempotent retry above.

Laravel: before and after. Without sticky, a write and a following read in one request can land on different servers:

php
<?php

// config/database.php (excerpt) — read/write split WITHOUT sticky.
// A write followed by a read in the same request can hit a replica that has
// not replayed the write yet.
return [
    'connections' => [
        'pgsql' => [
            'driver' => 'pgsql',
            'read' => [
                'host' => [env('DB_REPLICA_HOST', '10.0.0.12')],
            ],
            'write' => [
                'host' => [env('DB_PRIMARY_HOST', '10.0.0.11')],
            ],
            'port' => env('DB_PORT', '5432'),
            'database' => env('DB_DATABASE', 'laravel'),
            'username' => env('DB_USERNAME', 'laravel'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'prefix' => '',
            'search_path' => 'public',
            'sslmode' => 'prefer',
        ],
    ],
];

With 'sticky' => true, reads in the same request use the write connection after a write. The docs describe sticky as "an optional value that can be used to allow the immediate reading of records that have been written to the database during the current request cycle", and the built-in Illuminate\Foundation\Http\Middleware\PreventStaleDatabaseReads middleware "allows subsequent requests in the same session to read recently written data from the write connection" (it stores _database_modified_at in the session and calls useWriteConnectionWhenReading(); default window 2 seconds, PreventStaleDatabaseReads::for(5) to change it). Try that first:

php
// bootstrap/app.php
use Illuminate\Foundation\Http\Middleware\PreventStaleDatabaseReads;

->withMiddleware(function (Middleware $middleware) {
    $middleware->web(append: [PreventStaleDatabaseReads::for(5)]);
})
php
<?php

// config/database.php (excerpt) — same split, plus `sticky`.
// After a write in the current request, reads in that request use the write
// connection. It does not help the NEXT request (see the middleware below).
return [
    'connections' => [
        'pgsql' => [
            'driver' => 'pgsql',
            'read' => [
                'host' => [env('DB_REPLICA_HOST', '10.0.0.12')],
            ],
            'write' => [
                'host' => [env('DB_PRIMARY_HOST', '10.0.0.11')],
            ],
            'sticky' => true,
            'port' => env('DB_PORT', '5432'),
            'database' => env('DB_DATABASE', 'laravel'),
            'username' => env('DB_USERNAME', 'laravel'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'prefix' => '',
            'search_path' => 'public',
            'sslmode' => 'prefer',
        ],

        // Direct replica connection used only for lag reporting.
        'pgsql_replica' => [
            'driver' => 'pgsql',
            'host' => env('DB_REPLICA_HOST', '10.0.0.12'),
            'port' => env('DB_PORT', '5432'),
            'database' => env('DB_DATABASE', 'laravel'),
            'username' => env('DB_USERNAME', 'laravel'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'prefix' => '',
            'search_path' => 'public',
            'sslmode' => 'prefer',
        ],
    ],
];

A per-user variant (for APIs without sessions) uses Connection::recordsHaveBeenModified():

php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\Response;

// Keeps a user on the primary for a few seconds after they wrote something,
// across requests. `sticky => true` must be set on the connection.
final class PinToPrimary
{
    private const PIN_SECONDS = 5;

    public function handle(Request $request, Closure $next): Response
    {
        $key = $this->key($request);

        if ($key !== null && Cache::has($key)) {
            // Marks the connection as "modified", so sticky routes reads
            // to the write connection for the rest of this request.
            DB::connection()->recordsHaveBeenModified();
        }

        $response = $next($request);

        if ($key !== null && ! $request->isMethodSafe()) {
            Cache::put($key, true, self::PIN_SECONDS);
        }

        return $response;
    }

    private function key(Request $request): ?string
    {
        $id = $request->user()?->getAuthIdentifier();

        return $id === null ? null : "pin-primary:{$id}";
    }
}

The LSN-token version replaces the guessed window with the real replay position, using hasModifiedRecords(), useWriteConnectionWhenReading() and selectOne(..., [], false) (the third argument forces the write PDO):

php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\Response;

// Read-your-writes by WAL position instead of by a fixed time window.
// After a request writes, remember the primary's pg_current_wal_lsn() in the
// session. On the next request, read from the replica only if it has replayed
// past that LSN; otherwise send this request's reads to the write connection.
final class ReadYourWritesByLsn
{
    private const SESSION_KEY = '_primary_lsn';

    public function handle(Request $request, Closure $next): Response
    {
        $db = DB::connection('pgsql');
        $lsn = $request->session()->get(self::SESSION_KEY);

        if (is_string($lsn)) {
            if ($this->replicaHasReplayed($lsn)) {
                $request->session()->forget(self::SESSION_KEY);
            } else {
                $db->useWriteConnectionWhenReading();
            }
        }

        $response = $next($request);

        if ($db->hasModifiedRecords()) {
            // Third argument false: run on the write (primary) PDO.
            $row = $db->selectOne('SELECT pg_current_wal_lsn()::text AS lsn', [], false);
            $request->session()->put(self::SESSION_KEY, $row->lsn);
        }

        return $response;
    }

    private function replicaHasReplayed(string $lsn): bool
    {
        try {
            $row = DB::connection('pgsql_replica')->selectOne(
                'SELECT coalesce(pg_last_wal_replay_lsn() >= ?::pg_lsn, false) AS caught_up',
                [$lsn],
            );

            return (bool) $row->caught_up;
        } catch (QueryException) {
            // Replica unreachable: be safe and read from the primary.
            return false;
        }
    }
}

Replica lag check and lag guard ​

SQL: the two queries in Measuring replication lag. Go: ReplayDelay in the lsnwait program, used by ForRead to skip a replica above MaxDelay. Laravel: an Artisan command for dashboards and alerts:

php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

// php artisan db:replication-lag
final class ReplicationLag extends Command
{
    protected $signature = 'db:replication-lag';

    protected $description = 'Report replication lag as seen from the replica';

    public function handle(): int
    {
        // Runs on the replica. pg_last_xact_replay_timestamp() is NULL if no
        // transaction has been replayed yet.
        $row = DB::connection('pgsql_replica')->selectOne(<<<'SQL'
            SELECT
              pg_is_in_recovery() AS in_recovery,
              pg_last_wal_receive_lsn()::text AS receive_lsn,
              pg_last_wal_replay_lsn()::text AS replay_lsn,
              pg_wal_lsn_diff(pg_last_wal_receive_lsn(), pg_last_wal_replay_lsn())::bigint AS replay_backlog_bytes,
              EXTRACT(EPOCH FROM (now() - pg_last_xact_replay_timestamp()))::float AS replay_delay_seconds
        SQL);

        if (! $row->in_recovery) {
            $this->error('Connected server is not a standby.');

            return self::FAILURE;
        }

        $this->table(
            ['receive_lsn', 'replay_lsn', 'backlog_bytes', 'replay_delay_s'],
            [[$row->receive_lsn, $row->replay_lsn, $row->replay_backlog_bytes, $row->replay_delay_seconds]],
        );

        return self::SUCCESS;
    }
}

To act on it, schedule the command (Schedule::command('db:replication-lag')->everyMinute()) and, in a middleware, switch the request to the write connection when the last measured lag is above your limit:

php
if (Cache::get('db:replica-lag-seconds', 0) > 5) {
    DB::connection('pgsql')->useWriteConnectionWhenReading();
}

A slot filling the primary's disk ​

sql
-- alert rule: any slot retaining more than 20 GB, or not active for 15 minutes
SELECT slot_name, active, wal_status,
       pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn) AS retained_bytes
FROM pg_replication_slots
WHERE pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn) > 20 * 1024^3 OR NOT active;
ALTER SYSTEM SET max_slot_wal_keep_size = '50GB'; SELECT pg_reload_conf();

Size the cap below free disk, and decide in advance that a replica or CDC consumer that falls behind is rebuilt rather than allowed to stop the primary.

Writes during a failover ​

Every in-flight transaction on the old primary fails. Make writes idempotent (an idempotency key column with a unique constraint, or INSERT ... ON CONFLICT), classify errors (next section), back off, and retry. Never retry a non-idempotent write blindly: the COMMIT may have succeeded on the old primary and replicated before the connection broke.

Zero-downtime major upgrade with logical replication ​

text
1    new cluster (PG 19): pg_dump --schema-only | psql; CREATE SUBSCRIPTION ... (copy_data = true)
2    wait until pg_stat_subscription latest_end_lsn tracks the publisher; run checks
3    freeze DDL; at cut-over: stop writers (or PgBouncer PAUSE)
4    wait for the subscriber to reach the publisher's pg_current_wal_lsn()
5    sync sequences: ALTER SUBSCRIPTION ... REFRESH SEQUENCES (publisher 19+) or setval() per sequence
6    point PgBouncer/HAProxy to the new cluster; RESUME; drop the subscription and old slot

Retries and failure handling ​

ErrorMeaningRetry?
Connection reset / driver.ErrBadConn / SQLSTATE class 08Server went away (failover, restart)Yes, after reconnect, if idempotent
25006 read-only transactionYou are on a standby or the demoted old primaryYes, after re-routing (refresh DNS/pool)
57P01 admin shutdown, 57P03 cannot connect nowServer stopping / starting / in recoveryYes, with backoff
40001 conflict with recovery (standby read)Replay cancelled the queryYes, or route to primary / reporting replica
Sync commit warning after cancelCommitted locally, maybe not on standbyDo not re-run; treat as committed
MySQL 1290 super-read-only, 2013 lost connectionSame as 25006 / 08Yes, after re-routing
MongoDB NotWritablePrimary, PrimarySteppedDownElection in progressYes (drivers retry once with retryWrites)

Rules: retry only idempotent operations; cap attempts and total time (a failover takes tens of seconds, so 5–6 attempts with exponential backoff from 200ms); retry the whole transaction, never a single statement inside it; log every retry with the error code; after a failover, recycle long-lived pools (queue workers, Octane) so they re-resolve the primary.

Laravel specifics: Illuminate\Database\LostConnectionDetector (13.x) treats messages including SQLSTATE[25006]: Read only sql transaction: 7, canceling statement due to conflict with recovery and MySQL's running with the --read-only option so it cannot execute this statement as a lost connection, so a query outside a transaction is reconnected and retried once automatically; inside DB::transaction it is not, and you get the exception. Queue workers keep connections between jobs; run php artisan queue:restart after a failover or rely on the reconnect, and make jobs idempotent.

Go specifics: see failoverRetryable and WriteWithRetry in the lsnwait program.

Choosing a setup ​

Workload / situationRecommended setupExtra techniqueReason
Small app, one region, can lose secondsPrimary + 1 async streaming replica, Patroni or managed Multi-AZSlot with max_slot_wal_keep_size; backups + PITRCheap HA; RPO of seconds acceptable
Payments, ledgers, ordersQuorum sync: ANY 1 (az_b, az_c), Patroni synchronous_modeIdempotent writes, retriesRPO 0 without one standby blocking writes
Read-heavy product pagesAsync replicas behind a RO endpointLag guard; read-your-writes via LSN token for the writerScale reads; protect users' own writes
Long reports / BIDedicated reporting replica, max_standby_streaming_delay = -1, nofailoverOr logical replication to an OLAP storeReports finish; OLTP replicas stay fresh
Protection from human errorDelayed replica (e.g. 4h) + PITRNever a failover targetFast recovery of a dropped table
Major version upgradeLogical replication cut-overDDL freeze, sequence syncMinutes of downtime
Multi-region readsCascading async replica per regionRegion-local read-your-writes via tokenOne WAN stream; local latency
Multi-region writesNot PostgreSQL physical replication; distributed SQL or partitioned ownershiporigin = none bidirectional only with disjoint rowsSingle-leader cannot write in two regions
MySQL shopInnoDB Cluster (Group Replication + Router) or GTID + semi-sync + Orchestratorsuper_read_only on replicasBuilt-in consensus failover
MongoDB3+ member replica set, w: "majority"Causal sessions for read-your-writesElections built in

In architecture: from a single process to a distributed system ​

Replication turns one database into several copies that are not identical at every moment. Every architecture decision below is about where the application is allowed to notice that.

Monolith: one process, one database ​

How it shows up: a single PostgreSQL primary with one standby for HA. The application connects to one endpoint (Patroni/HAProxy, or a managed DNS name) and never reads from the standby.

Simplest correct usage: async streaming with a slot, max_slot_wal_keep_size, Patroni or RDS Multi-AZ, application retries on connection errors. No read routing at all, so no stale reads.

Example (simple): a Laravel shop on RDS PostgreSQL Multi-AZ. Failover flips DNS; LostConnectionDetector reconnects; queue workers are restarted by the deploy tool after an event notification.

Example (complex): the same shop adds a read replica for the admin's sales dashboard and search pages. It configures read/write hosts with sticky => true, adds PreventStaleDatabaseReads, and keeps checkout entirely on the write connection (DB::connection('pgsql')->useWriteConnectionWhenReading() in the checkout route group), because checkout reads stock and then writes an order.

Modular monolith and multiple databases ​

How it shows up: modules have their own schemas or databases with different needs: Billing wants RPO 0; Catalog wants many read replicas; Analytics wants a copy of some tables.

Example: Billing on a cluster with ANY 1 (az_b, az_c); Catalog on another cluster with three async replicas; Analytics receives orders and customers through logical replication (CREATE PUBLICATION analytics FOR TABLE orders, customers (id, country, created_at)) so it never touches the OLTP primary. Rule: decide the consistency tier per module; never let a module read another module's replica and then write to its own primary based on it.

Microservices ​

What survives: each service's own primary/replica setup and its own read-your-writes routing. What does not: a client's write in service A followed by a read in service B: B's data comes from an event, which is a replication channel with its own lag.

text
     Client          Order service (PG primary/replica)        Outbox relay / CDC slot        Search service
1    POST /orders ─▶ INSERT order + outbox row; COMMIT (lsn 0/A10)
2                    201 Created {order_id, token: "0/A10"}
3                                                              Debezium reads logical slot ─▶ OrderCreated
4    GET /search?mine ─────────────────────────────────────────────────────────────────────▶ not indexed yet
     -- fixes: return the created resource in the 201 body; GET /orders/{id} on the order service with the token;
     -- or have the search service expose "indexed up to event N" and the client wait for it

The CDC relay is itself a logical replication slot on the order database: if Debezium stops, that slot fills the order primary's disk (slots). After a failover, PostgreSQL 17+ failover slots (failover = true, sync_replication_slots = on on the standby) let the CDC connector continue from the new primary instead of re-snapshotting. See Change Data Capture and Transactional Outbox.

Distributed data: replicas, regions and other topologies ​

Replica reads at scale: treat "may be stale" as an explicit property of a query. Tag repository methods as strong (primary), session (read-your-writes via token), or stale-ok (any replica under a lag bound).

Multi-region: physical replication is single-leader: all writes travel to one region. Cross-region synchronous commit adds the inter-region round trip (tens of ms) to every commit; most designs keep sync replicas in-region (other AZs) and async replicas cross-region, accepting a cross-region RPO of seconds. Regional failover is usually a human decision because a partition between regions is indistinguishable from a regional outage.

Leader-follower vs multi-leader vs leaderless: everything on this page is leader-follower (single leader). Multi-leader (PostgreSQL bidirectional logical replication with origin = none, MySQL Group Replication multi-primary, BDR-style products) accepts writes in several places and must resolve conflicts. Leaderless (Dynamo-style: Cassandra, ScyllaDB, DynamoDB internals, Riak) writes to several nodes and reads with quorums (W + R > N). Consensus-replicated databases (CockroachDB, Spanner, YugabyteDB, etcd) replace failover with per-range Raft/Paxos elections. The comparison and conflict resolution are taught in Replication Topologies; the consensus algorithms in Distributed SQL, Consensus & 2PC; quorum consistency in Eventual Consistency.

Scaling path: 1×, 10×, 100× ​

LoadWhat changesReplication consequence
1× (one primary, modest traffic)Primary + one standby, HA manager or managed Multi-AZNo read routing; RPO/RTO written down; failover rehearsed
10× (read-heavy, reports, connection pool)Read replicas, PgBouncer, HAProxy RO endpoint, reporting replicaRead-your-writes routing; lag guard; slot caps; recovery conflicts tuned; quorum sync for money
100× (multiple regions, sharding, services)Cascading cross-region replicas, CDC to many consumers, shards each with their own HAPer-shard failover; failover slots for CDC; region-level RPO decisions; consider distributed SQL for multi-region writes

At every step the same rule holds: one writer per piece of data, an explicit bound on how stale each read may be, and a failover path that someone has actually run.

Lab ​

PostgreSQL 17 in Docker, one primary and one streaming replica. Run the experiments in order; expected output is in comments.

Setup.

bash
docker network create pgnet
docker volume create pg1data && docker volume create pg2data
docker run -d --name pg1 --network pgnet -v pg1data:/var/lib/postgresql/data \
  -e POSTGRES_PASSWORD=pg postgres:17 \
  -c wal_log_hints=on -c max_slot_wal_keep_size=2GB -c cluster_name=pg1
sleep 5
docker exec pg1 psql -U postgres -c "CREATE ROLE repl WITH REPLICATION LOGIN PASSWORD 'repl'"
docker exec pg1 bash -c "echo 'host replication all all scram-sha-256' >> /var/lib/postgresql/data/pg_hba.conf"
docker exec pg1 psql -U postgres -c "SELECT pg_reload_conf()"

# clone the replica with a slot; -R writes standby.signal + primary_conninfo
docker run --rm --user postgres --network pgnet -v pg2data:/var/lib/postgresql/data \
  -e PGPASSWORD=repl postgres:17 \
  pg_basebackup -h pg1 -U repl -D /var/lib/postgresql/data -X stream -R -C -S pg2_slot -P
docker run -d --name pg2 --network pgnet -v pg2data:/var/lib/postgresql/data postgres:17 \
  -c cluster_name=pg2 -c hot_standby_feedback=off
# terminal A: docker exec -it pg1 psql -U postgres     terminal B: docker exec -it pg2 psql -U postgres

Experiment 1: is it replicating?

sql
-- A (primary)
SELECT application_name, state, sync_state, sent_lsn, replay_lsn FROM pg_stat_replication;
--  pg2 | streaming | async | 0/3000148 | 0/3000148
SELECT slot_name, active, wal_status FROM pg_replication_slots;   -- pg2_slot | t | reserved
-- B (replica)
SELECT pg_is_in_recovery();                                         -- t
CREATE TABLE x (id int);  -- ERROR:  cannot execute CREATE TABLE in a read-only transaction

Experiment 2: lag under load, and receive vs replay lag.

bash
docker exec pg1 pgbench -U postgres -i -s 20 postgres
docker exec pg1 pgbench -U postgres -c 8 -j 2 -T 120 postgres &     # write load for 2 minutes
sql
-- A, repeat with \watch 1
SELECT application_name,
       pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS replay_bytes, write_lag, flush_lag, replay_lag
FROM pg_stat_replication \watch 1
-- pg2 | 81920 | 00:00:00.0004 | 00:00:00.0011 | 00:00:00.0016   (small, LAN)
-- B: freeze replay, keep receiving
SELECT pg_wal_replay_pause();
SELECT pg_wal_lsn_diff(pg_last_wal_receive_lsn(), pg_last_wal_replay_lsn()) AS replay_backlog_bytes \watch 1
-- grows by megabytes per second; on A replay_bytes and replay_lag grow while flush_lag stays small

Experiment 3: stale read after write.

sql
-- A
CREATE TABLE profiles (user_id int PRIMARY KEY, name text);   -- replay is still paused on B
INSERT INTO profiles VALUES (1, 'Ada'); SELECT pg_current_wal_lsn();   -- e.g. 0/2A1C3F08
-- B
SELECT * FROM profiles;   -- ERROR: relation "profiles" does not exist  (the replica is in the past)
SELECT pg_last_wal_replay_lsn() >= '0/2A1C3F08'::pg_lsn;   -- f  -> a router must use the primary
SELECT pg_wal_replay_resume();
SELECT * FROM profiles;   -- 1 | Ada
SELECT pg_last_wal_replay_lsn() >= '0/2A1C3F08'::pg_lsn;   -- t

Experiment 4: synchronous commit, and the cancelled wait.

sql
-- A
ALTER SYSTEM SET synchronous_standby_names = 'FIRST 1 (pg2)'; SELECT pg_reload_conf();
SELECT application_name, sync_state FROM pg_stat_replication;     -- pg2 | sync
bash
docker stop pg2
sql
-- A
INSERT INTO profiles VALUES (2, 'Grace');   -- hangs: no synchronous standby
-- press Ctrl-C:
-- 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.
SELECT * FROM profiles WHERE user_id = 2;    -- 2 | Grace   (it is committed)
ALTER SYSTEM RESET synchronous_standby_names; SELECT pg_reload_conf();

Experiment 5: the slot holds WAL while the replica is down. With pg2 still stopped:

bash
docker exec pg1 pgbench -U postgres -c 8 -T 60 postgres
sql
-- A
SELECT slot_name, active, wal_status,
       pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained
FROM pg_replication_slots;
-- pg2_slot | f | reserved | 900 MB  (grows; at 2GB it would turn 'lost' and pg2 would need a new clone)
bash
docker start pg2     # catches up from the slot; retained drops to ~0

Experiment 6: failover, split brain, pg_rewind.

bash
docker stop pg1                                                   # "primary crashed"
docker exec pg2 psql -U postgres -c "SELECT pg_promote()"          # t
docker exec pg2 psql -U postgres -c "SELECT pg_is_in_recovery(), timeline_id FROM pg_control_checkpoint()"
#  f | 2
docker exec pg2 psql -U postgres -c "INSERT INTO profiles VALUES (3, 'from new primary')"

docker start pg1                                                  # old primary comes back AS A PRIMARY
docker exec pg1 psql -U postgres -c "INSERT INTO profiles VALUES (3, 'from old primary')"
# INSERT 0 1   <- split brain: two primaries accepted conflicting rows for user_id 3

docker stop pg1                                                   # fence it
docker run --rm --user postgres --network pgnet -v pg1data:/var/lib/postgresql/data postgres:17 \
  pg_rewind --target-pgdata=/var/lib/postgresql/data \
  --source-server="host=pg2 user=postgres password=pg dbname=postgres" -R --progress
# pg_rewind: servers diverged at WAL location 0/... on timeline 1
# pg_rewind: rewinding from last common checkpoint at 0/... on timeline 1
# pg_rewind: Done!
docker start pg1
docker exec pg1 psql -U postgres -c "SELECT pg_is_in_recovery(), * FROM profiles WHERE user_id = 3"
#  t | 3 | from new primary      <- the old primary's conflicting row is gone; it now follows timeline 2
docker exec pg2 psql -U postgres -c "SELECT application_name, state FROM pg_stat_replication"

What you learned: lag has separate receive and replay parts; a replica can be in the past by whole tables; a cancelled sync wait leaves a committed row; a slot protects a replica and costs the primary disk; promotion starts a new timeline; without fencing, the old primary happily accepts writes; pg_rewind discards them. Clean up with docker rm -f pg1 pg2 && docker volume rm pg1data pg2data && docker network rm pgnet.

Common misconceptions ​

BeliefReality
A replica is a backupIt replicates mistakes in milliseconds; only a delayed replica or PITR helps
synchronous_commit = on makes replication synchronousOnly with synchronous_standby_names set and a matching standby connected
Synchronous replication means no data loss in every failoverOnly if the promoted node was synchronous; remote_write can still lose data on a double crash
One synchronous standby is the safe choiceWhen it dies, writes block; use ANY 1 (s1, s2) or Patroni's non-strict mode
Replica lag is always millisecondsThe tail (bulk loads, conflicts, replay of big DDL) is seconds to minutes
now() - pg_last_xact_replay_timestamp() is lagIt grows on an idle primary; check receive LSN = replay LSN first
Slots are harmlessAn abandoned slot fills pg_wal and stops the primary; cap with max_slot_wal_keep_size
hot_standby_feedback is freeIt moves the cost to bloat on the primary
The old primary can just restart as a replicaIts timeline forked; pg_rewind or re-clone, and its extra writes are discarded
Unreachable means deadPartitions are common; without fencing you get split brain
DNS failover is instantTTLs, resolver caches and pooled connections delay it
Logical replication is a full HA copyNo DDL, no incremental sequences, no large objects
MySQL Seconds_Behind_Source is accurateIt is event-timestamp based and misleads with parallel appliers or idle periods
Two nodes plus a script is HAWithout a quorum authority (etcd ×3, witness) a partition promotes both

Cheat sheet ​

TopicWhat to remember
Streaming setupREPLICATION role, pg_hba replication line, pg_basebackup -X stream -R -C -S name
LSNByte position in WAL; pg_wal_lsn_diff(a, b) = bytes between
Lag on primarypg_stat_replication: sent/write/flush/replay_lsn, write/flush/replay_lag
Lag on standbypg_last_wal_receive_lsn(), pg_last_wal_replay_lsn(), idle-safe timestamp check
SlotsProtect standbys, endanger disk; max_slot_wal_keep_size; watch wal_status
Sync commitsynchronous_standby_names = 'ANY 1 (a, b)'; synchronous_commit per transaction
Levelsoff < local < remote_write < on < remote_apply
Hot standby conflictsmax_standby_streaming_delay (30s) or hot_standby_feedback (bloat)
Delayed replicarecovery_min_apply_delay; never a failover target
LogicalPublication/subscription, replica identity, no DDL/sequences, origin = none (16+)
Promotionpg_promote(); new timeline; followers need recovery_target_timeline = latest
Old primaryFence it, then pg_rewind (needs wal_log_hints or checksums)
PatroniLeader key with TTL in etcd ×3; maximum_lag_on_failover; synchronous_mode; REST /primary
RoutingHAProxy on Patroni checks, PgBouncer, multi-host target_session_attrs=read-write
Read-your-writesSticky/time window, LSN token, or remote_apply; Laravel sticky + PreventStaleDatabaseReads
MySQLROW binlog, GTID auto-position, semi-sync AFTER_SYNC, InnoDB Cluster + Router

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Your replica shows flush_lsn close to the primary but replay_lsn far behind. What are two likely causes, and which knob is involved? Important ​

Answer

Answer: WAL arrives but is not applied: replay is waiting on a recovery conflict (a standby query, up to max_standby_streaming_delay), or replay is paused (pg_wal_replay_pause()), or single-threaded replay cannot keep up with a heavy write burst. See Hot standby and Measuring lag.

2 — A replica was shut down for three days and the primary's disk filled. Why, and what setting would have kept the primary up? Important ​

Answer

Answer: Its replication slot kept every WAL segment since it disconnected. max_slot_wal_keep_size caps retention; the slot becomes lost and the replica must be re-cloned, but the primary survives. See Replication slots.

3 — What is the difference between synchronous_standby_names = 's1, s2' and 'ANY 1 (s1, s2)'? Good to know ​

Answer

Answer: The first is FIRST 1 (s1, s2): priority, it waits for s1 while it is connected and uses s2 only if s1 is gone. ANY 1 is quorum: whichever of the two confirms first. See Synchronous replication.

4 — A user cancels a hanging COMMIT on a primary with a synchronous standby that is down. Is the row committed? Important ​

Answer

Answer: Yes, locally. PostgreSQL prints "canceling wait for synchronous replication" and "The transaction has already committed locally, but might not have been replicated to the standby." A failover now could lose it. See the sync timeline.

5 — Why does now() - pg_last_xact_replay_timestamp() report 10 minutes of lag on a fully caught-up replica at night? Important ​

Answer

Answer: It measures the age of the last replayed transaction; with no new writes on the primary, it keeps growing. Check pg_last_wal_receive_lsn() = pg_last_wal_replay_lsn() first, or use a heartbeat table. See Measuring lag.

6 — After an async failover, can you simply start the old primary with standby.signal? Must-know ​

Answer

Answer: No. It may have WAL after the divergence point on the old timeline. Run pg_rewind (needs wal_log_hints = on or checksums) or re-clone; its extra writes are discarded. See Promotion and timelines and pg_rewind.

7 — Explain split brain and two ways Patroni prevents it. Must-know ​

Answer

Answer: Two nodes both accept writes. Patroni allows only the holder of the leader key in a majority-based store (etcd) to be primary, and a leader that cannot renew the key demotes itself; optionally a watchdog reboots a node whose Patroni stopped renewing. See Split brain and Patroni.

8 — What does remote_apply give you that on does not, and what does it cost? Important ​

Answer

Answer: The commit is visible on synchronous standbys before COMMIT returns, so a read there sees it (read-your-writes without routing). It costs the replay time on every such commit and only covers synchronous standbys. See Synchronous replication.

9 — Why can't you fail over to a logical-replication subscriber without preparation? Good to know ​

Answer

Answer: DDL is not replicated, sequences are not incrementally replicated (use REFRESH SEQUENCES on 19 or setval), large objects are not replicated, and applications must be re-pointed. See Logical replication.

10 — A Laravel app uses read/write hosts. A user saves a form and the redirect shows old data. Name the built-in fix and its limitation. Must-know ​

Answer

Answer: 'sticky' => true covers the same request only; add PreventStaleDatabaseReads to keep the session on the write connection for a few seconds after a write. Its limitation is a guessed time window; the LSN-token middleware uses the real replay position. See Stale read after write.

11 — Why is RDS Multi-AZ (single standby instance) not a read-scaling solution? Must-know ​

Answer

Answer: The AWS docs: "You can't use a standby replica to serve read traffic." It is a synchronous HA standby only; read replicas (or a Multi-AZ DB cluster) are separate. See What each product really does.

12 — In MySQL semisynchronous replication, what does the source wait for, and what happens if no replica answers? Important ​

Answer

Answer: Until at least one replica has received and logged the events (relay log), not applied them. After rpl_semi_sync_source_timeout it falls back to asynchronous. See MySQL.

Glossary ​

TermMeaning
Primary / standby (source / replica, leader / follower)The writable server / a server replaying its changes
WAL (write-ahead log)PostgreSQL's change log; the stream replication ships
LSN (log sequence number)Byte position in WAL, type pg_lsn, e.g. 0/3000148
WAL shipping (log shipping)Copying completed WAL files to a standby via an archive
Streaming replicationSending WAL over a replication connection as it is written
walsender / walreceiverPrimary process sending WAL / standby process receiving it
pg_basebackupTool to clone a cluster for a new standby (-R, -C, -S)
primary_conninfo, standby.signalStandby's upstream connection string / file that starts standby mode
Replication slotPrimary-side record that retains WAL until a consumer has it
max_slot_wal_keep_sizeCap on WAL retained by slots; beyond it the slot is invalidated
wal_statusSlot state: reserved, extended, unreserved, lost
wal_keep_sizeFixed WAL retention for standbys without slots
Hot standbyStandby that serves read-only queries during replay
Recovery conflictReplay needs to remove or lock what a standby query uses
max_standby_streaming_delayHow long replay waits before cancelling conflicting queries
hot_standby_feedbackStandby reports its xmin so the primary keeps needed rows (bloat)
synchronous_commitPer-transaction level: off, local, remote_write, on, remote_apply
synchronous_standby_namesWhich standbys are synchronous: FIRST n (...), ANY n (...)
FIRST / ANYPriority-based / quorum-based synchronous standby selection
sync_statesync, potential, quorum or async in pg_stat_replication
Cascading replicationA standby sending WAL to further standbys
Delayed replica / recovery_min_apply_delayStandby that applies commits a fixed time late
Logical replicationRow-level change replication by publication/subscription
Publication / subscriptionSet of tables published / the consumer that applies them
Replica identityColumns used to find a row for UPDATE/DELETE on the subscriber
pgoutputPostgreSQL's built-in logical decoding output plugin
origin = noneSubscription option (16+) that skips replicated changes; enables bidirectional setups
Bidirectional replicationTwo nodes replicating to each other; needs loop prevention and no conflicting writes
Failover slotLogical slot synchronised to standbys (17+) so CDC survives failover
Promotion / pg_promote()Turning a standby into a primary
Timeline (TLI)History branch number; increments at each promotion
recovery_target_timelineWhich timeline a standby follows; latest by default
pg_rewindResynchronises a diverged old primary with the new one
wal_log_hintsSetting that lets pg_rewind work without data checksums
FailoverUnplanned promotion after the primary fails
SwitchoverPlanned, lossless role change
Split brainTwo nodes accepting writes as primary at once
Fencing / STONITHGuaranteeing the old primary can no longer write ("Shoot The Other Node In The Head")
WatchdogTimer device that reboots a node whose HA agent stops resetting it
Leader lock (leader key)DCS key whose holder is the only legitimate primary
DCSDistributed configuration store: etcd, Consul, ZooKeeper, Kubernetes API
etcdRaft-based key-value store used by Patroni and Kubernetes
PatroniHA manager for PostgreSQL built on a DCS leader key
maximum_lag_on_failoverPatroni bound on replica lag for promotion eligibility
synchronous_modePatroni mode that manages sync standbys and promotes only them
repmgr / repmgrdReplication manager and its failover daemon; witness node
pgpool-IIMiddleware with pooling, read load balancing, failover and watchdog
PgBouncerLightweight PostgreSQL connection pooler
HAProxyTCP/HTTP load balancer routing by Patroni health checks
VIPVirtual IP that moves to the current primary
DNS failoverMoving a DNS name to the new primary; limited by TTL and caches
target_session_attrslibpq/pgx option choosing read-write, read-only, primary, standby, prefer-standby hosts
Read-your-writesA client always sees its own earlier writes
Monotonic readsA client never sees older data after newer data
Consistent prefixReads see writes in the order they happened
Sticky sessionRouting a session's reads to one place (primary or one replica)
LSN token (causal token)WAL position carried by a client to demand a fresh-enough replica
pg_last_xact_replay_timestamp()Commit time of the last replayed transaction
pg_stat_replicationPrimary view with one row per connected standby
RPO / RTOMaximum acceptable data loss / downtime
BinlogMySQL binary log of committed changes
binlog_format ROW / STATEMENT / MIXEDRow images / SQL text / statement with automatic switch to row
Relay logReplica's local copy of fetched binlog events
GTIDMySQL global transaction ID source_uuid:n; SOURCE_AUTO_POSITION
Semisynchronous replicationMySQL source waits for at least one replica to log the events
AFTER_SYNC / AFTER_COMMITSemi-sync wait points; AFTER_SYNC is lossless (default)
super_read_onlyMySQL setting that blocks writes even from privileged users
Group ReplicationMySQL consensus-based replication group (single- or multi-primary)
InnoDB Cluster / ReplicaSetMySQL Shell-managed Group Replication / async replication with Router
MySQL RouterProxy that routes to the current primary (6446) or secondaries (6447)
OrchestratorMySQL topology manager and failover tool
Replica set (MongoDB)Primary + secondaries tailing the oplog, with elections
ElectionVoting to choose a new primary (MongoDB, Group Replication, Raft)
Write concernMongoDB acknowledgement level, w: 1 or w: "majority" (default)
RDS Multi-AZAWS synchronous standby in another AZ with DNS failover
AuroraAWS database with a shared storage volume and replicas reading it
Multi-leader / leaderlessTopologies with several writers / quorum reads and writes; see system design

References ​

Built by Morteza Negahi