Course contents

05. Distributed Databases Lesson 2 of 10

Primary-Replica Architecture

One writer, many readers: watch replicas scale reads, the primary cap writes, and a failover promote a replica while clients see the outage.

16 minIntermediate8 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Exactly one node, the primary, accepts writes; replicas are read-only copies that replay its change stream.
  • Replicas add read capacity roughly linearly, but every replica receives and replays every write.
  • Write throughput is capped by the primary: scale it up, reduce writes, or shard. More replicas never help writes.
  • Failover is a sequence (detect, choose, promote, repoint, fence); writes fail for its whole duration while reads continue.
  • The old primary must be fenced and rebuilt as a replica of the new one; letting it rejoin as-is risks stale reads or split brain.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

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:

  1. 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.
  2. Choose. Pick the replica with the most of the primary's log (highest replayed LSN or GTID set), so the least data is lost.
  3. Promote. The chosen replica stops replaying and starts accepting writes (pg_promote() in PostgreSQL).
  4. 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.
  5. 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.

The lesson as textEvery step of the simulation, written out.
  1. 1. One writer, many readers

    Each node has one job. The primary is the only node that accepts writes. The replicas are read-only copies: they take reads and replay the primary’s change stream (the purple replication packets).

    The DB proxy enforces the split. It sends every write (10% of the 600 queries per second) to the primary and spreads the reads round robin over the three replicas. Each replica serves about 180 reads per second and is a bit under half busy; the primary handles 60 writes per second.

    Scene: An app tier sends 600 queries per second through a DB proxy. Writes (10%) go to the primary, reads are spread over three replicas, and the primary streams every change to each replica.

    Key idea: Primary-replica means a single writer. Everything else in this lesson follows from that one rule.

  2. 2. Read traffic nearly doubles

    Traffic grows to 1,100 queries per second: about 990 reads and 110 writes. Each replica now gets about 330 reads per second, more than 80% of what it can serve. Latency still looks fine, but there is almost no headroom: one more traffic bump, or one replica failing and its share moving to the other two, and they saturate.

    The primary barely notices: 110 writes per second keep it under half busy. The read side is the bottleneck.

    Scene: At 1,100 queries per second each replica is more than 80% busy, with little headroom left. The primary stays under half busy.

    Key idea: Reads and writes load different machines. Find out which side is saturated before you scale.

  3. 3. Scale reads: add a replica

    We add Replica 4. The proxy spreads the same 990 reads over four replicas, about 250 each, and their utilisation falls to about 60%: headroom is back.

    Adding replicas is cheap for reads, but it is not free for the primary: it now sends four copies of every change instead of three (count the replication packets). In real databases each replica also replays every write, so a replica spends part of its capacity on writes it never serves, and each extra replica is another stream the primary has to feed and another lag to watch.

    Scene: A fourth replica joins. Each replica now serves about 250 reads per second and is about 60% busy; the primary sends every change to four replicas.

    Key idea: Replicas add read capacity linearly, but every replica receives and replays every write: the write stream fans out with the replica count.

  4. 4. The write share grows

    A new feature writes on almost every page view. One second in, the write share rises from 10% to 30%; at 2.5 s it reaches 50%. That is 550 writes per second against a primary that can do about 300.

    The primary’s connections are all busy, writes queue, and those that wait longer than 500 ms fail. Meanwhile the replicas get quieter: there are fewer reads to serve, and they sit at about a third busy. Four replicas, mostly idle, and no way to give them writes.

    Scene: The write share rises to 50%. The primary saturates and writes fail with pool timeouts, while the four replicas are only about a third busy.

    Key idea: The primary is a hard ceiling on write throughput. Replicas cannot take any of it.

  5. 5. Only the primary can fix writes

    The options for a write bottleneck all act on the primary or on the writes themselves: a bigger primary, fewer or cheaper writes (batching, dropping redundant indexes), or sharding, which splits the data over several primaries.

    Here we scale the primary up to three times its capacity (36 connections stand in for more cores and faster storage). Writes stop failing and the primary settles at about 60% busy. Note the asymmetry this creates: the primary is now a much bigger machine than any replica.

    Scene: The primary is scaled to three times the capacity. Writes stop failing and the primary is about 60% busy.

    Key idea: Write capacity comes from a bigger primary, fewer writes, or more primaries (sharding). More replicas never help.

  6. 6. The primary dies; promote a replica

    The write share is back to 10%. One second in, the primary crashes. Watch what clients see:

    First second: the proxy still sends writes to the dead primary and they are refused. Then the health checks eject it and writes fail fast with "no backend". Reads never stop: the replicas keep serving.

    At 4 s a failover tool promotes Replica 1: it becomes the primary, the proxy sends it the writes, and Replicas 2–4 now replay *its* change stream (the purple packets leave Replica 1). It stops serving reads, so three replicas carry all of them and run above 80% busy. About three seconds of failed writes in total. With only ~7 ms of lag, at most a write or two acknowledged just before the crash never reached Replica 1; a busier, laggier primary would lose more. Real failover takes from seconds to a minute (detection, choosing the most up-to-date replica, fencing, repointing), and the promoted replica is the small one: a primary that needed 3× capacity for a write-heavy load would now be undersized.

    Scene: The primary crashes at 1 s. Writes are refused, then fail with no backend after the proxy ejects it; reads continue. At 4 s Replica 1 is promoted: writes succeed again on it and the other replicas replicate from it.

    Key idea: Failover = detect, pick a replica, promote, repoint clients. Writes fail for the whole window; reads carry on.

  7. 7. The old primary comes back

    One second in, the old primary restarts. The failover tool already made it a replica of Replica 1, so it receives the new primary’s changes from now on, and the proxy’s health checks put it back into rotation about a second later, as a read backend.

    But it missed every write made while it was down, and nothing sends those to it. Watch the stale reads tile: reads it serves of keys written during the outage return old data, and only fade as those keys happen to be written again. Had any app server still been configured with its address as the primary, it would have accepted writes too: two primaries diverging, a split brain.

    A failed primary must never rejoin as-is. It is fenced (blocked from writing, its old endpoint revoked) and then rebuilt as a replica of the new primary, by rewinding it to the point where histories diverged (PostgreSQL’s pg_rewind) or re-cloning it.

    Scene: The old primary restarts as a replica of Replica 1. The proxy starts sending it reads; it receives new changes but lacks every write made while it was down, so some of its reads are stale. Writes keep going to Replica 1.

    Key idea: After failover the old primary is a liability until it is fenced and rebuilt as a replica of the new one.

  8. 8. The new shape

    The old primary has been re-cloned from Replica 1 on replica-sized hardware and serves reads as a full, current replica. Replica 1 is the primary now, streaming to the old primary and Replicas 2–4, and the proxy sends it every write. Four readers again, each about 60% busy: rebuilding (or replacing) the lost reader is the first job after a failover.

    The architecture has a few fixed properties: one writer sets the write ceiling; replicas scale reads and must each replay every write; failover is a sequence (detect, promote, repoint, fence) with a write outage the length of that sequence. When writes outgrow one primary, the next step is sharding, not more replicas.

    Scene: Replica 1 is the new primary and replicates to the rebuilt old primary and Replicas 2, 3 and 4. The proxy sends writes to it and reads to the four replicas, each about 60% busy. Nothing fails.

    Key idea: Replicas scale reads and give you failover targets; the single primary sets your write ceiling and your write outage during failover.