Replication

Copies of data for durability, read scale, and failover. The models, the lag they introduce, and what breaks when the leader dies.

Leader-follower Sync vs async Failover Multi-leader Quorum WAL
đŸĒž

Why Replicate

Replication keeps multiple copies of the same data. It buys four things: durability (a dead node doesn't lose data), read scaling (spread reads across copies), geographic locality (a copy near each region), and failover (promote a copy when the primary dies).

This is a different problem from sharding. Sharding splits data so each node holds a part; replication copies data so each node holds the same part. They're orthogonal, and most real systems do both — shard for capacity, replicate each shard for durability and reads (Sharding).

👑

Leader-Follower

The most common model: one leader takes all writes, then streams changes to followers that serve reads. Writes have a single ordering point (no write conflicts), and reads scale by adding followers. The tension is in when a write is considered done.

            writes                    reads
              │                    ┌────┴────â”Ŧ─────────┐
              â–ŧ                    â–ŧ         â–ŧ          â–ŧ
         ┌─────────┐  replicate  ┌──────┐ ┌──────┐  ┌──────┐
         │ LEADER  │ ──────────â–ļ │ foll │ │ foll │  │ foll │
         └─────────┘             └──────┘ └──────┘  └──────┘

  SYNC replication:  leader waits for follower ack before confirming write
                     → no data loss on failover, but slower writes
  ASYNC replication: leader confirms immediately, replicates in background
                     → fast writes, but a lagging follower can lose recent data

Replication lag is the gap between a write hitting the leader and reaching a follower. Read from a lagging follower right after writing and your own change is missing — a read-your-writes violation. This is where session guarantees come in: pin a user to the leader for their own reads, or track the version they've seen (Consistency Models).

🔀

Failover

When the leader dies, the system detects it, picks a follower, and promotes it. Sounds simple; three things make it hard.

HazardWhat goes wrong
DetectionCan't tell "dead" from "slow" — promote too eagerly and you cause outages, too slowly and you extend one
Split brainThe old leader comes back thinking it's still leader — now two leaders take conflicting writes
Lost writesWith async replication, writes acked but not yet replicated vanish when a behind follower is promoted
âš ī¸
Async replication plus failover means you can lose acknowledged writes: the leader told the client "committed," died before replicating, and the new leader never saw it. That's a real durability hole, and the fix — synchronous replication to at least one follower — costs write latency. Choosing where on that line to sit is the tradeoff. Leader election itself needs consensus to avoid split brain (Consensus).
đŸ‘Ĩ

Multi-Leader

With multiple leaders — typically one per region — each takes writes locally and replicates to the others. Writes are fast and local everywhere, and no single leader is a bottleneck or a distant round trip. The price is write conflicts: two regions can edit the same record at the same time, and both are "correct" locally.

Resolving conflicts is the whole problem. Last-write-wins is simplest and silently drops one of the two writes — sometimes fine, sometimes data loss you'll regret. CRDTs (conflict-free replicated data types) are data structures designed so concurrent updates merge deterministically without loss — the right tool for counters, sets, and collaborative text, at the cost of constrained operations. Multi-leader is the write side of active-active regions (Multi-Region).

đŸ—ŗ

Leaderless / Quorum

Leaderless stores (Dynamo, Cassandra) drop the leader entirely. A client writes to several replicas and reads from several, and overlap guarantees freshness. With N replicas, requiring W to ack a write and R to answer a read, the rule W + R > N forces every read set to overlap every write set by at least one up-to-date replica.

  N = 3 replicas.  W = 2, R = 2.   W + R = 4 > 3  ✓

  write ─â–ļ [R1] [R2] [R3]     ack from 2 (W=2) → write succeeds
              ✓    ✓    ✗
  read  ◀─ [R1] [R2] [R3]     ask 2 (R=2); at least one overlaps the write
              ✓         ✓      → the reader sees the latest value

  Tuning:  W=N (all)  → strong writes, slow, fragile to one node down
           R=1        → fast reads, weaker guarantee
           W+R ≤ N    → fast but may read stale data

Two repair mechanisms keep replicas honest. Read repair: when a read notices a stale replica, it writes the fresh value back. Anti-entropy: a background process compares replicas and reconciles differences. And a sloppy quorum with hinted handoff keeps writes flowing during a partition — a temporary node accepts the write and hands it off when the real owner returns, trading strictness for availability.

đŸĒĩ

Write-Ahead Logs

Underneath every model above sits one idea: log first, apply second. Before a database changes a page, it appends the change to a write-ahead log on durable storage. If the process crashes mid-operation, it replays the log on restart and recovers. The log is the source of truth; the data files are a materialized view of it.

💡
The WAL is also the replication stream — followers apply the leader's log to stay in sync — and the basis of change data capture: tail the WAL to turn every database change into an event feed for search indexes, caches, and downstream services (Distributed Transactions). One mechanism, three jobs: crash recovery, replication, and CDC. Naming that connection signals real depth.
📋

Quick Reference

ModelWrite pathConflict riskBest fit
Leader-followerOne leaderNone (single writer)Read scaling, most systems
Multi-leaderLeader per regionHigh — needs resolutionMulti-region local writes
Leaderless / quorumWrite to W of NHandled by versioningHigh availability, tunable
Quorum (N=3)Gives
W=2, R=2Strong-ish reads, tolerates one node down — the common default
W=3, R=1Fast reads, slow/fragile writes
W=1, R=1Fast both ways, may read stale (W+R ≤ N)
â„šī¸
The one-liners to keep ready. Replication ≠ sharding — copies vs splits, most systems do both. Leader-follower for read scale; sync vs async is the durability-vs-latency knob, and async can lose acked writes on failover. Multi-leader for local writes at the cost of conflict resolution. Quorum: W+R>N guarantees overlap. Underneath everything, the WAL logs first and applies second — the same log that does crash recovery, replication, and CDC.