Skip to main content

Replication

Learning objectives
  • Compare single-leader, multi-leader and leaderless replication and pick one for a given workload
  • Explain synchronous, semi-synchronous and asynchronous commit and quantify the data-loss window of each
  • Reason about quorums (R + W > N), sloppy quorums, hinted handoff, read repair and anti-entropy
  • Design a failover procedure that avoids split brain, and handle replication-lag anomalies in a payments product

TL;DR​

  • Replication buys availability, read scale and locality. It costs you a choice about when a write counts as done and who may accept writes.
  • Single-leader: one node orders all writes; followers copy the log. Simple and the default for ledgers. Synchronous followers mean no data loss on failover but higher latency; async means a loss window equal to the lag.
  • Multi-leader: several nodes accept writes and exchange them. Good for multi-region writes and offline clients; you inherit write conflicts and must resolve them (LWW, merge, CRDT, or avoid by routing each key to one leader).
  • Leaderless (Dynamo-style): clients write to W of N replicas and read from R. R + W > N makes read and write sets overlap. Sloppy quorums and hinted handoff trade that overlap for availability; read repair and Merkle-tree anti-entropy restore convergence.
  • Failover is where replication bugs become incidents: detection by timeout, choosing the most up-to-date follower, and fencing the old leader so two leaders never accept writes.
  • Replication lag causes user-visible anomalies (stale balance, vanishing refunds); handle them with session guarantees, not hope.

Why it matters​

A payment service that loses the last two seconds of committed writes during a failover has captured card payments that the ledger no longer knows about. Customers were charged, orders were never confirmed, and someone will spend a week reconciling against the PSP's settlement file. That is the asynchronous-replication data-loss window, made concrete.

The opposite failure is just as real. In 2012, GitHub promoted an out-of-date MySQL follower; its auto-increment counter lagged the old leader, so it reissued primary keys that had already been used — and those keys were also referenced in a Redis cache, which exposed some private data to the wrong users. Replication design decisions show up as money, data-protection and trust problems, which is why bank and e-commerce interviewers dig into them.

Core concepts​

Single-leader replication​

All writes go to the leader, which appends them to its log (WAL, binlog) and ships that log to followers. Followers apply the log in order, so every replica goes through the same sequence of states. Reads can be served by the leader (fresh) or followers (possibly stale).

The key knob is when the leader acknowledges a commit:

  • Asynchronous: acknowledge after the leader's local fsync. Lowest latency; if the leader dies, everything not yet shipped is lost. The loss window equals replication lag — usually milliseconds, but seconds or minutes under load or network trouble.
  • Synchronous: acknowledge only after at least one follower has durably received the record. A failover to that follower loses nothing. Each commit pays a round trip, and if the sync follower is down, commits stall unless you fall back to another one.
  • Semi-synchronous: MySQL's term for "wait for at least one replica to receive the event into its relay log", not to apply it. In MySQL the wait point matters: AFTER_SYNC (the "lossless" mode, default in 5.7+) waits before the commit is visible to other sessions, while AFTER_COMMIT can let other clients see data that is then lost on failover. (Variable names changed from master to source in 8.0.26+.)
  • Quorum commit: PostgreSQL's synchronous_standby_names = 'ANY 2 (a, b, c)' waits for any two of three standbys, which tolerates one slow standby without stalling.

PostgreSQL's synchronous_commit levels make the trade-off precise: off (don't even wait for local fsync), local, remote_write (standby received it into OS memory), on (standby flushed it to disk), remote_apply (standby applied it, so reads there see it).

Replication log formats: statement-based (fragile with NOW(), random values, triggers), physical/WAL shipping (exact, but ties replicas to the same version), and logical/row-based (decoupled, version-tolerant, and the basis for CDC).

Multi-leader replication​

Each leader accepts writes and replicates them asynchronously to the others. Typical uses: one leader per region so writes stay local; mobile or POS clients that keep working offline and sync later; collaborative editing.

