Summary#
Replication keeps copies of the same data on several machines. It gives availability (survive a server loss), read scaling (spread reads over copies) and lower latency (a copy near users). Three topologies exist: leader-follower (one node takes writes, followers copy them; the default for SQL databases), multi-leader (several nodes take writes, conflicts must be resolved) and leaderless (any node takes writes, with quorums). Replication can be synchronous (safe, slower), asynchronous (fast, may lose recent writes on failover) or semi-synchronous. Asynchronous followers lag, so design for read-your-writes. Failover must avoid split-brain, and multi-writer systems need conflict resolution.
Why It Exists#
One database server is a single point of failure and a hard ceiling on read capacity. Disks die, machines are patched, data centres lose power. If the only copy of your data is on that server, you are down (or worse, data is lost) until it returns. Replication solves three problems at once:
- Availability and durability: another copy can take over within seconds.
- Read scaling: most applications read far more than they write (10:1 or 100:1), and replicas multiply read capacity.
- Latency: a replica in Europe serves European users in a few milliseconds instead of a 90 ms round trip to the US.
This page builds on ACID and Isolation Levels.
How It Works#
Topologies#
| Leader-follower | Multi-leader | Leaderless | |
|---|---|---|---|
| Who accepts writes | One leader (primary) | Several leaders, usually one per region | Any replica; client writes to several |
| Conflicts | None (one writer orders all changes) | Yes, must be resolved | Yes, resolved by versions or timestamps |
| Read scaling | Add followers | Each leader also serves reads | Read from a quorum |
| Failure handling | Failover: promote a follower | Other leaders keep working | No failover; tolerates node loss by quorum |
| Examples | PostgreSQL, MySQL, MongoDB replica sets, Redis | MySQL/Postgres with multi-primary tools, CouchDB, collaborative and offline apps | Cassandra, ScyllaDB, Riak, Amazon's Dynamo |
Leader-follower (also called primary-replica or master-slave): the leader writes each change to its log and streams it to followers, which apply it in the same order. It is simple and avoids conflicts, so it is the default.
Multi-leader: each data centre has its own leader that accepts local writes and replicates to the others asynchronously. Writes are fast everywhere and each region survives alone, but two regions can change the same record concurrently, creating conflicts. Offline-capable apps (a calendar on a phone) are a form of multi-leader: each device is a leader while offline.
Leaderless: the client (or a coordinator node) sends each write to several replicas and reads from several, using quorums to find the latest value. See Quorums and Leaderless Replication.
Topologies in depth#
What actually flows from leader to follower. Every leader-follower database replicates a log, an ordered record of changes.
- PostgreSQL streams its write-ahead log (WAL). A
walsenderprocess on the primary pushes WAL records to awalreceiveron each standby, which writes them to disk, and a startup process replays them. Followers identify their progress by log sequence number (LSN). - MySQL replicates its binary log. A receiver thread on each replica copies events into a relay log, and applier threads execute them. Global transaction IDs (GTIDs) name each transaction, so a replica can be re-pointed at a new source without hunting for file offsets.
- MongoDB replica set members tail the primary's oplog, a capped collection of idempotent operations.
- Redis replicas receive a stream of write commands. After a short disconnection they resume from a replication backlog buffer (
PSYNC). If the gap is larger than the backlog, they must take a full snapshot again.
Replication slots and retention. A follower that falls behind needs the leader to keep the log it has not yet consumed. PostgreSQL replication slots guarantee that retention. The danger is that a dead follower, or a stalled CDC consumer, with an active slot makes the primary keep WAL forever, until the primary's disk fills and it stops. Set max_slot_wal_keep_size (PostgreSQL 13 and later), and alert on slot lag. MySQL keeps binlogs for a configured period (binlog_expire_logs_seconds). A replica that falls further behind than that must be rebuilt from a snapshot.
What a follower costs the leader. Each follower adds one log stream of network bandwidth and a little CPU on the leader, but not query load. Ten followers of a primary writing 50 MB per second of WAL need 500 MB per second of outbound bandwidth. That is why large fleets use cascading replication, where some followers feed others. The trade-off is extra lag at each hop, and a mid-tier follower failure orphans its children until they re-attach.
Multi-leader topologies. With three or more leaders, changes must travel along some graph:
- All-to-all: every leader sends to every other. It is the most fault-tolerant, but changes can arrive in different orders at different leaders. Suppose an insert travels from A to C slowly, while an update to the same row travels from B to C quickly. C sees the update before the insert. Systems handle this with version vectors, or by buffering until dependencies arrive.
- Circular or star: each change passes through intermediate leaders, so ordering is easier. But one failed node can break the ring, and each node must tag changes with their origin to stop them looping forever.
The disadvantages of multi-leader, as the primer lists them, are worth remembering:
- Writers need a load balancer or application logic to decide where to write.
- Most such systems are either loosely consistent, breaking ACID guarantees across leaders, or slow, because leaders synchronise on writes.
- Conflict resolution gets harder as you add leaders and as the latency between them grows.
Leaderless placement, Cassandra as the example. In Cassandra, the partition key is hashed onto a consistent-hashing ring of virtual nodes (vnodes). To place replication_factor copies, Cassandra starts at the vnode that owns the hash and walks clockwise, collecting distinct physical nodes. It skips vnodes that belong to a physical node already chosen, so one machine failure never takes out two replicas. Two strategies control the walk:
-- testing / single data centre: plain clockwise walk
ALTER KEYSPACE app WITH REPLICATION =
{'class': 'SimpleStrategy', 'replication_factor': 3};
-- production: rack- and data-centre-aware, per-DC replica counts
ALTER KEYSPACE app WITH REPLICATION =
{'class': 'NetworkTopologyStrategy', 'dc1': 3, 'dc2': 2};NetworkTopologyStrategy also spreads replicas across racks within each data centre, so a rack power failure leaves the other copies alive. Any node can act as the coordinator for a request. It forwards the write to all replicas and waits for as many acknowledgements as the consistency level requires (ONE, QUORUM, LOCAL_QUORUM, ALL).
When a replica is down, the coordinator stores a hint, a copy of the missed write, and replays it when gossip reports the node is back (hinted handoff). Hints expire after a few hours by default, so a node that stays down longer is brought back in line by read repair or a full anti-entropy repair. Failure detection uses a phi accrual detector over gossip heartbeats. A "convicted" node stays in the ring until an operator removes it, so a brief restart does not trigger a costly data rebalance. See Consistent Hashing and Failure Detection and Gossip.
Failover patterns at the server level. The primer separates two availability patterns.
- Active-passive: the standby receives heartbeats and takes over the active node's IP address or DNS name when they stop. A hot standby is already running and caught up, so takeover takes seconds. A cold standby must boot and restore first, which can take minutes to hours.
- Active-active: both nodes serve traffic, and clients must know both addresses, through DNS for public services or application configuration for internal ones.
Both add hardware and complexity. Both can lose data if the active node dies before its latest writes reach the other node. That loss window is exactly the asynchronous replication gap.
Synchronous, asynchronous and semi-synchronous#
- Synchronous: the leader confirms a commit only after a follower has the change. No committed data is lost if the leader dies, but every commit waits for the follower (sub-millisecond in a zone, 1-2 ms across zones, ~100 ms across continents), and a slow or dead follower blocks writes.
- Asynchronous: the leader confirms immediately and ships changes in the background. Fastest, and followers can be far away, but if the leader dies, the last changes not yet copied are lost on failover.
- Semi-synchronous: the leader waits for at least one of several followers to confirm receipt, then continues. MySQL semi-sync and PostgreSQL's
synchronous_standby_nameswithANY 1 (...)work this way. This gives no data loss on a single failure without waiting on every follower.
Common setup: one synchronous (or semi-sync) follower in another availability zone for safety, plus asynchronous followers for reads and distant regions.
Synchronous and asynchronous in depth#
What "acknowledged" can mean. PostgreSQL's synchronous_commit shows how many durability levels exist between "fast" and "safe":
| Setting | Commit returns after | Survives |
|---|---|---|
off | WAL is in memory on the primary (flushed within about 3 × wal_writer_delay) | Nothing: a crash can lose the last few hundred milliseconds |
local | WAL flushed on the primary's disk | Primary crash with disk intact |
remote_write | Standby received the WAL and handed it to its operating system | Primary loss, unless the standby's OS also crashes |
on (with sync standbys) | Standby flushed the WAL to disk | Loss of the primary machine |
remote_apply | Standby replayed the change, so it is visible to reads there | Loss of the primary, and gives read-your-writes on that standby |
Each step adds latency, roughly one network round trip plus a disk flush on the standby. In one availability zone that is about 0.2-1 ms per commit. Across zones in a region it is 1-2 ms, and across continents 70-150 ms. This is why synchronous replication is almost always kept inside a region.
Quorum commit. synchronous_standby_names = 'ANY 2 (s1, s2, s3)' waits for any two of three standbys. A single slow standby no longer stalls commits, and two copies besides the primary always hold every committed transaction. FIRST 1 (s1, s2) instead names a priority order. MySQL's semi-synchronous replication waits for a configurable number of replicas to acknowledge receipt (rpl_semi_sync_source_wait_for_replica_count). Since MySQL 5.7 the default AFTER_SYNC mode waits before the commit becomes visible on the source. That "lossless" semi-sync avoids a window in which other clients could read a transaction that a failover then loses.
When the synchronous follower dies. If the only synchronous standby dies, a strictly synchronous primary blocks all commits, which makes the system less available. Tools usually degrade to asynchronous mode after a timeout. MySQL semi-sync does so after rpl_semi_sync_source_timeout, 10 seconds by default. Patroni's synchronous_mode picks another standby, and synchronous_mode_strict refuses to degrade. Which to choose is a business decision: stop taking orders, or take them with a risk of losing the last few after a second failure.
RPO and RTO. Two numbers frame every replication choice.
- Recovery point objective (RPO) is how much data you can afford to lose. Asynchronous replication gives an RPO equal to the lag, usually under a second but unbounded in the worst case. Synchronous replication gives an RPO of zero.
- Recovery time objective (RTO) is how long you can be down. It is set by failure detection time plus promotion time plus client reconnection time, typically 30-120 seconds for managed databases.
State both numbers when you choose a topology. See Disaster Recovery.
Quorum storage: Amazon Aurora. Aurora moves replication below the database engine. "Amazon Aurora: Design Considerations for High Throughput Cloud-Native Relational Databases" (Verbitski and colleagues, SIGMOD 2017) describes how the primary sends only redo log records to a storage layer that keeps six copies of each 10 GB segment, two in each of three availability zones. A write succeeds when 4 of 6 copies acknowledge it, and reads need 3 of 6. The storage tier survives the loss of a whole zone plus one more node without losing data, and keeps accepting writes after losing a zone. Read replicas share the same storage volume, so they need no separate copy of the data and typically lag by tens of milliseconds.
Chain replication. "Chain Replication for Supporting High Throughput and Availability" (van Renesse and Schneider, OSDI 2004) orders replicas in a chain. Writes enter at the head and flow down. A write is committed when it reaches the tail, and reads are served by the tail. Every read therefore sees only fully replicated data, giving strong consistency, and the head and tail split the load. The cost is write latency proportional to chain length. Research systems such as FAWN-KV (SOSP 2009) and CRAQ (USENIX ATC 2009) build on it, CRAQ letting every replica serve reads of committed versions.
Consensus as synchronous majority replication. Raft and Multi-Paxos replicate a log to a majority before committing. With 3 replicas, one may be slow or dead without blocking writes, and with 5, two may. That is strictly better than "wait for one specific standby". Leader election is built in and safe against split-brain, because a new leader needs a majority vote. etcd, ZooKeeper, CockroachDB, TiDB, YugabyteDB, Spanner and MongoDB replica sets, whose protocol is Raft-like since version 3.2, all work this way. See Consensus.
Replication lag and read-your-writes#
With asynchronous followers, a change reaches followers after a delay, the replication lag. It is usually milliseconds, but rises to seconds or minutes under heavy write load, long queries on the follower or network trouble. Lag causes visible anomalies:
Fixes, from simplest:
- Read-your-writes from the leader: for a short window (say 5-10 seconds) after a user writes, or for that user's own data, route their reads to the leader.
- Track positions: after a write, remember the leader's log position (LSN in Postgres, GTID in MySQL); read from a follower only if it has applied at least that position, otherwise use the leader or wait.
- Sticky reads (monotonic reads): pin each user to one follower so they never see time go backwards by switching to a more-lagged replica.
- Consistent prefix: in partitioned systems, keep causally related writes in the same partition so readers never see an answer before its question.
See Consistency Models.
Replication lag in depth#
The session guarantees. "Session Guarantees for Weakly Consistent Replicated Data" (Terry and colleagues, 1994, from the Bayou project) named the guarantees users actually notice:
- Read your writes: after I write, my reads reflect that write.
- Monotonic reads: once I have seen a value, I never later see an older one.
- Writes follow reads: if I write after reading something, my write is ordered after what I read.
- Monotonic writes: my writes are applied in the order I made them.
Lagging asynchronous replicas can break all four. Each is fixed by tracking positions rather than by making the whole system synchronous. A stronger guarantee, consistent prefix reads, says readers see writes in an order that respects causality. It matters when related writes land in different partitions with different lag. See Consistency Models.
Where lag comes from, in numbers. In a healthy setup within one region, lag is a few milliseconds. Lag has several sources:
- Replay throughput. A replica that replays serially can apply perhaps 20-50 MB per second of WAL. A primary bulk-loading at 200 MB per second builds lag at about 150 MB per second, so a 10-minute load can leave replicas more than a minute behind.
- Long transactions. On MySQL, a single 30-minute
UPDATEreplicates as one event and replays for about 30 minutes on each replica. Nothing behind it moves, and parallel appliers cannot help. - Replica query conflicts. Long queries on a PostgreSQL standby can pause replay, up to
max_standby_streaming_delay. - Network. Cross-region links add tens to hundreds of milliseconds of baseline lag, and bandwidth caps limit catch-up after a burst.
- Resource starvation. A replica on smaller hardware, or one saturated by read traffic, falls behind under load.
Measuring lag correctly. PostgreSQL's pg_stat_replication on the primary reports write_lag, flush_lag and replay_lag per standby, and byte lag can be computed with pg_wal_lsn_diff(sent_lsn, replay_lsn). MySQL's Seconds_Behind_Source compares event timestamps and is misleading in two ways. It reads 0 when the replica is idle and when its receiver is broken, and it jumps when long transactions arrive. The robust method is a heartbeat table. A job on the primary writes the current time to a row every second, and lag on each replica equals now minus the replicated timestamp. Percona's pt-heartbeat does this. Alert on lag in seconds, and also on whether the replication threads are running.
Implementing read-your-writes with log positions. The precise fix is to carry the commit position with the user's session.
// After a write on the primary, capture its WAL position.
const { lsn } = await primary.one("SELECT pg_current_wal_lsn() AS lsn");
session.minLsn = lsn; // store in session or cookie
// On a later read, use a replica only if it has replayed that far.
async function readPool(session: Session) {
if (!session.minLsn) return pickReplica();
for (const r of replicasByLowestLag()) {
const ok = await r.one(
"SELECT pg_last_wal_replay_lsn() >= $1::pg_lsn AS ok", [session.minLsn]);
if (ok.ok) return r;
}
return primary; // nobody caught up: fall back
}The check costs one tiny query, and in practice replica routers cache each replica's replay position for a few milliseconds instead of asking per request. MySQL offers the same idea with GTIDs: WAIT_FOR_EXECUTED_GTID_SET(gtid, timeout) blocks until the replica has applied the transaction. MongoDB has causally consistent sessions that pass an afterClusterTime automatically.
Cross-device read-your-writes. If a user edits their profile on a phone and opens a laptop, the laptop session has no stored position. Either keep the last-write position in a server-side record keyed by user ID, or route reads of a user's own data, such as profile and settings, to the primary, while other users' data comes from replicas. The second option is simpler and usually cheap, because own-data reads are a small fraction of traffic.
Monotonic reads in practice. Load balancers that spread each request across replicas at random can show a comment, then hide it on refresh, then show it again, as requests alternate between a fresh and a lagging replica. Pin each session to a replica, hashing on user ID, so a user's view only moves forward. Re-pin only when that replica fails or exceeds the lag threshold.
Read replica pattern#
Route writes to the primary and most reads to replicas:
- In the application: two connection pools,
primaryandreplica; the data layer picks per query. - In a proxy: ProxySQL, PgPool-II, or cloud reader endpoints (Amazon Aurora reader endpoint) that balance across replicas.
- Rules: anything inside a write transaction, read-after-write paths and strongly consistent reads go to the primary; feeds, search pages, reports and analytics go to replicas. Remove replicas from rotation if their lag exceeds a threshold.
Replicas scale reads, not writes: every replica must apply every write. See Pattern: Scaling Reads.
Read replicas in depth#
Why reads are the first bottleneck. Read traffic usually grows much faster than write traffic. Opening a photo feed may trigger dozens to hundreds of queries for posts, authors, like counts and comment previews. The user who posts once a day causes one write. Read-to-write ratios start around 10:1 and reach 100:1 or more for content-heavy products. The usual progression has three steps:
- Make reads cheap inside the database, with indexes and denormalised read models.
- Spread them across replicas.
- Put caches (Redis, CDNs) in front for the hottest data.
Replicas are the middle step. See Pattern: Scaling Reads.
Capacity arithmetic. Suppose a primary sustains 30,000 simple reads a second at 60% CPU, and writes take 20% of its capacity. Each replica pays most of that 20% to replay the same writes, leaving about 80% for reads, roughly 40,000 reads a second on the same hardware. Five replicas then give about 200,000 reads a second. Two limits appear as you add more:
- Write share. As writes grow, every replica's spare capacity shrinks together. At 80% write load, a replica has almost nothing left for reads. Replicas buy no time against write growth.
- Working set per replica. Each replica caches the same hot data, so ten replicas do not give ten times the buffer cache. If the working set does not fit in one machine's RAM, every replica misses equally. Sharding, not replicas, divides the working set.
Routing rules that hold up.
- Reads inside a transaction that also writes go to the primary. Mixing pools mid-transaction gives inconsistent snapshots.
- Writes followed by redirects ("save, then show the saved page") read from the primary, or wait for a position.
- Lists, searches, feeds, counts and other users' profiles can usually tolerate seconds of lag and go to replicas.
- Reports and exports go to a dedicated analytics replica, so a 10-minute scan cannot evict the hot data that user-facing replicas cache.
Lag-aware load balancing. A replica that falls behind should be drained automatically, not left to serve stale data until someone notices. ProxySQL's max_replication_lag, Amazon Aurora reader endpoints, and Vitess tablet health checks all remove lagging replicas from rotation. Beware the cascade. If one replica of three is drained, the other two take 50% more load each, slow down, and may lag in turn. Keep enough headroom that losing one replica, through lag or failure, leaves the rest under about 70% utilisation.
When replicas are the wrong answer. A celebrity profile or a viral post can receive a million reads a second for a single key. Replicas spread load across machines, but every replica would be hit by the same key at the same rate, and each read still costs a full query. A cache with request coalescing, which sends one query to the database for many concurrent misses on the same key, plus a CDN for public data, handles that at a fraction of the cost. Replicas suit broad read load over many keys. Caches suit concentrated load on a few keys. Most large systems use both.
Failover and split-brain#
When the leader fails, a follower must be promoted:
- Detect failure, usually by missed heartbeats over a timeout (for example 10-30 seconds). Too short a timeout causes needless failovers during brief slowdowns; too long means longer outages.
- Choose the most up-to-date follower (least data loss).
- Reconfigure: clients and other followers point to the new leader (DNS or virtual IP update, proxy reconfiguration, service discovery).
- Fence the old leader so it cannot accept writes if it comes back.
Split-brain is when two nodes both believe they are leader and both accept writes, so data diverges. It happens when the old leader was only cut off from the network, not dead. Defences: decide leadership by a majority (a consensus system such as etcd, ZooKeeper or Raft inside the database), require the old leader to lose its lease before a new one starts, and fencing (revoke its storage access or reject writes with an old term number). Tools such as Patroni (Postgres) and Orchestrator (MySQL) automate this, and managed databases handle it for you, typically in 30-120 seconds.
Failover in depth#
Detecting failure is the hardest step. A leader that does not answer may be dead, or overloaded, or behind a network partition while it keeps serving other clients. No timeout can tell these apart for certain. In an asynchronous network, a slow node and a dead node look the same. Systems pick a timeout that balances two risks. Too short, and a 5-second garbage-collection pause or an I/O stall triggers a failover, which itself causes disruption and possibly data loss. Too long, and real failures mean long outages. Typical values are 10-30 seconds for databases. The phi accrual failure detector (Hayashibara and colleagues, 2004), used in Cassandra and Akka, replaces a fixed timeout with a suspicion level computed from the history of heartbeat intervals. It adapts to networks that are normally jittery.
A safe automated failover, step by step, with Patroni and etcd as the example:
The key property is that leadership is a lease in a majority-replicated store. Only one node can hold the key at a time, and a primary that cannot reach etcd demotes itself before its lease could have expired. Patroni does this to avoid ever having two writable primaries. The old primary, when it recovers, may have WAL that was never replicated. It must be rewound with pg_rewind to the new timeline, or rebuilt, before it can rejoin as a follower. Those few unreplicated transactions are the data lost under asynchronous replication.
Fencing. Self-demotion depends on the old leader behaving correctly. Fencing enforces it from outside:
- STONITH ("shoot the other node in the head"): power off the old node through its management interface, or detach its cloud volume.
- Storage-level fencing: shared storage rejects writes from the old node.
- Epoch or term numbers: every write carries the leader's term, and replicas and downstream systems reject writes from a lower term. This is the same idea as the fencing tokens used with distributed locks, covered in Distributed Locking.
Client redirection. Clients must find the new leader quickly:
- DNS changes are simple but slow. Clients and resolvers cache records regardless of a low TTL, and connection pools keep old connections open.
- Virtual IPs move in seconds within one network segment.
- Proxies (HAProxy with health checks against Patroni's REST API, PgBouncer, ProxySQL) or cluster-aware drivers (MongoDB, Aurora's smart drivers,
target_session_attrs=read-writein libpq) usually give the fastest and most reliable cutover.
Applications must also retry. In-flight transactions on the old leader fail, and a well-behaved client reconnects and retries idempotent operations.
Choosing which follower to promote. Promote the follower with the highest replayed position, to minimise data loss. Refuse to promote one that is too far behind (Patroni's maximum_lag_on_failover), and prefer a synchronous standby, which by definition has every commit. In MySQL with GTIDs, tools such as Orchestrator compare executed GTID sets, and they can also apply missing transactions from the most advanced replica's relay log to others before re-pointing them.
Failover drills and what goes wrong. Failover code runs rarely, so it rots. Run planned switchovers regularly, for example monthly or during maintenance. Common failure modes include:
- The new leader is undersized, because the standby was a smaller instance.
- Cold caches on the new leader cause a minutes-long latency spike.
- Applications cache the old leader's address.
- Cron jobs still point at the old host.
- Failover loops, where the new leader also gets flagged as unhealthy under the sudden load.
The GitHub incident of October 2018 shows a further risk. Failover across regions during a brief partition produced writes on both sides that took about a day to reconcile. Many teams therefore keep cross-region promotion manual, or allow it only after a much longer timeout.
Conflict resolution#
Multi-leader and leaderless systems accept concurrent writes to the same key and must decide the result:
| Method | How | Risk | Fits |
|---|---|---|---|
| Last write wins (LWW) | Keep the write with the highest timestamp | Silently drops concurrent writes; clock skew can drop the "newer" one | Caches, sensor readings, data where losing an update is acceptable |
| Version vectors | Each replica keeps a counter per writer; the database detects concurrent versions and keeps both as siblings | Application must merge siblings | Shopping carts, Dynamo-style stores |
| Application-level merge | Custom logic: union of cart items, max of counters, field-by-field merge | More code to write and test | Domain data with clear merge rules |
| CRDTs | Data types designed to merge automatically (counters, sets, text) | Limited to supported types | Collaborative editing, counters |
| Avoid conflicts | Route all writes for a record to one "home" leader | Less local-write benefit | Most multi-region designs |
The best strategy is usually to avoid conflicts by giving each record a single home region. See Collaborative Editing and CRDTs.
Conflict resolution in depth#
What counts as a conflict. Two writes conflict when neither "happened before" the other, meaning neither writer had seen the other's write. That is Lamport's happened-before relation, from "Time, Clocks, and the Ordering of Events in a Distributed System" (1978). Writes that are merely close in time do not conflict if one was made with knowledge of the other. Detecting real concurrency needs causal metadata, not wall-clock time.
Last write wins, and why it loses data. LWW attaches a timestamp to each write and keeps the highest. Cassandra does this per cell (column value), so concurrent updates to different columns of one row both survive, but concurrent updates to the same column keep one. Two problems follow:
- Concurrent writes vanish. Two users add different items to the same list stored as one value. One addition disappears silently, and neither writer gets an error.
- Clock skew reorders history. Suppose node A's clock runs 200 ms fast. A write at true time 10:00:00.100 on A is stamped 10:00:00.300, and a later write at true time 10:00:00.200 on node B is stamped 10:00:00.200. The older write wins, and the newer one is discarded. NTP typically keeps servers within a few milliseconds of each other, but misconfiguration, VM pauses and leap-second handling produce larger jumps.
LWW is acceptable when overwrites are naturally idempotent, such as the latest sensor reading, a cache entry, or "last seen at". Avoid it for anything users edit collaboratively or for counters.
Version vectors, worked through. Each replica keeps a counter per replica that has written the key. Take a shopping cart replicated on nodes X and Y.
- A client writes
cart = [book]via X. The version is{X:1}. - The client reads
{X:1}, then adds a pen via X, givingcart = [book, pen]at{X:2}. - Meanwhile, during a partition, another session that had read
{X:1}adds a lamp via Y, givingcart = [book, lamp]at{X:1, Y:1}. - When the versions meet, neither
{X:2}nor{X:1, Y:1}dominates the other. X is higher in one and Y in the other, so they are concurrent. The store keeps both as siblings. - The next read returns both. The application merges them, here into
[book, pen, lamp], and writes the result with a vector that dominates both,{X:2, Y:1}plus one increment.
This is the mechanism in "Dynamo: Amazon's Highly Available Key-value Store" (DeCandia and colleagues, SOSP 2007). The paper notes that the cart merge could resurrect deleted items, because a union does not know that an item was removed. Riak later adopted dotted version vectors, which avoid sibling explosion when many clients write through the same node.
CRDTs: merges that are always correct. Conflict-free replicated data types, formalised in "Conflict-free Replicated Data Types" (Shapiro, Preguiça, Baquero and Zawirski, 2011), are data structures whose merge is commutative, associative and idempotent. Replicas therefore converge whatever the order or number of times updates are delivered. Common examples:
| CRDT | State | Merge | Use |
|---|---|---|---|
| G-Counter | One count per replica | Per-replica maximum, value is the sum | Likes, views |
| PN-Counter | Two G-Counters, increments and decrements | Merge each, value is P − N | Stock adjustments, votes |
| LWW-Register | Value plus timestamp | Keep the higher timestamp | Single fields where LWW is acceptable |
| OR-Set (observed-remove) | Elements tagged with unique IDs, plus removed tags | Union of adds minus observed removes | Carts, tags, membership, with correct deletes |
| Sequence CRDTs (RGA, and the algorithms in Yjs and Automerge) | Ordered elements with unique positions | Interleave by position IDs | Collaborative text editing |
Redis Enterprise's active-active databases, Riak's data types, and Azure Cosmos DB's multi-region writes with custom merge procedures all build on these ideas. The limit is that CRDTs guarantee convergence, not business correctness. Two replicas can each sell the "last" seat, and a counter CRDT will happily converge to minus one. Invariants that span replicas still need coordination. See Collaborative Editing and CRDTs.
Application-level merge strategies beyond CRDTs:
- Field-level merge: if two edits touched different fields of a record, keep both.
- Domain rules: the maximum of two "last login" values, the union of two permission grants, or the minimum of two inventory counts as the safer choice.
- Surface to the user: Git-style conflict markers, or "this note was edited on two devices, choose a version".
Multi-primary PostgreSQL tools such as EDB's BDR (now PGD) and Bucardo let you register conflict handlers per table, and they log every conflict they resolve, which is essential for auditing what was silently overwritten.
Avoiding conflicts by design. The cheapest conflict is the one that cannot happen.
- Give each record a home region (a user's data lives where they signed up), and send all writes for that record to its home, even from other regions.
- Write immutable events instead of updating shared state. Appends with unique IDs never conflict, and the current state is derived by folding the events.
- Partition hot shared objects so each writer owns a slice, such as per-region counters summed at read time.
These designs keep most multi-region systems effectively single-writer per key, which is why true multi-leader conflict resolution is rarer in practice than in textbooks. See Multi-Region and Global Data.
How popular systems replicate#
The same ideas appear with different knobs. Knowing the knob names makes designs concrete.
MongoDB. A replica set has one primary and usually two or more secondaries, with Raft-style elections. The client chooses durability per operation with a write concern. w: 1 is acknowledged by the primary only, while w: "majority" waits until a majority has the write, making it safe across failover. Since MongoDB 5.0, majority is the default. The client chooses freshness with a read concern (local, majority, linearizable) and a read preference (primary, secondaryPreferred, nearest). A w: 1 write can be rolled back if the primary fails before replicating it, and MongoDB writes such rolled-back documents to rollback files for manual recovery.
Redis. Replication is asynchronous. The WAIT numreplicas timeout command blocks until that many replicas have acknowledged previous writes, which improves durability but is not a transaction: a failover can still pick a replica that missed the write. Redis Sentinel or Redis Cluster performs failover. With min-replicas-to-write, a primary stops accepting writes if too few replicas are connected, which limits how much a partitioned old primary can accept. Treat Redis replication as fast and usually right, not as a ledger.
Kafka. Each topic partition is a replicated log with a leader and followers. The followers that are caught up form the in-sync replica set (ISR). A producer with acks=all waits until every ISR member has the record. min.insync.replicas=2 with a replication factor of 3 makes the write fail rather than succeed on a lone replica. Leader election is restricted to ISR members unless unclean.leader.election.enable is turned on, which trades possible data loss for availability. Since Kafka 3.3, KRaft (Kafka's own Raft-based controller quorum) can replace ZooKeeper for cluster metadata, and ZooKeeper support was removed in Kafka 4.0.
DynamoDB. Within a region, each partition is replicated across three availability zones, with a Paxos-elected leader per partition. Eventually consistent reads may hit any replica, and strongly consistent reads go to the leader at twice the read-capacity cost. Global Tables replicate across regions asynchronously, as multi-leader with last-writer-wins conflict resolution, so concurrent writes to the same item in two regions keep one. AWS has since added a multi-region strong consistency mode for Global Tables, which trades higher write latency for no lost writes.
PostgreSQL and MySQL, logical replication. Besides physical streaming, both databases offer logical replication of row changes for chosen tables. PostgreSQL uses publications and subscriptions. MySQL has row-based binlog replication, and Group Replication adds a Paxos-based multi-primary or single-primary mode. Logical replication lets the subscriber have different indexes or extra tables, run a different major version, or receive only some tables. That makes it the standard tool for near-zero-downtime upgrades and for feeding change data capture. See Change Data Capture.
Adding, rebuilding and upgrading replicas#
Seeding a new replica. A new follower needs a consistent copy of the data plus the log from the moment that copy was taken.
pg_basebackupstreams a copy of a running PostgreSQL cluster along with the WAL needed to make it consistent, then the standby streams from there.- MySQL 8.0.17 added the clone plugin, which copies a donor's data over the network. Older setups used Percona XtraBackup.
- MongoDB performs an initial sync: it copies all collections, then applies the oplog from the sync start.
For a multi-terabyte database, seeding is bounded by disk and network throughput. 5 TB at 500 MB per second is about 3 hours. Restoring from a recent storage snapshot and then catching up from archived WAL is usually faster, and it avoids loading the primary.
Major-version upgrades with minimal downtime.
- Create a new cluster on the new version.
- Subscribe it to the old one with logical replication, and let it catch up.
- Verify row counts and checksums, and point read traffic at it to test.
- Stop writes briefly, wait for the subscriber to reach the final position, and switch clients over.
The write pause is seconds to minutes, instead of the hours an in-place dump-and-restore would take. The same pattern underlies blue-green deployments of managed databases such as Amazon RDS Blue/Green. Sequences, schema changes and large objects need extra care, because logical replication in PostgreSQL does not carry DDL or sequence state.
Delayed replicas and backups. A replica configured to apply changes an hour late (recovery_min_apply_delay in PostgreSQL, SOURCE_DELAY in MySQL) gives a window to recover from a destructive mistake. You stop its replay before the bad statement arrives, then extract the lost data. It complements real backups but does not replace them. Proper protection is base backups plus continuous WAL or binlog archiving to object storage, which allows point-in-time recovery to any second within the retention window. Tools such as pgBackRest and WAL-G do this. Restores must be tested, because an untested backup is a hope, not a recovery plan.
Worked example: replication plan for an order database#
Requirements. An e-commerce order database in one primary region handles 3,000 writes a second at peak and 40,000 reads a second. The business states that a confirmed order must never be lost (RPO zero within the region), the checkout must recover from a server or zone failure within a minute (RTO 60 seconds), the service must survive a full region loss with at most a few seconds of data loss, and European customers' order-history pages should load quickly.
Sizing the log. At about 5 KB of WAL per order transaction (row, indexes, and full-page writes after checkpoints), peak WAL volume is about 3,000 × 5 KB ≈ 15 MB per second. The daily average is perhaps a third of that, around 5 MB per second, or about 430 GB a day. This number drives network cost, replica replay capacity, and how long archived WAL takes to restore.
The design.
- Primary in zone A, synchronous standby in zone B with
synchronous_standby_names = 'ANY 1 (b1, c1)', using two candidate standbys in zones B and C so one failure never blocks commits. Commit latency rises by about 1-2 ms, which is acceptable for checkout. That meets RPO zero for a server or zone failure. - Patroni and a 3-node etcd across the three zones, with a leader TTL of 30 seconds and
maximum_lag_on_failoverset low. Expected RTO is 30-45 seconds including client reconnection, which meets the 60-second goal. - Three asynchronous read replicas for order history and search, behind a lag-aware proxy that drains any replica more than 5 seconds behind. At 40,000 reads a second and about 15,000 per replica, three replicas leave headroom to lose one. Order confirmation pages read from the primary for 10 seconds after checkout.
- A cross-region asynchronous replica in the disaster-recovery region. Typical lag is under a second, so in a region loss the RPO is roughly that lag, a few seconds at worst under peak write bursts. Promotion to that region is manual, or automated only after several minutes of confirmed regional outage, to avoid split-brain on a transient partition. Inter-region transfer at about 430 GB a day, at around $0.02 per GB, costs about $9 a day.
- A European read replica serving order history to EU customers in about 10 ms instead of about 90 ms, using the same lag rules. Writes from Europe still travel to the primary region, adding about 90 ms to checkout, which is accepted.
- Backups. Nightly base backups and continuous WAL archiving to object storage in a separate account, with 30 days of point-in-time recovery, tested monthly by restoring into a scratch cluster.
What this design deliberately does not do. It does not use multi-leader writes. Orders and inventory have invariants (no double-selling) that conflict resolution cannot protect. It does not use replicas for write scaling. If writes grow tenfold, the next step is to shard orders by customer, not to add replicas. It keeps synchronous replication in-region. A synchronous cross-region replica would add about 90 ms to every commit, which the business chose not to pay for in return for zero regional RPO.
Monitoring the plan. Dashboards should show these signals:
- Replay lag in seconds and bytes for every replica.
- Synchronous standby state: is a sync standby currently attached?
- Replication slot retention and WAL archive success.
- etcd health and leader changes.
- The time since the last successful restore test.
Alerts fire when no synchronous standby is attached, because RPO zero is silently gone. They also fire when cross-region lag exceeds the stated disaster-recovery RPO, and when WAL archiving fails, because point-in-time recovery stops at the last archived segment. Each alert maps to a promise made in the requirements, which keeps the monitoring focused on what the business actually needs.
When to Use It#
- Always, for production databases: at least one standby in another zone for availability.
- Read-heavy workloads that exceed one node's read capacity.
- Users in several regions who need low-latency reads.
- Separating analytics and reporting from transactional traffic (a dedicated replica).
When NOT to Use It#
- Do not use replicas to scale writes; every replica applies every write. Shard instead.
- Do not send read-after-write traffic to asynchronous replicas without a read-your-writes plan.
- Avoid multi-leader unless you need multi-region writes or offline clients; conflicts are hard.
- Replication is not a backup: a bad
DELETEreplicates to every copy within milliseconds.
How to Implement It#
- Start with leader-follower: one primary, one synchronous or semi-sync standby in another zone.
- Add async read replicas as read load grows; route via the app or a proxy.
- Implement read-your-writes for user-facing writes (leader reads for a window, or LSN tracking).
- Automate failover with majority-based leader election and fencing; test it regularly.
- Monitor lag and pull lagging replicas out of rotation.
- Keep backups and point-in-time recovery separately from replication.
# Illustrative Patroni (PostgreSQL HA) settings
bootstrap:
dcs:
ttl: 30 # leader lease in etcd, seconds
loop_wait: 10
maximum_lag_on_failover: 1048576 # bytes; don't promote a far-behind replica
synchronous_mode: true # keep one synchronous standby
postgresql:
parameters:
synchronous_commit: "on"
hot_standby: "on"| Technology | Fits when |
|---|---|
| PostgreSQL streaming replication + Patroni | Self-managed Postgres HA with automatic failover |
| MySQL replication + Orchestrator, Group Replication | Self-managed MySQL HA |
| Amazon RDS Multi-AZ, Aurora, Cloud SQL HA | Managed failover and read replicas |
| Cassandra, ScyllaDB | Leaderless, multi-datacentre replication |
Trade-offs#
| Choice | Gain | Cost | Pick when |
|---|---|---|---|
| Synchronous | No data loss on failover | Higher commit latency; blocked by slow follower | Payments, orders (in-region) |
| Asynchronous | Fast commits, distant replicas | Lag; recent writes lost on failover | Read replicas, cross-region copies |
| Semi-sync | No loss on single failure, tolerable latency | More config; still waits for one ack | Primary HA in a region |
| Multi-leader | Local writes in every region | Conflicts | Multi-region writes, offline apps |
| Leaderless | No failover, high write availability | Quorum tuning, conflict handling | Always-on, write-heavy stores |
| Consensus (Raft/Paxos) replication | RPO zero, safe automatic failover | Majority round trip per write, more replicas | Metadata, money, inventory |
| Quorum storage (Aurora-style) | Survives a zone loss, fast replicas on shared storage | Vendor-specific, storage-layer cost | Managed relational at scale |
| Cascading replicas | Less leader bandwidth for many replicas | Extra lag per hop, fragile middle tier | Large read fleets, cross-region fan-out |
| Home-region writes | No conflicts, local reads everywhere | Remote write latency for travelling users | Most multi-region products |
Common Pitfalls#
- Reading your own write from a lagging replica and showing users stale data.
- Failover that promotes a far-behind replica, losing many seconds of writes.
- No fencing, allowing split-brain when a partitioned old leader keeps accepting writes.
- Using last-write-wins without realising it silently discards concurrent updates.
- Treating replicas as backups.
- Abandoned replication slots retaining WAL until the primary's disk fills.
- Trusting
Seconds_Behind_Sourceinstead of a heartbeat table. - Random per-request replica choice breaking monotonic reads.
- Strict synchronous replication with one standby, so a standby failure stops all writes.
- Never rehearsing failover, so the first real one runs untested code.
Real-World Examples#
GitHub's October 2018 incident began with a 43-second network partition; automated MySQL failover promoted primaries in another data centre, leaving writes in both sites that had to be reconciled, and the service was degraded for about 24 hours.
Amazon's Dynamo paper describes leaderless replication with version vectors, returning conflicting shopping-cart versions to the application to merge.
Amazon Aurora's SIGMOD 2017 paper describes six-way replicated storage across three availability zones, with 4-of-6 write and 3-of-6 read quorums, so the database survives a zone failure without losing data.
Etcd, the Raft-based store behind Kubernetes, keeps cluster state replicated across an odd number of members so that a majority can always elect a leader safely.
In the Interview#
Handling replication questions in an interview#
Make the default explicit, then justify deviations. A strong opening: "Single-leader Postgres. One synchronous standby in another zone for RPO zero. Async replicas for read scaling. Automatic failover through Patroni and etcd, with an RTO around 30 seconds." Then say what the product needs beyond that. Multi-region reads need async cross-region replicas. Multi-region writes need a home region per user, or a consensus-based database.
Quantify lag and loss. Say what happens to the last second of writes when the primary dies, and to a user who refreshes right after posting. Interviewers listen for whether you know that asynchronous failover can lose acknowledged writes, and that replicas serve stale reads.
Match the topology to the requirement.
- Banking, orders and inventory: single leader, synchronous within a region, or consensus. No multi-leader for balances.
- Social feeds, likes and view counts: async replicas and eventually consistent counters, possibly CRDT-style.
- Always-writable stores across data centres, such as carts or device telemetry: leaderless with quorums, accepting conflict resolution.
- Offline-first mobile or collaborative apps: multi-leader per device, with CRDTs or explicit merges.
Expect these follow-ups:
- "The primary fails mid-transaction. What does the client see?" A connection error. Retry idempotently against the new primary, found via the proxy or driver. Committed transactions are on the sync standby. Uncommitted ones are rolled back.
- "How do you stop two primaries?" A lease in a majority quorum, self-demotion on lease loss, and fencing by term number or STONITH.
- "Why not multi-leader across regions?" Conflicts, lost updates under LWW, and harder invariants. Prefer a home region per record.
- "Replica lag hits 30 seconds during a batch job." Drain lagging replicas, throttle or chunk the batch, and route critical reads to the primary.
Red flags: claiming replicas scale writes, failover with no fencing, LWW on user-edited data, and treating replication as a backup.
Deep Dive: How changes are shippedShow
Statement-based replication sends the SQL statements; it breaks with non-deterministic functions (now(), random()). Physical (WAL shipping) sends low-level page changes; it is exact and fast but ties followers to the same database version. Logical (row-based) replication sends row-level changes (insert row X, update columns Y); it works across versions and feeds change data capture, which is why MySQL's row-based binlog and Postgres logical decoding power tools such as Debezium. See Change Data Capture.
Adding a follower without downtime: take a consistent snapshot tied to a log position, restore it on the new node, then stream changes from that position.
Chained replication (followers of followers) reduces load on the leader for many replicas, at the cost of more lag at the end of the chain.
Deep Dive: Replicating a log with Raft, and why it fixes classic failoverShow
The problem Raft solves. Classic primary-standby failover bolts leader election (a timeout plus a promotion script) onto a replication stream that was never designed with it. That is where split-brain and lost writes come from. Raft, from "In Search of an Understandable Consensus Algorithm" (Diego Ongaro and John Ousterhout, USENIX ATC 2014), designs the two together. Its safety does not depend on timing. Timeouts affect only how fast it recovers, never whether it stays correct.
Terms and elections. Time is divided into numbered terms. A follower that hears no heartbeat within a randomised election timeout, for example 150-300 ms, becomes a candidate. It increments the term and asks the others for votes. Each node votes at most once per term, and only for a candidate whose log is at least as up to date as its own, meaning a higher last term, or the same last term and an equal or longer log. A candidate with votes from a majority becomes leader. Two leaders in the same term are impossible, because two majorities always overlap. An old leader from a lower term is rejected by any node that has seen the higher term. Term numbers are therefore built-in fencing tokens.
Log replication. The leader appends each client command to its log and sends AppendEntries to followers, including the index and term of the preceding entry. A follower accepts only if its log matches at that point. If not, the leader walks back until the logs agree, then overwrites the follower's divergent suffix. An entry is committed once it is stored on a majority, and the leader then applies it and answers the client. The vote rule guarantees that any future leader already holds every committed entry, so a committed write is never lost in a failover. This is exactly what asynchronous primary-standby cannot promise.
Costs and tuning.
- Every write needs a majority round trip. Within a region that is about 1 ms. With replicas spread across regions it is 50-150 ms per commit, unless entries are batched and pipelined.
- Throughput is bounded by one leader per group, so systems such as CockroachDB, TiKV and YugabyteDB run thousands of Raft groups, one per data range, each with its own leader spread across nodes.
- Reads served by the leader can be stale if it was deposed without knowing it. Linearizable reads need either a quorum check, using Raft's
ReadIndex, or a time-based leader lease that relies on bounded clock drift. - Membership changes, such as adding or removing replicas, use joint consensus or single-server changes so that two disjoint majorities can never exist during the transition.
Raft versus Paxos. Multi-Paxos, from Leslie Lamport's "The Part-Time Parliament" (1998) and "Paxos Made Simple" (2001), provides the same guarantees. Raft is easier to implement because it insists on a strong leader and a log with no gaps. Production systems use both: Spanner and Chubby use Paxos, while etcd, Consul and CockroachDB use Raft. ZooKeeper uses Zab, a closely related atomic broadcast protocol.
When to use it. Use consensus-replicated storage when you need RPO zero and automatic failover without split-brain, such as configuration, metadata, locks, and financial or inventory data. Prefer asynchronous replication when cross-region latency on every write is unacceptable and a small loss window is tolerable.
Key Takeaways#
- Replication provides availability, read scaling and lower latency, but not write scaling or backups.
- Leader-follower is the default; multi-leader and leaderless allow more writers at the cost of conflicts.
- Synchronous replication avoids data loss but adds latency; async is fast but may lose recent writes; semi-sync balances both.
- Asynchronous lag breaks read-your-writes; route recent writers to the leader or track log positions.
- Failover needs majority-based election and fencing to avoid split-brain; resolve or avoid conflicts deliberately.
- Replication logs differ (WAL, binlog, oplog) but the questions are the same: lag, loss window, failover and conflicts.
- Choose durability per commit: from local flush to synchronous apply; quorum commit avoids one slow standby blocking writes.
- Session guarantees (read-your-writes, monotonic reads) are fixed by tracking log positions, not by making everything synchronous.
- Safe failover = majority-held lease + self-demotion + fencing by term; rehearse it.
- LWW loses concurrent updates; version vectors detect them; CRDTs merge them; home regions avoid them.