Primary-replica

On this page 7

Primary-replica is a database replication architecture in which one primary server accepts all writes and continuously ships its changes to one or more replica servers that hold copies of the data and serve reads or stand by for failover. In replication for databases, it is the most widely deployed topology, used by PostgreSQL streaming replication, MySQL and MariaDB binary log replication, SQL Server availability groups and most managed cloud databases.

The model was historically called master-slave; most vendors now use primary and replica, or primary and standby. Its strength is simplicity: with a single writer, there are no write conflicts to resolve. Its limits are equally clear: write capacity is bounded by one server, and replicas may show slightly outdated data whenever replication is asynchronous.

How primary-replica replication works

Primary-replica replication works by turning every committed change on the primary into an ordered change stream and applying that stream, in the same order, on each replica. Because the order is identical, every replica passes through the same sequence of states as the primary, only later.

The change stream is usually the log the database already writes for recovery or auditing. PostgreSQL ships its write-ahead log (WAL), MySQL ships its binary log, and SQL Server ships transaction log blocks. Each replica tracks its position in the stream, such as a log sequence number in PostgreSQL or a GTID set in MySQL, so it can resume exactly where it stopped after a restart or a network interruption.

MethodWhat is shippedStrengthsLimitations
Physical replicationByte-level page changes from WALExact copy, low overheadSame major version and platform required
Logical, row-basedChanged rows per tableCross-version, selective tablesSchema changes need care
Statement-basedSQL statementsCompact logNondeterministic functions can diverge
Storage-levelDisk blocksDatabase-agnosticNo read access on standby in many setups
Replication methods used in primary-replica setups

Replicas in most engines are read-only: they reject writes so that the change stream remains the only source of modification. Replicas can also feed further replicas in a cascading topology, which reduces the network and CPU load on the primary when there are many copies.

Synchronous, asynchronous and semi-synchronous modes

The replication mode decides when the primary confirms a commit to the client, and therefore how much data a failover can lose. This choice is expressed through the recovery point objective (RPO): the maximum acceptable data loss.

ModeCommit confirmed afterData loss on primary failureWrite latency impact
AsynchronousLocal log flush onlyRecent commits may be lostNone
Semi-synchronousAt least one replica has received the changeUsually noneOne network round trip
SynchronousReplica has flushed or applied the changeNone for confirmed commitsRound trip plus remote flush
Quorum synchronousA set number of replicas, for example 2 of 3None while the quorum holdsRound trip to the fastest quorum
Commit acknowledgment modes

Synchronous replication across regions is expensive: a 70 ms round trip between continents adds at least 70 ms to every commit. Synchronous mode also introduces an availability risk, because if the only synchronous replica becomes unreachable, the primary stops confirming writes. For that reason, many deployments keep one synchronous replica nearby and the rest asynchronous.

Failover and the risk of split brain

Failover is the promotion of a replica to primary when the original primary fails, followed by redirecting clients and re-pointing the remaining replicas. It can be manual or automatic, using cluster managers such as Patroni for PostgreSQL or Orchestrator for MySQL, which rely on consensus stores or quorum votes to decide that the primary is truly down.

The most dangerous failure is split brain: a network partition leaves the old primary running while a replica is promoted, so two servers accept writes and the data diverges. Correct designs prevent it with fencing, which forcibly stops or isolates the old primary, and with a majority quorum that allows only one side of a partition to elect a primary.

ProblemCauseMitigation
Stale readsReplication lag on asynchronous replicasRoute read-after-write queries to the primary
Lost commits after failoverAsynchronous mode with unshipped changesSemi-synchronous or synchronous replica
Split brainPromotion without fencing during a partitionQuorum-based failover and fencing
Replica falls behind permanentlyLong queries or slow disk on replicaFaster storage, limits on replica query time
Primary disk fills upRetained log for a disconnected replicaMonitor slots, cap retained log size
Typical problems in primary-replica operation

Primary-replica compared with other topologies

Primary-replica is a single-leader design. Alternatives allow writes on several nodes, which improves write availability but forces the system to detect or resolve conflicts.

TopologyWrite nodesConflict handlingTypical use
Primary-replicaOneNot neededMost OLTP systems, read scaling, high availability
Multi-primarySeveralDetection, resolution rules or certificationMulti-region writes, Galera clusters
Leaderless quorumAnyVersioning, read repair, last write winsDynamo-style stores such as Cassandra
Consensus-replicatedOne leader per data rangeRaft or Paxos orderingDistributed SQL such as CockroachDB
Replication topologies

Primary-replica scales reads, not writes. When write volume exceeds what one server can handle, the usual next step is sharding, in which each shard is itself a primary-replica group.

Designing and operating a primary-replica setup

  • Define the RPO and recovery time objective first, then choose the replication mode and failover method that meet them.
  • Keep at least two replicas so that one can be rebuilt or upgraded while the other still protects the primary.
  • Monitor replication lag in both bytes and seconds, and alert well before it affects users.
  • Make the application lag-aware: send reads that must see a just-written change to the primary, or wait until the replica reaches the required log position.
  • Test failover regularly, because an untested promotion procedure is the most common reason a planned recovery takes hours instead of seconds.
  • Remember that a replica is not a backup: an accidental DROP TABLE replicates within milliseconds, so point-in-time backups remain necessary.

In everyday language

Primary-replica works like one official ledger with several photocopies. Only the clerk at the main desk may write in the ledger. Every new line is sent to assistants who keep identical copies, and visitors who only want to read can look at any copy.

If the main clerk falls ill, one assistant takes over the ledger. The catch is that copies can be a few moments behind, and if the clerk leaves before the newest line was sent, that line can be lost unless the system waits for confirmation first.

Seen in the real world

A news website runs PostgreSQL with one primary and three replicas in two data centers. About 95 percent of queries are reads, so the application sends article and comment reads to the replicas and keeps the primary for edits, logins and new comments. One replica in the same data center is synchronous, and the two others are asynchronous.

Normal replication lag stays below 100 milliseconds, but a newly posted comment is read back from the primary for the next few seconds so that authors always see their own text. When the primary’s storage controller fails on a weekday morning, the cluster manager promotes the synchronous replica in 25 seconds. Because that replica had every confirmed commit, no published edits are lost, and readers notice only a brief pause.