The defining problem is write conflicts: two leaders accept different updates to the same row concurrently. Options:

  • Avoid conflicts by routing: each key has a home leader (each account belongs to one region). This is by far the most common approach in banking — it is effectively single-leader per key.
  • Last-writer-wins (LWW): pick the write with the highest timestamp. Simple, and silently discards the other write. Unacceptable for balances; fine for "last login time".
  • Merge: application-specific logic (union of cart items) or CRDTs — data types with a mathematically commutative merge (counters, sets, registers).
  • Record and surface: keep both versions and ask the application or user to resolve.

Topology also matters: in a circular or star topology a single node failure can interrupt replication; all-to-all is more robust but can deliver causally related writes out of order.

Leaderless replication​

Popularized by Amazon's Dynamo paper and used by Cassandra, Riak and ScyllaDB. There is no leader; the client (or a coordinator node acting for it) sends each write to all N replicas of a key and waits for W acknowledgements, and reads from R replicas, taking the newest version.

With N = 3, W = 2, R = 2, the write set {A, B} and read set {B, C} must share at least one node (here B), so the reader sees v7.

Quorum math:

  • R + W > N guarantees read and write sets overlap, so a read sees at least one copy of the latest acknowledged write.
  • Common choices for N = 3: W = 2, R = 2 (balanced); W = 3, R = 1 (fast reads, writes fail if any replica is down); W = 1, R = 1 (fastest, no overlap — eventual).
  • The quorum tolerates N − W unavailable nodes for writes and N − R for reads.

Why quorums are still not linearizable:

  • Concurrent writes resolved by LWW can lose data; clocks decide the winner.
  • A write that succeeds on fewer than W nodes is reported as failed but is not rolled back — later reads may or may not see it.
  • A read concurrent with a write may see the new value on one replica and the old on another; without read repair before returning, two sequential readers can see new-then-old.
  • Sloppy quorums (below) break the overlap entirely.

Sloppy quorum and hinted handoff. If some of a key's home replicas are unreachable, the coordinator writes to other healthy nodes instead, with a hint naming the intended owner. When the owner returns, the stand-in hands the data off. This keeps writes available during partitions but means W acknowledgements may not intersect the R nodes a reader contacts — so it is an availability feature, not a consistency one.

Read repair. When a read sees divergent versions, the coordinator writes the newest version back to stale replicas. It only fixes keys that are read.

Anti-entropy with Merkle trees. A background process compares replicas to fix keys nobody reads. Each node builds a hash tree over its key ranges: leaves hash ranges of keys, parents hash their children. Two nodes compare root hashes; if they match, the ranges are identical. If not, they descend only into differing subtrees, so they exchange O(log n) hashes to find the few divergent ranges instead of streaming all data. Cassandra's nodetool repair does this; you must run it regularly (more often than the tombstone grace period, gc_grace_seconds) or deleted data can resurrect.

Failover and split brain​

Single-leader failover has three steps, each with its own failure modes:

  1. Detect that the leader is dead — only possible via timeouts. Too short and you fail over during a GC pause or a brief network blip; too long and you are down for the duration.
  2. Choose a new leader — ideally the follower with the most recent log (fewest lost writes). With consensus-based systems this is an election; with orchestration tools (Patroni, Orchestrator, cloud-managed failover) it is a decision backed by a consensus store such as etcd or ZooKeeper.
  3. Reconfigure clients and other followers to use the new leader, and make sure the old one cannot accept writes when it comes back.

Split brain is two nodes both believing they are leader and both accepting writes:

Defenses:

  • Leases: the leader may only serve writes while holding a time-bound lease from a consensus store; it must stop when the lease expires, and the new leader waits out the old lease before starting (see Distributed Locks & Leases).
  • Fencing: physically or logically prevent the old leader from writing — STONITH (power off), revoke its storage access, or require a monotonically increasing epoch on every write so storage rejects stale leaders.
  • Majority-based election: only a node that can reach a quorum of voters can become or remain leader, so the minority side demotes itself.

