DS·71
Replication
Keeping copies of data on several nodes, in depth: single-leader replication (synchronous, asynchronous, semi-synchronous, chain replication), what gets shipped (statements, WAL, logical rows), replication lag and its anomalies, failover and split brain with epochs and fencing; multi-leader replication, its topologies and conflict handling; leaderless Dynamo-style replication with quorums, sloppy quorums, hinted handoff, read repair and Merkle-tree anti-entropy; version vectors; and CRDTs, with implementations in Go, Rust, Python and Elixir. Builds on Vol. 4 ch. 61.
Start here: three ways to keep copies
Why replicate at all
Copies of data on several machines let you survive a machine or zone failure (availability and durability), serve reads from many places (read scaling), and put data near users (latency). The hard part is keeping the copies in step while they change. Every replicated system answers one question: who may accept a write?
| Approach | Who accepts writes | Examples | Main risk |
|---|---|---|---|
| Single leader | One leader; followers copy its log | PostgreSQL, MySQL, Redis, MongoDB, Kafka partitions | Replication lag; failover can lose async writes |
| Multi-leader | Several leaders (often one per region), replicating to each other | MySQL group/BDR setups, CouchDB, collaborative apps | Conflicting concurrent writes |
| Leaderless | Any replica; clients write to W and read from R of N | Dynamo, Cassandra, Riak, ScyllaDB | Stale reads unless R + W > N; conflicts |
Leaderless quorums: R + W > N
With N = 3 replicas, a write is sent to all three and succeeds when W have stored it; a read asks R replicas and takes the newest version. Replica A is down and C is slow (another zone):
st = Store([Replica("A"), Replica("B"), Replica("C", delay=(0.02, 0.04))], w, r)
await st.put("cart:42", f"{i} dosas")
if await st.get("cart:42") != f"{i} dosas": stale += 1
1) N=3, W=1, R=1, replica A down, 200 write-then-read: 18 stale reads
1) N=3, W=2, R=2, replica A down, 200 write-then-read: 0 stale reads
N=3, W=2 with two replicas down: write fails (only 1 of 2 replicas answered)
With W = 1 and R = 1, the read sometimes went to C before the write reached it. With W = 2 and R = 2, any two replicas you read overlap with any two that stored the write (2 + 2 > 3), so at least one copy in every read is current. Lose two replicas and W = 2 can't be met: the system chooses consistency, and that write fails. Lower W or R for availability and speed, raise them for freshness: it's the PACELC dial from chapter 70, per request.
Concurrent writes: who wins?
With more than one place accepting writes, two writes can happen "at the same time" in different places. The simplest rule, last-writer-wins (LWW, by timestamp), silently discards one of them:
2) 2 regions, 100 likes in each at the same moments, last-writer-wins: 100 likes stored
same clicks with a G-counter CRDT: 200 likes stored
Each region read the count, added one and wrote it back; LWW kept whichever write had the later timestamp, losing the other region's 100 likes. A CRDT (conflict-free replicated data type) is designed so concurrent updates merge without loss: a G-counter keeps one slot per region and merges by taking the maximum of each slot, so the total is always right. Other options are keeping both versions as siblings for the application to merge (Riak, CouchDB), or making all writes for a key go through one leader.
How deep to go in replication
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Explain why we replicate and the three replication approaches |
| L2 | Configure replicas, read routing, quorum levels and failover in real databases |
| L3 | Explain lag anomalies, quorum overlap, sloppy quorums, conflict resolution and CRDTs |
| L4 | Diagnose lag, stale reads, lost writes after failover and conflict anomalies |
| L5 | Choose replication topology and conflict strategy for multi-region systems |
| L6 | Operate replication fleets with lag SLOs, automated failover and repair at scale |
Why and how we replicate
Goals
Replication keeps copies of the same data on multiple nodes to get:
- Durability: data survives a disk or node loss.
- Availability: keep serving when a node fails.
- Read scaling: spread reads over replicas.
- Latency: serve users from a nearby copy.
The difficulty is changes: every write must reach every copy, while nodes and links fail. The three architectures differ in who accepts writes:
Single-leader replication
Mechanics
One replica, the leader (primary, master), accepts all writes. It records each change in its replication log and streams it to followers (replicas, secondaries, standbys), which apply changes in the same order. Reads can go to the leader (fresh) or followers (possibly stale). This is the model of PostgreSQL, MySQL, MongoDB replica sets, Redis, SQL Server Always On, and also of each partition in Kafka and each Raft group in CockroachDB/TiKV.
Single-leader is simple and gives a total order of writes for free (the leader's log order), which is why it's the default.
Synchronous, asynchronous, semi-synchronous
| Mode | Leader acknowledges a write after… | Trade-off |
|---|---|---|
| Synchronous | Followers confirm they've stored it | No loss on leader failure; but one slow or dead follower blocks all writes |
| Asynchronous | Its own local write | Fast and available; recent acknowledged writes are lost if the leader dies before shipping them |
| Semi-synchronous | At least one (or k) follower confirms | Bounded loss risk, tolerates slow followers. PostgreSQL synchronous_standby_names = 'ANY 1 (s1, s2)', MySQL semi-sync |
| Quorum (consensus) | A majority confirms | No loss of committed writes while a majority survives; leader election is safe (Raft, chapter 72) |
PostgreSQL's synchronous_commit levels show how fine-grained this gets: off (don't even wait for local flush), local, remote_write (standby received it in OS memory), on (standby flushed WAL), remote_apply (standby applied it, so reads there see it, giving read-your-writes on that standby).
What gets shipped
| Method | Description | Issues |
|---|---|---|
| Statement-based | Ship the SQL statements | Non-determinism: NOW(), RAND(), autoincrement order, triggers. MySQL's old default; now mostly replaced |
| Physical / WAL shipping | Ship the storage engine's write-ahead log (byte-level page changes) | Exact copy, but tied to storage format and version, so cross-version replication is limited. PostgreSQL streaming replication |
| Logical (row-based) | Ship row-level changes: insert row X, update key K set columns… | Version-independent, can filter tables, feeds CDC (Debezium, chapter 73). MySQL row-based binlog, PostgreSQL logical replication, MongoDB oplog |
| Trigger-based | Application-level triggers copy changes | Flexible, slow; legacy tools |
Chain replication
Chain replication (van Renesse and Schneider, 2004): replicas form a chain. Writes go to the head and propagate down; the tail acknowledges, and reads go to the tail. Since the tail has only fully replicated writes, reads are linearizable without consensus on each operation (a separate configuration master handles membership). Variants such as CRAQ allow reads from any node with a version check. Used in some object stores and in Microsoft's and Meta's storage systems.
Replication lag and its anomalies
With asynchronous followers, lag ranges from milliseconds to minutes (under load, long transactions or network trouble). Reading from followers causes the session-guarantee violations from chapter 69:
- Read-your-writes violation: write to the leader, read your stale profile from a follower.
- Monotonic reads violation: two reads hit followers with different lag, so time appears to go backwards.
- Consistent prefix violation (in partitioned systems): you see an answer before the question, because the two were in different partitions replicating at different speeds.
Fixes: read from the leader for recently written data, version tokens (wait for replica LSN ≥ client's), sticky replica routing, and monitoring lag (pg_stat_replication.replay_lag, MySQL Seconds_Behind_Source, Kafka consumer lag for CDC).
Failover
When the leader fails, a follower must be promoted:
- Detect the failure: usually via timeouts (chapter 77). Too short gives false failovers during load spikes; too long gives long outages.
- Choose a new leader: the most up-to-date follower (minimum data loss), via consensus or an external coordinator (Patroni with etcd/Consul for PostgreSQL, Orchestrator for MySQL, MongoDB's built-in Raft-like election, Redis Sentinel).
- Reconfigure: clients and other followers switch to the new leader (DNS, VIP, proxy reconfiguration, or service discovery).
Things that go wrong:
- Lost writes: with async replication, writes the old leader acknowledged but didn't ship are gone. If the old leader comes back, its unreplicated writes conflict with the new leader's history and are usually discarded (
pg_rewind). The GitHub 2012 incident: a promoted out-of-date MySQL follower reused autoincrement IDs that were also cached in Redis, leaking private data between users. - Split brain: two nodes both believe they're leader and accept writes (next section).
- Cascading failover: the new leader is overloaded by the full write load plus catch-up and fails too.
Split brain, epochs and fencing
Split brain happens when the old leader isn't actually dead (it was paused by GC, or partitioned) and keeps acting as leader after a new one is chosen. Both accept writes and data diverges.
Defences, from weakest to strongest:
- STONITH ("shoot the other node in the head"): power off or isolate the old leader via IPMI or the cloud API before promoting. Crude, effective, and itself can fail.
- Leases: a leader holds a time-limited lease and must stop acting as leader when the lease expires without renewal. Relies on bounded clock drift and the leader checking its lease before every action.
- Epochs / terms / generation numbers: each new leader gets a strictly higher number; followers and storage reject requests from older epochs. That's Raft's term, Kafka's leader epoch and controller epoch, and ZooKeeper's zxid epoch.
- Fencing tokens: the coordination service hands out a monotonically increasing token with each leadership or lock grant; the resource being protected (storage, database) rejects writes with a token lower than the highest it has seen. That's the only defence that works even if the old leader doesn't know it's been replaced (chapter 77).
Multi-leader replication
When and why
Several nodes accept writes, each replicating to the others asynchronously. Use cases:
- Multi-region active-active: each region has a leader, so writes are local (low latency) and a region outage doesn't stop writes elsewhere.
- Offline clients: every phone or laptop with a local database is effectively a leader (calendar apps, notes, local-first software).
- Collaborative editing: every editor's copy accepts changes (Google Docs-style, Figma, Automerge/Yjs).
Examples: MySQL group replication in multi-primary mode, PostgreSQL BDR / pgEdge / pgactive, Oracle GoldenGate, CouchDB/PouchDB, DynamoDB global tables, Cosmos DB multi-region writes, Redis Enterprise Active-Active (CRDT-based).
Topologies
- All-to-all: every leader sends to every other. Most robust, but messages can arrive out of causal order (an update arrives before the insert it modifies), so causality must be tracked (version vectors).
- Circular / star: forwards through intermediate nodes; each change carries the IDs of nodes it has passed to avoid loops. A single node failure can break the ring.
Conflicts
When two leaders concurrently modify the same data, there's a write conflict, detected only after both writes were accepted. Strategies:
| Strategy | How | Trade-off |
|---|---|---|
| Avoid | Route all writes for a given record to one "home" leader (per user, per tenant, per region) | Simplest and most common; breaks when the home leader fails or a user moves |
| Last-writer-wins | Highest timestamp (or replica ID tiebreak) wins | Silent data loss of concurrent writes; clock skew picks arbitrary winners |
| Merge values | Concatenate, union, sum | Only for some data types |
| Record conflicts for the app / user | Keep both versions (siblings), resolve on read or in a UI | Correct but complex; CouchDB's _conflicts |
| Conflict-free data types (CRDTs) | Data structures whose merge is mathematically guaranteed to converge | Must model data as CRDTs; some semantics are hard |
| Operational transformation | Transform concurrent edit operations against each other (Google Docs) | Central server usually needed; complex |
Subtle conflicts also arise from constraints: two leaders each accept a booking for the last room; uniqueness or capacity invariants can't be enforced without coordination (chapter 70's invariant confluence).
Leaderless replication
Dynamo-style quorums
Amazon's Dynamo paper (2007) introduced the design used by Cassandra, ScyllaDB, Riak and Voldemort: no leader; the client (or a coordinator node acting for it) sends each write to all N replicas of a key and each read to several.
- N: replication factor (e.g. 3).
- W: acks required for a successful write.
- R: replies required for a read.
If R + W > N, the set of nodes read overlaps the set written by at least one node, so a read sees at least one copy of the latest successful write, and the client picks the newest by version/timestamp. Common choice: N=3, W=2, R=2. W=N with R=1 gives fast reads and fragile writes; W=1, R=N the reverse.
Why quorums aren't linearizable by default
Even with R + W > N, anomalies remain:
- A write that fails (fewer than W acks) may still have reached some replicas, and isn't rolled back; later reads may or may not see it.
- Concurrent writes need a conflict rule; with LWW, one is silently lost.
- A read concurrent with a write may see the new value while a later read sees the old one (if the second read's quorum doesn't include the updated node), unless readers do synchronous read repair before returning.
- Sloppy quorums (below) break the overlap guarantee entirely.
Cassandra provides linearizable compare-and-set only through lightweight transactions (Paxos per partition, with Accord transactions planned for a future release).
Handling failures without a leader
- Sloppy quorum and hinted handoff: if some of a key's N "home" nodes are unreachable, a write is accepted by other nodes, which store a hint and hand the data back once the home node recovers. That boosts write availability but means R + W > N no longer guarantees overlap with the home nodes.
- Read repair: when a read sees stale replicas, the coordinator writes the newest value back to them (synchronously or in the background).
- Anti-entropy: background processes compare replicas and fix differences. Comparing whole datasets is expensive, so they compare Merkle trees (hash trees over key ranges): matching root hashes mean identical ranges, and mismatches are narrowed down by descending the tree, transferring only differing ranges. Cassandra's
nodetool repairis anti-entropy, and running it regularly (beforegc_grace_secondsexpires) prevents deleted data resurrecting via stale replicas that never saw the tombstone.
Version vectors
To tell whether two versions of a key are ordered (one supersedes the other) or concurrent (a real conflict), each replica keeps a version vector: a counter per replica. Version A dominates B if every counter in A ≥ the counter in B. If neither dominates, they're concurrent siblings. (Vector clocks, chapter 75, are the same idea applied to events.) Riak uses dotted version vectors to avoid sibling explosion.
# Python: comparing version vectors
def compare(a: dict[str, int], b: dict[str, int]) -> str:
keys = a.keys() | b.keys()
a_ge = all(a.get(k, 0) >= b.get(k, 0) for k in keys)
b_ge = all(b.get(k, 0) >= a.get(k, 0) for k in keys)
if a_ge and b_ge: return "equal"
if a_ge: return "a supersedes b"
if b_ge: return "b supersedes a"
return "concurrent: conflict, keep both or merge"
print(compare({"r1": 2, "r2": 1}, {"r1": 1, "r2": 1})) # a supersedes b
print(compare({"r1": 2, "r2": 0}, {"r1": 1, "r2": 1})) # concurrent
CRDTs
The idea
Conflict-free replicated data types (Shapiro, Preguiça, Baquero and Zawirski, 2011) are data types designed so that replicas can be updated independently and concurrently without coordination, and always converge when they've received the same updates (strong eventual consistency, chapter 69).
Two families:
- State-based (CvRDT): replicas exchange full state and merge with a function that is commutative, associative and idempotent (a join-semilattice). Duplicated, reordered or repeated merges are harmless, which suits unreliable networks perfectly. Delta-state CRDTs ship only recent changes.
- Operation-based (CmRDT): replicas broadcast operations, which must commute; needs reliable, exactly-once, causally ordered delivery.
Common CRDTs
| CRDT | State | Merge |
|---|---|---|
| G-Counter (grow-only) | Map replica → count; each replica increments its own entry | Per-entry max; value = sum |
| PN-Counter | Two G-Counters: increments (P) and decrements (N) | Merge both; value = P − N |
| G-Set | Set with add only | Union |
| 2P-Set | Add set + remove (tombstone) set; can't re-add after removing | Union both |
| OR-Set (observed-remove) | Each add gets a unique tag; remove deletes observed tags | Add-wins semantics: a concurrent add survives a remove |
| LWW-Register | Value + timestamp | Higher timestamp wins (still CRDT, still loses concurrent writes) |
| MV-Register | Keeps all concurrent values | Application picks |
| Sequence CRDTs (RGA, Logoot, YATA, Fugue) | Ordered list of elements with unique position IDs | For collaborative text editing (Yjs, Automerge, Loro) |
// Go: a state-based G-Counter, merge is per-replica max, so it's commutative, associative, idempotent
type GCounter map[string]uint64
func (g GCounter) Inc(replica string) { g[replica]++ }
func (g GCounter) Value() (sum uint64) {
for _, v := range g { sum += v }
return
}
func (g GCounter) Merge(other GCounter) {
for r, v := range other {
if v > g[r] { g[r] = v }
}
}
// Replica A: {A:3}, replica B: {B:2}. Merge in any order, any number of times → {A:3, B:2}, value 5.
// Rust: PN-Counter built from two G-Counters
use std::collections::HashMap;
#[derive(Default, Clone)]
struct GCounter(HashMap<String, u64>);
impl GCounter {
fn inc(&mut self, r: &str, n: u64) { *self.0.entry(r.into()).or_default() += n; }
fn value(&self) -> u64 { self.0.values().sum() }
fn merge(&mut self, o: &GCounter) {
for (r, v) in &o.0 { let e = self.0.entry(r.clone()).or_default(); *e = (*e).max(*v); }
}
}
#[derive(Default, Clone)]
struct PNCounter { p: GCounter, n: GCounter }
impl PNCounter {
fn inc(&mut self, r: &str) { self.p.inc(r, 1) }
fn dec(&mut self, r: &str) { self.n.inc(r, 1) }
fn value(&self) -> i64 { self.p.value() as i64 - self.n.value() as i64 }
fn merge(&mut self, o: &PNCounter) { self.p.merge(&o.p); self.n.merge(&o.n); }
}
# Elixir: delta_crdt (used by Horde for distributed process registries), an add-wins map across nodes
{:ok, crdt} = DeltaCrdt.start_link(DeltaCrdt.AWLWWMap, sync_interval: 50)
DeltaCrdt.set_neighbours(crdt, [{CartCrdt, :"node2@host"}]) # gossip deltas to peers
DeltaCrdt.put(crdt, {"cart", 42, "sku-1"}, 2)
DeltaCrdt.to_map(crdt) # converges on every node
// Java: an OR-Set sketch, each add is tagged uniquely; remove deletes only observed tags (add wins)
final class ORSet<E> {
private final Map<E, Set<UUID>> adds = new HashMap<>();
private final Map<E, Set<UUID>> removes = new HashMap<>();
void add(E e) { adds.computeIfAbsent(e, k -> new HashSet<>()).add(UUID.randomUUID()); }
void remove(E e) { removes.computeIfAbsent(e, k -> new HashSet<>()).addAll(adds.getOrDefault(e, Set.of())); }
boolean contains(E e) {
Set<UUID> live = new HashSet<>(adds.getOrDefault(e, Set.of()));
live.removeAll(removes.getOrDefault(e, Set.of()));
return !live.isEmpty();
}
void merge(ORSet<E> o) {
o.adds.forEach((e, t) -> adds.computeIfAbsent(e, k -> new HashSet<>()).addAll(t));
o.removes.forEach((e, t) -> removes.computeIfAbsent(e, k -> new HashSet<>()).addAll(t));
}
}
Limits of CRDTs
- Invariants across objects can't be maintained ("balance ≥ 0", "room booked once"): merge never fails, so it can't refuse a violating combination. Use escrow/bounded counters (pre-allocate quota to replicas) or coordination.
- Metadata growth: tombstones and per-replica entries accumulate; garbage collection needs coordination (knowing everyone has seen a removal).
- Semantics may surprise users: add-wins versus remove-wins, interleaving in concurrent text inserts. Choose the CRDT whose semantics match the domain.
Choosing a replication strategy
| Need | Strategy |
|---|---|
| Simple, strongly consistent primary with read replicas | Single-leader; sync/semi-sync or consensus for zero data loss |
| Zero data loss + automatic safe failover | Consensus-replicated (Raft/Paxos) groups: CockroachDB, YugabyteDB, TiDB, Spanner, etcd; or PostgreSQL with Patroni + synchronous standbys |
| Low-latency writes in many regions | Multi-leader with per-record home regions, or CRDTs; or a consensus database with regional leader placement |
| Maximum write availability, tunable consistency | Leaderless (Cassandra/ScyllaDB, DynamoDB) |
| Offline/local-first or collaborative editing | CRDTs (Automerge, Yjs, Loro) or OT |
Lab: quorums, repair, clocks and real lag
Experiments 1 and 2 use this book's Python Dynamo model (dyn.py: three replicas with random simulated delays of 1–3 ms, one at 20–40 ms; writes go to all and wait for W; reads ask R random replicas in parallel). Experiment 3 is a timestamp calculation; experiment 4 measures real Redis 7 replication; experiment 5 runs the CRDT logic by hand.
Experiment 1: R, W and the overlap
150 write-then-read pairs per setting, N = 3, one replica 30 ms away:
W=1, R=1 (R+W≤N): stale reads 15/150, median write 5.0 ms, read 6.4 ms
W=1, R=2 (R+W≤N): stale reads 0/150, median write 4.9 ms, read 52.6 ms
W=2, R=1 (R+W≤N): stale reads 8/150, median write 5.7 ms, read 5.8 ms
W=2, R=2 (R+W>N): stale reads 0/150, median write 5.8 ms, read 55.1 ms
W=3, R=1 (R+W>N): stale reads 0/150, median write 62.3 ms, read 6.4 ms
W=1, R=3 (R+W>N): stale reads 0/150, median write 4.9 ms, read 61.3 ms
Every setting with R + W > N had zero stale reads; settings without the overlap were stale up to 10% of the time. (W=1, R=2 happened to show none: with fast replicas the write usually reached a second one before the read; nothing guarantees that.) Latency follows the slowest replica you must wait for: W = 3 made every write pay the far replica, R = 2 often included it. That's why Cassandra users pick LOCAL_QUORUM, a majority within the local datacenter, rather than a global quorum.
Experiment 2: read repair
Replica C was down while 100 keys were updated, then came back. Normal traffic then read every key once with R = 2:
read repair off: C still stale on 100 keys
read repair on : C still stale on 26 keys
Leaderless systems heal replicas in three ways: hinted handoff (a healthy node stores writes meant for the down one and replays them), read repair (a read that sees a stale copy writes the newest version back; here only the replicas a read contacted were repaired, so a third of keys were never touched), and anti-entropy (a background process comparing replicas with Merkle trees, like nodetool repair). Read repair alone leaves cold data stale forever, which is why Cassandra requires regular repairs within gc_grace_seconds, or deleted data can come back.
Experiment 3: last-writer-wins and clock skew
Two writers update the same key 0–20 ms apart; the second writer's clock runs slow by 0, 5 or 50 ms. 1,000 trials each:
second writer's clock 0 ms slow: the later write lost 0/1000 times
second writer's clock 5 ms slow: the later write lost 246/1000 times
second writer's clock 50 ms slow: the later write lost 1000/1000 times
LWW orders writes by wall-clock timestamps, so clock skew decides the winner. NTP typically keeps servers within a few milliseconds, which is enough to lose a quarter of near-simultaneous updates here, and a bad clock loses all of them silently. Remedies: hybrid logical clocks (chapter 75), version vectors that detect concurrency instead of guessing, conditional writes (IF version = n, lightweight transactions), or a single leader per key.
Experiment 4: real replication lag in bytes
Redis 7 primary under a pipelined write load (batches of 200 SETs of 200 bytes), sampling replication offsets every 40 ms for 2 seconds:
nearby replica median 46,890 bytes behind (max 187,560); 3 ms replica median 92,490 (max 140,670)
Even on one machine, under load the replicas were tens of kilobytes behind: hundreds of writes that a replica read wouldn't see. Lag is a distribution that grows with write rate and distance, not a constant; monitor it (master_repl_offset - slave_repl_offset in Redis, pg_stat_replication.replay_lag in PostgreSQL, ReplicaLag in RDS) and alert on it.
Experiment 5: an OR-set versus an LWW set
A shared shopping list: Asha removes "paneer" while Ravi, offline, re-adds it (his add carries an earlier timestamp):
concurrent remove and re-add of 'paneer': LWW-set keeps it: False; OR-set keeps it: True (add wins)
The LWW set let a timestamp decide and dropped Ravi's add. An observed-remove set tags every add uniquely; a remove deletes only the tags it has seen, so a concurrent add survives. Neither is "right": they encode different policies, and choosing the CRDT means choosing the policy (Automerge and Yjs make the same choices for collaborative documents).
Try it yourself
- Add hinted handoff to
dyn.py: when a replica is down, store the write on another with a hint, and replay it when the replica returns. - Repeat experiment 1 with "sloppy quorums" (any 2 of 5 nodes count, not 2 of the key's 3). How does staleness change?
- Implement a PN-counter (increments and decrements) and a version vector, and show the vector detecting the conflict in experiment 3.
- Stop the Redis replica's link for 10 seconds under load and watch it resync: partial (
PSYNC) or full?
Revision sheet: replication
Key ideas
- Goals: availability, durability, read scaling, locality.
- Single leader: synchronous, semi-synchronous or asynchronous followers; log shipping (statement, WAL, logical/row); failover (detection, election, reconfiguration) and its dangers (lost async writes, split brain, fencing).
- Lag anomalies: read-your-writes, monotonic reads, consistent prefix; fixes from chapter 69.
- Multi-leader: per-region leaders, offline clients and collaborative editing; conflicts handled by avoidance (home region per key), LWW, merge functions, CRDTs or user resolution; replication topologies (all-to-all, ring, star).
- Leaderless: N, W, R; R + W > N overlap; sloppy quorums and hinted handoff; read repair; anti-entropy with Merkle trees; tombstones and gc grace.
- Conflict detection: version vectors and dotted version vectors; siblings.
- CRDTs: state-based (merge is commutative, associative, idempotent) and operation-based; G-counter, PN-counter, LWW-register, MV-register, OR-set, RGA/sequence CRDTs (Automerge, Yjs).
Numbers to remember
- Lab: R+W>N gave 0 stale reads, W=1/R=1 up to 10%; read repair left 26% of keys stale on a returning replica; 5 ms clock skew lost 25% of near-simultaneous LWW updates; Redis replicas ran 47–92 KB behind under load.
Pitfalls
- Assuming quorum reads are linearizable (sloppy quorums, concurrent writes and partial failures break it).
- LWW on wall clocks for data that matters.
- Never running anti-entropy repair; resurrected deletes.
- Failing over to an async replica without measuring what's lost.
- Multi-leader without a conflict policy.
Glossary
- Replication lag: delay between a write on the leader and on a follower.
- Quorum: minimum replicas that must respond (W for writes, R for reads).
- Hinted handoff: temporary storage of writes for an unavailable replica.
- Read repair: fixing stale replicas during reads.
- Version vector: per-replica counters detecting concurrent updates.
- CRDT: replicated type with conflict-free merge.