What it is
Primary-replica (leader-follower) is the most common way to run a replicated relational database. One node, the primary, accepts every write. Each replica keeps a full copy by replaying the primary's change log (PostgreSQL's write-ahead log, MySQL's binlog) and serves read-only queries. A routing layer (the application, a driver, or a proxy such as ProxySQL, HAProxy, pgpool-II or a cloud "reader endpoint") sends writes to the primary and reads to replicas.
The Database Replication lesson introduces replicas, lag and sync versus async. This lesson looks at the architecture itself: where its capacity comes from, where it stops, and how the single-writer rule shapes failover.
Why it exists
A single writer is the simplest way to keep copies consistent. All changes are ordered by one machine, so replicas only need to replay a log in order: there are no write conflicts to resolve. That buys read scaling, hot standbys for failover, and isolated nodes for analytics and backups without the complexity of multi-leader or leaderless replication.
How it works
Roles. The primary executes writes, appends them to its log and streams the log to every replica. Replicas apply the log and answer reads; they reject writes (PostgreSQL hot standbys and MySQL replicas with super_read_only refuse them). Replicas can also feed further replicas (cascading replication), which takes streaming load off the primary.
Read scaling. Read capacity grows roughly with the number of replicas, as long as reads can tolerate replica lag. In the lesson three replicas at 330 reads/s each are over 80% busy; a fourth brings them to about 60%.
What each replica costs. Every replica receives and replays every write. The primary runs one sender per replica (or the cascade does), so outgoing replication traffic is writes × replicas. On the replica, replay competes with queries for I/O and CPU; a replica of a write-heavy primary has noticeably less read capacity than an idle one. More replicas also means more lag to monitor and more failover candidates to keep in sync.
The write ceiling. All writes land on one machine. When the write share grows, the primary saturates while the replicas get quieter, and nothing about the replicas can help. The fixes act on the primary or on the writes: a bigger primary (more cores, faster storage), fewer or cheaper writes (batching, removing unused indexes, moving counters or logs elsewhere), or sharding into several primary-replica groups.
Failover. When the primary dies:
- Detect. Health checks or a consensus-backed manager (Patroni with etcd, Orchestrator, a cloud control plane) notice the primary is gone. Short timeouts detect faster but risk failing over on a brief hiccup.
- Choose. Pick the replica with the most of the primary's log (highest replayed LSN or GTID set), so the least data is lost.
- Promote. The chosen replica stops replaying and starts accepting writes (
pg_promote()in PostgreSQL). - Repoint. Clients, proxies and the other replicas must follow the new primary: update the proxy, move a virtual IP, change DNS (subject to TTLs and client caching), and repoint the remaining replicas.
- Fence. Make sure the old primary cannot accept writes if it comes back (STONITH, revoking its network access or storage, or a lease it can no longer renew).
During steps 1–4 writes fail. Reads continue on the replicas, but the promoted replica stops serving reads, so the remaining replicas take its share.
The old primary. A restarted old primary is missing every write since the failover, and may contain writes the new primary never received. It must be rebuilt as a replica: rewound to the point where the histories diverged (pg_rewind) or re-cloned from the new primary.
When to use it
- Read-heavy OLTP workloads where one machine can handle all writes, which covers most applications.
- When you need a hot standby for fast recovery from machine or zone failure.
- When analytics, reporting or backups must not load the transactional node.
When not to
- Writes exceed what one machine can do, or will soon: shard, or use a database that partitions writes across nodes.
- Writes must be accepted in several regions with local latency: consider multi-leader or a distributed SQL database, and accept their conflict or latency costs.
- Every read must be current: replicas add little; scale the primary or cache carefully.
Trade-offs
| Decision | Gain | Cost |
|---|---|---|
| More replicas | Read capacity, more failover candidates | More replication streams and replay work; more lag to monitor |
| Bigger primary than replicas | Write headroom | Promoted replica may be undersized; keep one primary-sized standby |
| Automatic failover | Write outage of seconds instead of minutes | Risk of failing over on a transient blip; requires fencing to avoid split brain |
| Short detection timeouts | Faster failover | More false positives, more unnecessary failovers |
| Cascading replicas | Less streaming load on the primary | Extra lag on downstream replicas; an intermediate replica becomes a dependency |
Alternatives
- Sharding: several primary-replica groups, each owning part of the data. Scales writes; adds routing and cross-shard complexity.
- Multi-leader replication: writes accepted in several places, with conflict resolution.
- Leaderless replication (Dynamo-style quorums): any replica takes writes; consistency is tuned per request.
- Consensus-replicated databases (CockroachDB, Spanner, YugabyteDB, TiDB): a leader per data range elected by Raft or Paxos; failover is built in, and writes scale across ranges.
- Shared-storage designs (Aurora, AlloyDB, Neon): replicas read from a replicated storage layer instead of replaying a full log.
Failure modes
- Primary failure. Writes fail until promotion and repointing finish; with asynchronous replication, the promoted replica may lack the last acknowledged writes.
- Split brain. A partition makes the primary look dead; a replica is promoted while the old primary still accepts writes from clients that can reach it. Two diverging histories, usually resolved by hand. Prevented by fencing and quorum-based failure detection.
- Undersized promotion. The promoted replica is smaller than the old primary, or the remaining replicas cannot absorb its read share.
- Stale endpoints. Clients cache DNS or connection pools keep pointing at the old primary after failover.
- Failover flapping. Aggressive detection fails over on transient load spikes, and each failover causes its own outage.
- Replica set drift. After a failover, other replicas still follow the old primary and stop receiving changes.
In production
Run at least one replica in another zone, sized to take over as primary. Automate failover with a tool that uses a consensus store or the cloud control plane for leader decisions, and fence the old primary. Practise failover regularly (planned switchovers are a good drill) and measure the write outage end to end, from the client's point of view. Keep connection strings pointing at a stable endpoint (proxy, VIP or managed endpoint) rather than a host. Alert on replica lag and on the number of healthy replicas, and size the read tier for N+1 so promotion or a replica loss does not overload the rest.
Common misconceptions
- "Add replicas and the database scales." Reads scale. Writes stay on one machine, and every replica adds replay work.
- "Failover is instant." Detection, promotion and repointing take seconds to minutes, and writes fail throughout.
- "A restarted primary can just rejoin." It is behind and may have diverged; it must be rewound or re-cloned as a replica.
- "Replicas are idle standbys, so they're free." Each one replays every write, consumes I/O, and must be monitored for lag.
Interview angle
State the single-writer rule early and draw the routing layer explicitly. Then quantify: reads per replica, writes on the primary, and where the ceiling is. Expect "what if writes grow?" (bigger primary, reduce writes, shard), "what happens when the primary dies?" (detect, choose, promote, repoint, fence, with a write outage and possibly lost writes under async), and "how do you avoid split brain?" (fencing, quorum-based leader election). Mentioning that the promoted replica must be sized like the primary, and that the read tier loses a node in the process, shows you have thought about the operational reality.
Model assumptions
The simulation is a simplified model, not a benchmark. Every database has 12 connections, a 30 ms mean read and a 40 ms mean write (lognormal, cv 0.4); a query waiting more than 500 ms for a connection fails. A replica serves about 400 reads/s; the primary about 300 writes/s ("36 connections" stands in for a primary with three times the capacity). Queries use 500 keys with Zipf(1.0) popularity. A proxy sends writes to the node configured as the write target and balances reads by least connections over healthy replicas (health checks every 500 ms; 2 failures eject, 2 successes restore). Replication is asynchronous with about 7 ms of lag, and applying changes costs a replica nothing (in real databases replay uses replica capacity). Promotion is modelled: at a fixed time Replica 1 takes over the primary's replication links and settings, the old primary becomes its replica, the proxy sends writes to Replica 1, and acknowledged writes Replica 1 never received are counted as lost (here at most one or two, because the lag is short). Changes the old primary had not yet shipped when it crashed are gone; when it restarts it receives Replica 1's new changes but nothing from its outage, and the recap shows it after a rebuild, as a full replica. Not modelled: detection and the decision to fail over (the promotion time is fixed), choosing the most up-to-date replica, fencing, DNS or client-side caching of endpoints, and the old primary's own unreplicated writes. Numbers show behaviour and orders of magnitude only.