A real example of how hard this is: in October 2018, a 43-second network partition between GitHub's US East Coast data center and its hub triggered a cross-country MySQL failover. Writes then landed in both locations, and resolving the divergent data took around 24 hours of degraded service. The partition was short; the recovery was not.

Replication lag problems​

Async followers are "eventually consistent". Under normal load lag is milliseconds; under bulk jobs, vacuum, long-running queries on replicas, or network trouble, it can be seconds to minutes. The resulting anomalies and their fixes:

AnomalyExampleFix
Read-your-writesTransfer done, balance unchanged on refreshRead own data from leader for a window, or version tokens
Monotonic readsRefund visible, then goneSticky replica per user, or max-seen version
Consistent prefixDebit visible before the funding creditKeep causally related writes in one partition / one log
Stale decisionStock check on replica oversellsDecide on the leader, atomically

See Consistency Models for the techniques in detail.

Replication vs erasure coding​

Everything above stores full copies. For large, immutable blobs (object stores, backups, data lakes) the usual alternative is erasure coding (EC): cut the data into k chunks, compute m parity chunks, and place all k+m in different failure domains. Any k surviving chunks rebuild the original. Ch 9 · S3-like Object Storage walks through a full design.

3× replicationEC 8+4
Raw storage per logical byte3×1.5× (same for 4+2)
Losses survivedAny 2 copiesAny 4 chunks (any 2 for 4+2)
Normal readOne replicak nodes; tail latency follows the slowest
Degraded readRead another replicaFetch k chunks, then decode
Rebuilding one lost pieceCopy it from a replicaRead k chunks over the network, ≈k times the size of the lost chunk
CPUNegligibleEncode on every write; decode on degraded reads and repairs
Small objectsFineA 20 KB object becomes 12 pieces of ≈2.5 KB: more IOPS and metadata, so pack objects into large segments and encode those

Durability, roughly. Under an independent-failure model, data with n copies is lost only if all n disks die. With an annual failure rate (AFR) of ≈1%, the crude figure for 3 copies is ≈10⁻⁶ a year. Two corrections matter more than the copy count:

  • Repair time. Data dies only if the remaining copies fail while the first loss is still being rebuilt. For 3 copies that risk grows with roughly the square of the repair window, so cutting rebuild time from days to hours adds orders of magnitude. Fast, parallel re-replication is a durability feature, and EC earns its extra nines the same way: it tolerates more losses inside that window.
  • Correlated failures. Shared power, a rack switch, a firmware batch or a bad deploy kill many disks at once. Spreading copies across racks and AZs does not change the independent arithmetic. It stops one site event from taking every copy, which is what keeps the independent model honest.

Where each fits. Replicate hot, small or mutable data where latency matters: OLTP databases, the ledger, carts, and freshly written objects. Erasure-code large, cold, write-once data: statement PDFs older than a few months, KYC images kept for years after an account closes, audit-log archives and backups. A common pattern writes new objects replicated, then re-encodes sealed segments in the background once they cool. At ≈1 PB of retained statements and KYC scans, that is ≈3 PB raw under 3× versus ≈1.5 PB under 8+4. The core ledger stays on synchronous replication, because each of its writes needs low latency, not cheap bytes.

Trade-offs​

OptionStrengthsWeaknessesChoose when
Single-leader, asyncSimple, fast commits, cheap read scaleData-loss window on failover; lag anomaliesMost OLTP where a small loss window is acceptable or covered by reconciliation
Single-leader, sync / quorum commitNo acknowledged-write loss on failoverCommit latency includes a replica round trip; stalls if sync replicas are unavailableLedgers, payments, anything where an acknowledged write must survive
Multi-leaderLocal writes in each region; offline clientsConflicts; complex topology; LWW loses dataPer-region writes with keys homed to one region; collaborative or offline apps
Leaderless quorumNo failover step; tolerates node loss gracefully; tunable per requestNot linearizable; repair operations; conflict handling; tombstonesHigh-volume, availability-first data: carts, sessions, activity feeds, IoT
Consensus-replicated (Raft/Paxos)Linearizable, automatic safe failoverWrite latency of a majority round trip; leader bottleneckMetadata, ledgers on distributed SQL (CockroachDB, Spanner, TiDB)

