What it is
Replication keeps copies of the same data on several database servers. In the most common setup, primary–replica (also called leader–follower), one server, the primary, accepts all writes. It records each change in a log and ships that log to the replicas, which replay it in the same order. Applications send writes to the primary and can send reads to any replica.
Why it exists
Three reasons, in roughly the order teams meet them:
- Read capacity. Most applications read far more than they write. One server has a fixed number of connections and a fixed time per query; replicas multiply the read capacity.
- Availability and durability. If the primary dies, a replica that already has the data can be promoted. Without a copy, a dead disk means restoring from backup and losing everything since.
- Isolation. Reports, analytics and backups run on a replica so they don't slow the primary down.
How it works
Shipping changes. The primary writes each change to its log (the write-ahead log in PostgreSQL, the binlog in MySQL) and streams it to every replica. A replica applies the changes in order, so it shows the primary's state as of some moment in the past. How far in the past is the replication lag.
Routing. Something has to send writes to the primary and reads to replicas: the application itself (two connection strings), a database proxy (ProxySQL, PgBouncer with routing, a cloud reader endpoint), or the driver. In the lesson a proxy does it.
Asynchronous replication. The primary acknowledges a write as soon as it has stored it locally and ships it afterwards. Writes are fast and unaffected by replicas, but replicas lag, and anything not yet shipped exists only on the primary.
Synchronous replication. The primary acknowledges only after the replicas have the write. Replicas are never behind what clients were told, but every write waits for the slowest replica, and if a replica cannot answer, writes wait or fail.
Semi-synchronous and quorum replication. The middle ground: wait for one replica (MySQL semi-sync, PostgreSQL synchronous_standby_names with ANY 1), or for a majority (consensus systems like etcd, CockroachDB, and the quorum writes of leaderless stores). At least one other machine has every acknowledged write, and one slow or dead replica does not block writes.
Read-your-writes. A user who just wrote something expects to see it. With async replicas that is not guaranteed. Common fixes: read from the primary for a short time after the user writes; remember the log position of the user's last write and read only from replicas that have reached it; or keep the user's session pinned to the primary for writes-then-reads flows.
When to use it
- Read-heavy workloads where one server's reads are the bottleneck and a little staleness is acceptable for most reads.
- Any database whose data you cannot afford to lose to a single machine failure (that is: almost every production database).
- Separating heavy analytical queries or backups from the transactional primary.
When not to
- Write-bound workloads. Replicas do not add write capacity; each one replays every write. Shard, batch or reduce writes instead.
- Reads that must be current (balances before a transfer, inventory at checkout, permission checks right after a change): route those to the primary rather than replicas, or use synchronous replication for that data.
- Before simpler fixes. A missing index or a cache in front of hot reads often removes the read load replicas were meant to absorb.
Trade-offs
| Choice | You gain | You pay |
|---|---|---|
| Async replication | Fast writes, replicas never block the primary | Stale reads; acknowledged writes can be lost on failover |
| Sync replication (all replicas) | Fresh replicas, no loss on failover | Write latency of the slowest replica; one dead replica blocks writes |
| Semi-sync / quorum | No single-replica dependency, at least one extra copy of every write | Some write latency; still stale reads on replicas outside the quorum |
| More replicas | More read capacity, more failover candidates | More replication traffic and lag to monitor; writes unchanged |
| Reads from replicas by default | Offloads the primary | Must route read-your-writes and must-be-current reads to the primary |
Alternatives
- Caching hot reads (cache-aside) takes load off the database with lower latency than a replica, with its own staleness to manage.
- Sharding splits data across several primaries, which scales writes as well as reads, at a large cost in complexity.
- Multi-leader and leaderless replication accept writes in several places (multi-region writes, high write availability) and pay with conflict resolution.
- Managed distributed SQL (Spanner, CockroachDB, Aurora's shared storage) hides replication behind consensus or a replicated storage layer.
Failure modes
- Replica failure. Reads on it fail until the proxy stops routing to it; the remaining replicas take its share, so size for N+1. Under sync replication it can also block writes until it is removed from the synchronous set.
- Primary failure. Writes fail until a replica is promoted and clients are pointed at it. With async replication the promoted replica may be missing the last writes the old primary acknowledged.
- Split brain. The old primary was not really dead (a network partition) and keeps accepting writes after a replica was promoted. Two primaries diverge. Fencing (revoking the old primary's ability to write) prevents it.
- Lag spikes. Long transactions, a replica running heavy reports, a write burst or a slow network make lag jump from milliseconds to minutes. Reads that tolerate "a bit stale" may not tolerate that.
- A replica that falls too far behind can no longer catch up from the primary's retained log and must be rebuilt from a fresh copy.
In production
Monitor replication lag per replica and alert on it; remove replicas from read rotation when lag exceeds what the application tolerates. Automate failover (Patroni, Orchestrator, managed services), test it regularly, and know your recovery point objective (how much data a failover may lose). Use semi-sync or a synchronous standby in another zone when acknowledged writes must survive the loss of the primary. Keep must-be-current reads on the primary.
Common misconceptions
- "Replicas make the database faster at everything." They add read capacity. Writes go through one primary and are replayed on every replica.
- "Replication is a backup." A bad
DELETEreplicates to every replica within milliseconds. Backups and point-in-time recovery protect against mistakes; replicas protect against machine failure. - "If the write was acknowledged, it's safe." With async replication it exists on one machine until shipped. Lose that machine and the write is gone.
- "Synchronous replication is always better." It trades write latency and write availability for freshness. For most data, semi-sync plus sensible read routing is the better balance.
Interview angle
When a design is read-heavy, add read replicas and say how reads are routed. Then expect the follow-ups: what happens to a user who reads right after writing (read-your-writes; route to the primary), what lag you expect and how you monitor it, sync or async and why, how failover works and how much data it can lose, and why replicas don't help a write-heavy workload (that's where sharding comes in). Putting numbers on it ("10k reads/s, 400 per replica at our query cost, so 30 replicas or a cache first") shows you are reasoning, not reciting.
Model assumptions
The simulation in this lesson is a simplified model, not a benchmark. Every database has 12 connections, a 30 ms mean read and a 15 ms mean write (lognormal, cv 0.4); a query waiting more than 500 ms for a connection fails. 10% of queries are writes, over 200 keys with a Zipf(1.0) popularity, so a few keys are hot. A proxy sends writes to the primary and balances reads round robin over healthy replicas (health checks every 500 ms; 2 failures eject). The primary ships each write to every replica after the network hop plus a fixed extra lag; with asynchronous replication applying it costs the replica no time, so lag is measured to arrival. Synchronous mode acknowledges once all replicas have applied the write (a further 15 ms each, their own write time) and their acknowledgements have travelled back, so a synchronous write takes the delay, the apply and the hop home; it keeps its primary connection meanwhile, so the primary has 48 connections in the synchronous steps (12 would run out). A read is counted as stale when the replica has not yet applied a write the primary had already acknowledged for that key. Changes the primary has not delivered when it crashes are lost. Promotion happens at a fixed time (detection and the decision are not modelled): the promoted replica takes over the replication links, the proxy sends writes to it, and the simulation counts the keys whose latest acknowledged write it never applied; the recap hands the role back to the rebuilt original primary. Not modelled here: catch-up of a replica after it restarts (it misses the writes of its outage) and semi-synchronous or quorum modes (see the Synchronous Replication and Quorum lessons). Numbers show behaviour and orders of magnitude only.