In practice​

PostgreSQL configuration for a ledger primary (illustrative):

# postgresql.conf on the primary
synchronous_commit = on
synchronous_standby_names = 'ANY 1 (standby_az_b, standby_az_c)'
wal_level = replica
max_wal_senders = 10

Commits wait until one of two standbys in other availability zones has flushed the WAL. One standby can be down without stalling commits; both down stalls writes — a deliberate CP choice.

Monitor lag on the primary:

SELECT application_name, state, sync_state,
write_lag, flush_lag, replay_lag
FROM pg_stat_replication;

Alert on replay_lag for replicas that serve reads, and on flush_lag for sync standbys (it directly adds to commit latency).

Cassandra for an availability-first workload (e.g., cart or session data):

  • Replication factor 3 per data center with NetworkTopologyStrategy.
  • LOCAL_QUORUM for reads and writes keeps latency within the local DC while still overlapping quorums.
  • Run repairs on a schedule shorter than gc_grace_seconds (default 10 days) so tombstones propagate before they are purged.

Rough numbers (approximate): same-AZ replica round trip well under 1 ms; cross-AZ ≈ 1–2 ms; cross-region tens to hundreds of ms. A synchronous cross-region commit therefore adds at least one inter-region RTT to every write — which is why most banks replicate synchronously within a region and asynchronously to the DR region, then define an RPO for the DR case (see High Availability & Disaster Recovery).

Failover tooling: Patroni (PostgreSQL, uses etcd/Consul/ZooKeeper for leader leases), Orchestrator (MySQL topology management), and managed services (RDS Multi-AZ, Cloud SQL HA, Aurora) all implement the detect–choose–reconfigure–fence loop. Read their documentation for what they do when the old primary is unreachable but alive.

Common pitfalls​

  • Promoting a lagging follower without reconciling. Lost commits plus reused sequence values. Symptom: duplicate primary keys, payments in the PSP report but missing from the ledger.
  • No fencing. The old leader resumes after a pause and accepts writes. Symptom: two divergent histories; manual data surgery.
  • Failover timeouts tuned for a quiet day. A 5-second timeout fires during a GC pause or a deploy. Symptom: flapping failovers that cause more downtime than they prevent.
  • Single synchronous standby. It goes down for patching and the primary stops committing. Use quorum commit (ANY 1 (a, b)) or a documented fallback.
  • Reading decision data from replicas. Balance or stock checks on a follower. Symptom: overdrafts and oversells that correlate with lag spikes.
  • LWW for anything that accumulates. Counters, balances, inventory under multi-leader LWW lose increments. Use single-writer per key, CRDT counters, or a ledger of immutable entries.
  • Skipping Cassandra repair. Symptom: deleted rows come back weeks later ("zombie" data).

Interview angle​

  • Expect: "How do you replicate the payment database across AZs and regions?" Strong answer: single leader per shard, synchronous quorum commit across AZs (RPO = 0 within the region), asynchronous to a DR region with a stated RPO; automated failover with fencing; read replicas only for staleness-tolerant reads; session guarantees for user-facing reads.
  • Follow-ups: "What's your RPO and RTO?" "What if the sync standby is down?" "How do you prevent split brain?" "Why not active-active multi-leader?" (conflicts on balances; route each account to one home region instead.)
  • Leaderless questions: be able to compute overlap for given N, R, W; explain why quorums still aren't linearizable; explain hinted handoff vs read repair vs anti-entropy.
  • Red flags: "async replication, so no data loss"; "we'll use multi-master for the ledger" without a conflict story; failover with no fencing.

Self-check​

1. What exactly is lost when an asynchronously replicated leader crashes, and how do you bound it?

Every write the leader acknowledged but had not yet shipped to the follower that gets promoted — the replication lag at that moment. Bound it by using synchronous or quorum commit to at least one standby, by alerting on lag, and by refusing to promote a follower whose lag exceeds a threshold (preferring a slower, safer failover).

2. With N = 5, which (R, W) pairs guarantee overlap, and what does each tolerate?

Any pair with R + W > 5: e.g., W = 3, R = 3 tolerates two nodes down for both reads and writes; W = 5, R = 1 gives fast reads but writes fail if any node is down; W = 1, R = 5 the reverse. The write path tolerates N − W failures and the read path N − R.

3. Explain hinted handoff, read repair and anti-entropy. Which one fixes data that is never read?

Hinted handoff stores writes for an unreachable replica on a stand-in node and delivers them when the replica returns. Read repair fixes stale replicas discovered during a read. Anti-entropy is a background comparison of replicas — using Merkle trees to find differing key ranges efficiently — and is the only one that fixes data nobody reads.

4. Why can a quorum system with R + W > N still return stale data?

Sloppy quorums can place writes on nodes outside the key's home set; failed writes that reached fewer than W nodes are not rolled back; concurrent writes resolved by LWW depend on clocks; and reads concurrent with writes can see different versions on different replicas. Overlap only guarantees seeing the latest acknowledged write in the simple, non-concurrent case.

5. Scenario: a bank wants active-active writes in two regions for its core ledger. What do you propose?

Avoid true multi-leader on balances. Give each account a home region that is the single writer for it; route requests there (with a global routing table). Each region is active for its own accounts and a replica for the other's. Cross-region transfers become a two-step, idempotent flow between ledgers (see sagas). On region loss, fail over the affected accounts' home with fencing and an accepted RPO.

6. What is split brain, and name three ways to prevent it.

Two nodes both act as leader and accept writes, producing divergent histories. Prevent it with majority-based election (a leader must reach a quorum), time-bound leader leases that the old leader respects and the new leader waits out, and fencing — STONITH, revoking storage access, or epoch numbers that storage checks on every write.

7. Why does faster repair raise durability so much, and what does spreading copies across AZs actually buy you?

Data is lost only if the surviving copies also fail before the first loss is rebuilt. With 3 copies that chance scales with roughly the square of the repair window, so going from days to hours gains orders of magnitude. AZ spreading does not change the independent-failure maths. It protects against correlated events (power, cooling, network, a bad deploy) that would otherwise destroy every copy at once.

🧠 Flashcards0/10 learned · 0 retries

Exercise​

Design the replication topology for a payment service's PostgreSQL cluster serving one country, with a DR region:

  1. Draw the topology (AZs, regions, sync vs async links) as a diagram.
  2. State RPO and RTO for: loss of one node, loss of one AZ, loss of the primary region.
  3. Write the failover runbook: detection signal and timeout, how the new leader is chosen, how the old one is fenced, how applications discover the new leader, and how you reconcile any lost writes with the PSP settlement file.
  4. List which queries may use read replicas and which must hit the primary.

Optional lab: run Patroni with etcd in Docker, kill the primary, and measure the time to a new primary and the number of writes lost by a client that writes once every 10 ms with synchronous_commit = local vs on.

Done when: every number in step 2 follows from a concrete mechanism in step 1, and the runbook explains why split brain cannot happen.

Further reading​

  • Martin Kleppmann, Designing Data-Intensive Applications, ch. 5 "Replication".
  • DeCandia et al., "Dynamo: Amazon's Highly Available Key-value Store" — SOSP 2007.
  • PostgreSQL documentation: "High Availability, Load Balancing, and Replication" and the synchronous_commit setting.
  • MySQL Reference Manual: "Semisynchronous Replication".
  • Apache Cassandra documentation: consistency levels, hinted handoff and repair.
  • GitHub Engineering blog, "October 21 post-incident analysis" (2018).
  • Alex Petrov, Database Internals, part II (replication, anti-entropy).
Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).