Single-leader replication has one job and does it well: one region takes all the writes, everyone else follows. The moment you ask “can Mumbai and Virginia both accept writes to the same key at the same instant?” that model is dead. You cannot route every write through one leader across an ocean - a user in Mumbai writing to a leader in Virginia eats 200ms of round trip per write, and if Virginia is down, Mumbai cannot write at all. Active-active means every region is a leader. Every region accepts writes locally, at local latency, even when every other region is unreachable. That is the whole appeal, and it is also the whole problem: if Mumbai and Virginia both write to the same key in the same 100ms window, before either has heard of the other, you have two different “latest” values and no leader to arbitrate. Someone has to decide, deterministically, which one wins - and they have to decide it the same way on every continent, with no phone call between regions.

So the real system has two hard halves. The replication half must take every local write and propagate it to every other region within a couple hundred milliseconds, asynchronously, surviving regions that are temporarily cut off and reconnect hours later with a backlog. The convergence half must guarantee that once all writes have propagated, every replica holds byte-for-byte the same state - regardless of the order writes arrived in, regardless of which region saw what first. That is the hard theorem: convergence without coordination. You do not get to pause the world and vote (that is Raft/Paxos, and it needs a quorum round trip you refused to pay). You resolve conflicts with math that is associative, commutative, and idempotent - last-write-wins timestamps or CRDT merge functions - so that the merge is independent of order. DynamoDB global tables, Cassandra multi-DC, and Riak are exactly this system. Let me build it the way I would in an interview: requirements, sizing, architecture, then take the genuinely hard parts - async multi-master replication, conflict detection and resolution, CRDTs, and anti-entropy - from the naive version, break them, and evolve.

Functional Requirements (FR)

In scope:

  • Writes accepted in every region, locally. A client in any region writes to its nearest datacenter and gets an ack at local latency (single-digit ms), without any cross-region round trip on the write path. All regions are peers; none is special.
  • Reads served locally. A read hits the nearest region and returns that region’s current state. Reads are fast and never cross regions on the hot path.
  • Asynchronous replication to all regions. Every local write propagates to every other region in the background. Steady-state cross-region lag is a few hundred milliseconds; a region that was partitioned catches up when the link heals.
  • Automatic conflict resolution. When two regions write the same key concurrently, the system resolves it automatically and deterministically - no human, no app-level merge required for the common case - using last-write-wins (LWW) by default, or CRDT merge for registered CRDT types (counters, sets, maps).
  • Convergence (the core guarantee). Once all in-flight writes have propagated and no new writes occur, every replica converges to the identical state. This is strong eventual consistency: same set of updates applied, same final value, independent of delivery order.
  • Key-value / document data model. Get, Put, Delete on keys; values are blobs or structured documents. Optional registered CRDT types per key (counter, OR-set, LWW-register, map).

Explicitly out of scope (own the boundary so you control scope):

  • Strong consistency / linearizability across regions. We do not promise that a read anywhere reflects the most recent write everywhere. A write in Mumbai may not be visible in Virginia for a few hundred ms. If you need linearizable global reads, you need global consensus (Spanner-style, with the latency bill), and that is a different system. We chose AP; we will not sneak CP back in.
  • Multi-key ACID transactions across regions. No global transactions spanning keys in different regions with atomicity and isolation. Conflict resolution is per-key. Cross-key invariants (“debit A, credit B atomically, globally”) are not provided - that needs coordination we deliberately refuse.
  • Read-your-own-writes across regions by default. Unless pinned to a region, a client that writes in Mumbai and immediately reads from Virginia may not see its write. We offer session stickiness and read-your-writes within a region, not globally for free.
  • Preventing all conflicts. We do not prevent concurrent writes; we resolve them after the fact. A design goal is that resolution is automatic and lossless for CRDT types and deterministic (if lossy) for plain LWW.

The one decision that drives the whole design: we trade global consistency for local availability and latency, and we buy back correctness with order-independent conflict resolution. We are firmly on the AP side of CAP (and the low-latency side of PACELC). Every region writes locally and never waits for another region. The hard, interesting work is making sure that this freedom does not leave replicas permanently disagreeing - that the merge math guarantees they all land in the same place.

Non-Functional Requirements (NFR)

  • Availability: extremely high, per region. Each region accepts reads and writes even when every other region is unreachable. A full network partition isolating a region does not stop it serving its local clients. Target 99.99%+ per region; the system as a whole has no global single point of failure because there is no global anything on the write path.
  • Consistency: strong eventual consistency (convergence). Not linearizable. The guarantee is: replicas that have received the same set of updates are in the same state, and all replicas eventually receive all updates. Conflict resolution is deterministic so convergence does not depend on delivery order.
  • Write latency: single-digit ms (local). A write is acked once it is durable in the local region (local quorum), before cross-region replication. No cross-region round trip on the write path, ever.
  • Read latency: single-digit ms (local). Served from the nearest region.
  • Replication lag: a few hundred ms at p99 steady-state. From local commit to visibility in the farthest region, under normal network conditions. This is the headline number for the replication half. A partitioned region’s backlog drains to this once reconnected.
  • Durability: no acknowledged write is lost. A write is durable in its origin region (replicated to a local quorum, fsynced) before ack. Cross-region replication adds redundancy but local durability stands alone. Under conflict resolution, “lost” means a value was superseded by a deterministic rule, not dropped by a bug.
  • Scale: global DAU in the hundreds of millions; billions of writes/day; 5-10 regions; per-key write rate from trivial to hot (a shared counter hammered from every region). Dataset in the tens of terabytes per region, replicated full-copy to every region (every region holds everything, so any region can serve any key).
  • Fault model: crash-stop, network partitions, and long region isolation (minutes to hours), not Byzantine. Clocks are NTP-synced but not perfectly - clock skew between regions (tens of ms, occasionally more) is a first-class concern, because LWW leans on timestamps.

Back-of-the-Envelope Estimation (BoE)

The numbers justify the architecture and show where the pressure is.

Traffic:

Global DAU                    ~200,000,000
Writes per user per day       ~20   (profile edits, carts, counters, prefs)
Total writes/day              200e6 * 20 = 4e9 writes/day
Avg write QPS                 4e9 / 86,400 ≈ 46,000 writes/sec global
Peak write QPS (3x)           ~140,000 writes/sec global

Read:write ratio              ~10:1
Avg read QPS                  ~460,000 reads/sec global
Peak read QPS                 ~1,400,000 reads/sec global

Per-region load (say 5 regions, roughly even):

Local write QPS per region    ~140,000 / 5 ≈ 28,000 writes/sec (peak)
Local read QPS per region     ~1,400,000 / 5 ≈ 280,000 reads/sec (peak)

Cross-region replication fan-out (the headline pressure):

Every local write must ship to the OTHER 4 regions.
Replication stream out of one region = its local writes * (N-1)
  = 28,000 writes/sec * 4 regions = 112,000 replicated events/sec egress
Each region INGESTS replication from the other 4:
  = 28,000 * 4 = 112,000 replicated writes/sec to apply (peak)
So a region handles ~28K local writes + ~112K inbound replicated writes
  = ~140,000 write-applies/sec. Inbound replication dominates write load.

This is the first key number: a region spends more write capacity applying other regions’ writes than its own. Replication apply, not local write, sizes the write path.

Replication bandwidth:

Avg write payload (key+value+metadata+version vector) ≈ 1 KB
Egress per region = 112,000 events/sec * 1 KB ≈ 112 MB/sec ≈ ~0.9 Gbps
Across 5 regions, total cross-region replication ≈ ~4.5 Gbps steady-state,
  spiking with backlogs. Batching and compression cut this substantially.

Storage:

Per key stored: value (~1 KB) + version metadata (version vector / timestamps,
   ~200 B for a few regions) + tombstones for deletes.
Live keyspace                 say 20 billion keys * 1.2 KB ≈ 24 TB live
Every region holds a FULL copy (any region serves any key) => 24 TB per region.
With local replication factor 3 within a region => ~72 TB raw per region.
Writes/year for history/backup: 4e9/day * 365 * 1KB ≈ 1.46 PB/year of write volume
   (not all retained; compacted, but sizes backups and CDC streams).

Conflict rate (why resolution matters but is not the bulk):

A conflict needs two regions writing the SAME key within the replication
window (~hundreds of ms). For most keys (user-owned data) cross-region
concurrent writes are rare - a user is usually in one region.
But SHARED keys (global counters, inventory, collaborative docs) can
conflict constantly. Design for: common case near-zero conflict (cheap),
hot shared keys with high conflict (CRDTs earn their keep there).

Conflict metadata memory:

Version vector = one (region_id, counter) per region that touched the key.
For 5 regions, ~5 * (4B id + 8B counter) = 60 B, plus LWW timestamp 8 B.
Negligible per key, but it is per key across 20B keys => ~1.2 TB of version
metadata per region. Keep it compact (prune entries, cap vector size).

The headline: local writes and reads are modest per region and served locally (the easy part). The expensive, architecture-defining pressure is inbound cross-region replication (a region applies ~4x its own write rate from peers) and conflict resolution on shared hot keys. Making replication converge correctly and cheaply, and resolving conflicts deterministically without coordination, is the entire design.

High-Level Design (HLD)

The spine: N symmetric regions, each a complete, independently-writable replica of the full keyspace. Within a region, data is sharded and locally replicated (local quorum for durability). Each region has a local write path (client writes land locally, get a version stamp, commit to a local quorum, ack) and a replication path (every committed write is captured from a durable change log and streamed to every other region, where it is applied through a conflict resolver). A background anti-entropy process (Merkle-tree sync) repairs anything the streaming path missed. There is no global coordinator, no global leader, nothing that all regions must agree on synchronously.

   ┌─────────────────────────────┐          ┌─────────────────────────────┐
   │        REGION: Mumbai        │          │       REGION: Virginia       │
   │  ┌────────┐   Clients (local)│          │ Clients (local)  ┌────────┐  │
   │  │ API/    │◀── read/write ──│          │─── read/write ──▶│ API/    │  │
   │  │ coord   │                 │          │                  │ coord   │  │
   │  └───┬─────┘                 │          │                  └────┬────┘  │
   │      │ stamp version, local  │          │   stamp version, local│       │
   │      ▼ quorum write + ack    │          │   quorum write + ack  ▼       │
   │  ┌──────────────────────┐    │          │    ┌──────────────────────┐   │
   │  │ Sharded KV store      │   │          │    │ Sharded KV store      │  │
   │  │ (RF=3 in-region)      │   │          │    │ (RF=3 in-region)      │  │
   │  │ + per-key version meta│   │          │    │ + per-key version meta│  │
   │  └─────────┬────────────┘    │          │    └──────────┬───────────┘   │
   │            │ change log (CDC) │          │ change log (CDC)│            │
   │     ┌──────▼───────┐          │          │        ┌───────▼──────┐      │
   │     │ Replicator    │         │          │         │ Replicator   │     │
   │     │ - reads CDC   │         │          │         │ - reads CDC  │     │
   │     │ - ships events│         │          │         │ - ships events│    │
   │     │ - applies in  │         │          │         │ - applies in │     │
   │     │   via RESOLVER│         │          │         │   via RESOLVER│    │
   │     └──┬────────▲───┘         │          │         └──▲────────┬──┘     │
   └────────┼────────┼────────────┘          └────────────┼────────┼────────┘
            │        │                                     │        │
            │        │     cross-region replication        │        │
            │        └─────────────────────────────────────┘        │
            │          (async, ordered-per-origin, retried)         │
            └───────────────────────────────────────────────────────┘
                   also: periodic Merkle-tree ANTI-ENTROPY sync
                   (repairs drift from dropped/duplicated events)

        [ Tokyo, Frankfurt, Sao Paulo regions identical, full mesh ]

Write flow (local, no cross-region wait):

  1. A client writes Put(key, value) to its nearest region’s API/coordinator.
  2. The coordinator assigns a version stamp: a per-region monotonic sequence plus a wall-clock timestamp (for LWW) and/or updates the key’s version vector (for conflict detection). The origin region id is recorded.
  3. The write is committed to a local quorum within the region (e.g. 2 of 3 replicas, fsynced) and acked to the client. This is the only thing on the write path - single-digit ms, no ocean crossing.
  4. The committed write lands in the region’s durable change log (CDC stream) - an append-only, ordered-per-shard log (think the commit log / a Kafka-like stream).

Replication flow (async, background):

  1. The region’s Replicator tails the change log and ships each event (key, value, version stamp, version vector, origin, timestamp) to every other region, in per-origin order, batched and compressed, over durable connections with retry and offset tracking.
  2. A receiving region’s Replicator applies each inbound event through the conflict resolver: it looks up the local current version of the key, compares versions (version vector dominance, then LWW timestamp or CRDT merge for ties/concurrency), and writes the winning/merged value locally. The apply is itself idempotent (re-delivering the same event is a no-op).
  3. The receiving region does not re-replicate events that originated elsewhere in a way that loops; origin tracking and version vectors stop replication cycles (an event already reflected is a no-op, so even if it arrives twice via different paths it converges).

Read flow (local):

  1. A read goes to the nearest region and returns that region’s current value for the key. Optionally the client requests the value with its version vector to do application-level conflict handling (siblings), but by default the resolver has already collapsed to a single value.

Anti-entropy flow (repair):

  1. Periodically, pairs of regions exchange Merkle tree hashes over key ranges. Where hashes differ, they drill down to find the specific diverged keys and exchange just those, re-running the resolver. This catches anything the streaming path dropped, duplicated out of the idempotency window, or missed during a long partition. Streaming gives low latency; anti-entropy guarantees eventual convergence even if streaming is lossy.

The structural insight: local availability comes from never waiting on another region; convergence comes from making every apply a deterministic, order-independent merge. The replication stream is best-effort-but-ordered-per-origin for low latency; anti-entropy is the backstop that makes “eventual” actually eventual. No component requires all regions to agree synchronously, which is exactly why a region can keep serving while the rest of the planet is unreachable.

Component Deep Dive

The genuinely hard parts, naive-first then evolved: (1) asynchronous multi-master replication that does not loop or lose writes; (2) detecting concurrent writes (you cannot resolve a conflict you cannot detect); (3) resolving conflicts deterministically - LWW and its traps, then CRDTs; (4) anti-entropy so convergence is guaranteed, not hoped for.

1. Asynchronous multi-master replication

The job: every write committed in any region must reach every other region, in an order that lets the resolver converge, without replication loops, without losing writes when links drop, and without waiting on any region at write time.

Naive approach: each region broadcasts every write to every other region, fire-and-forget

The obvious first cut: when a region commits a write, it immediately sends a UDP/HTTP message with the new value to all other regions, which overwrite their local copy. Simple full mesh, no log.

Mumbai commits key=5 -> POST {key, value} to Virginia, Tokyo, Frankfurt
Each receiver: store[key] = value

Where it breaks:

  • Lost writes on any failure. The link to Tokyo blips for 2 seconds; those writes are gone forever. Fire-and-forget has no retry, no durability, no catch-up. A region that was partitioned for an hour comes back permanently missing an hour of everyone’s writes.
  • No ordering, so last-arrived-wins by network luck. Two writes to the same key from Mumbai arrive at Virginia out of order (retries, multipath); Virginia ends with the older value. “Overwrite with whatever arrived last” makes the final state depend on network timing, so regions diverge and never converge.
  • Replication storms and loops. If a receiver re-broadcasts what it receives (to propagate through a non-full mesh), events loop forever. Even in a full mesh, a write reflected back is reapplied endlessly without a stop condition.
  • Replication competes with and blocks the write path. Doing the broadcast inline in the request means a slow region slows local writes - breaking the “never wait on another region” rule.

Fire-and-forget gives you neither durability nor convergence. The final state is a function of packet timing, which is the definition of divergence.

Evolved approach: a durable per-region change log, pull/stream replication with offsets, origin tracking, idempotent apply

Capture every committed write in a durable, ordered log and replicate from the log, so replication is decoupled from the write path, survives outages, and delivers in a convergence-friendly order.

  • Durable change log per shard (CDC). Every committed local write is appended to a durable, append-only, ordered-per-shard log (the commit log itself, exposed as a change stream). This is the source for replication. Because it is durable and ordered, replication can resume from any point and never loses a write.
  • Replication decoupled from the write path. The client write path ends at “committed to local quorum + appended to log + acked.” A separate Replicator process tails the log and ships events. A slow or dead peer never touches local write latency. This is the structural fix for “never wait on another region.”
  • Streaming with per-peer offsets (replication slots). For each destination region, the Replicator tracks the offset up to which that region has acknowledged receipt. It streams forward from there, batched and compressed. If the link drops, it resumes from the last acked offset when it heals - no gaps, no manual intervention. A region partitioned for an hour drains its backlog on reconnect.
  • Ordered-per-origin delivery. Events from a given origin region are delivered to peers in the origin’s commit order. This does not give a global order (impossible without coordination) but it gives a per-origin order, which combined with version vectors is enough for the resolver to converge. A receiver applies origin X’s events in X’s order; interleaving across origins is resolved by the conflict rules, not by arrival order.
  • Origin tracking and loop prevention. Every event carries its origin region id and the key’s version vector. A receiving region, when it re-examines data, never reflects an event back toward a region that already has it, and - crucially - apply is idempotent: an event whose version is already dominated by the local state is a no-op. So even in a full mesh, or if an event arrives via two paths, reapplying it changes nothing. Loops terminate because a twice-seen update is a no-op.
  • Idempotent, commutative apply. The apply step does not blindly overwrite; it runs the conflict resolver (deep dives 2-3), which is idempotent (reapplying an event yields the same state) and commutative (order of applying events from different origins does not change the final state). This is what makes “at-least-once, out-of-order-across-origins” delivery safe.
Mumbai commit: append to shard log @ offset 9471
   event = { key, value, origin=MUM, vv={MUM:52,VIR:17,...}, ts=... }
Replicator(MUM->VIR): stream from VIR's acked offset 9468 forward, batched
   VIR applies 9469,9470,9471 in MUM-order, each through RESOLVER (idempotent)
   VIR acks offset 9471 back to MUM
Link MUM->TOK down 1 hour -> TOK's acked offset frozen at 9000
   link heals -> MUM streams 9001..current -> TOK drains backlog, catches up
Event replayed twice (retry) -> second apply: vv already dominates -> NO-OP

Why this is right: the durable per-shard log makes replication lossless and resumable (no write is ever dropped, partitions just create a drainable backlog); decoupling replication from the write path keeps local writes fast regardless of peer health; per-peer offsets give exactly the catch-up semantics a geo-system needs; and idempotent, commutative apply plus origin/version tracking kill replication loops and make out-of-order cross-origin delivery safe. This is precisely how Cassandra/DynamoDB-style systems replicate across DCs: from the commit log, with offsets and resolution on apply.

2. Detecting concurrent writes (version vectors)

The job: before you can resolve a conflict, you must detect one - distinguish “Virginia’s write is strictly newer than what I have (just apply it)” from “Virginia’s write and my local write are concurrent (neither saw the other - conflict, must resolve)”. Wall-clock timestamps alone cannot tell these apart safely.

Naive approach: compare wall-clock timestamps, newer timestamp wins

Each write carries the origin’s wall-clock time. On apply, if the incoming timestamp is greater than the stored one, overwrite; else drop. “Latest write wins by the clock.”

Where it breaks:

  • Clock skew silently loses writes. Region clocks differ by tens of ms (sometimes seconds under NTP trouble). Mumbai writes at its 10:00:00.050; Virginia writes later in real time at its 10:00:00.040 (its clock is behind). Virginia’s write has the smaller timestamp, so it loses - even though it happened after and the user saw it succeed. A write the user was told succeeded vanishes. Worse, it is non-deterministic: it depends on which way the clocks drift.
  • Cannot distinguish concurrent from causal. Timestamp comparison treats every pair of writes as ordered. It cannot tell “these two writes were truly concurrent (a real conflict the app might care about)” from “one causally followed the other.” For plain LWW you might accept that, but for anything that needs to preserve both writes (a shopping cart, a set), silently picking one by clock is data loss you cannot even detect.
  • Ties are undefined. Equal timestamps (coarse clocks, same ms) have no defined winner, so different regions can pick different winners and never converge.

Timestamps give an ordering that is physically wrong under skew and logically blind to concurrency. Necessary for a tiebreak maybe, but not a detection mechanism.

Evolved approach: version vectors for detection, with a deterministic tiebreak

Track causality explicitly with a version vector (one counter per region), so you can tell dominance from concurrency precisely, and only fall back to a timestamp/merge when writes are genuinely concurrent.

  • Version vector per key. Each key carries vv = { region_id -> counter }. When a region commits a write to the key, it increments its own counter and records the vector it based the write on. The vector captures “which updates from which regions this value has seen.”
  • Dominance vs concurrency, defined exactly. Given incoming vector A and local vector B:
    • A dominates B (A >= B on every entry, strictly greater on at least one): the incoming write causally saw everything local plus more. Just apply it, no conflict.
    • B dominates A: the local value is already newer and has seen the incoming write’s history. Drop the incoming (it is stale / a redelivery). This is the idempotency that kills loops.
    • Neither dominates (they diverge - each has an entry the other lacks): the writes are concurrent. This is a true conflict - neither saw the other - and only now do we invoke resolution (LWW tiebreak or CRDT merge).
  • This makes “newer” meaningful without a global clock. Causality, not wall time, decides dominance. Clock skew cannot cause a causally-newer write to lose, because dominance is checked on counters that increment on actual writes, not on clocks. Timestamps re-enter only as a tiebreaker among genuinely concurrent writes, where by definition there is no causal order to violate.
  • Keep vectors bounded. A vector has one entry per region that ever wrote the key - bounded by the number of regions (5-10), which is tiny, unlike per-client vector clocks that grow unboundedly. Entries for regions that are provably caught up can be pruned. This is why region-granular version vectors are practical where per-actor vector clocks are not.
  • Siblings (optional, for lossless types). For data where losing a concurrent write is unacceptable, the system can keep both concurrent values as siblings (like Riak) and expose them to the application or a CRDT merge on next read, rather than auto-picking one. LWW collapses siblings immediately; CRDTs merge them; plain registers can defer to the app.
Key "cart" local vv = {MUM:3, VIR:5}
Incoming from VIR: vv = {MUM:3, VIR:6}   -> dominates local (VIR 6>5, rest equal)
   => APPLY, no conflict (VIR had seen MUM:3 and added one more)
Incoming from TOK: vv = {MUM:4, TOK:1}   -> neither dominates
   local has VIR:5 TOK lacks; incoming has MUM:4,TOK:1 local lacks
   => CONCURRENT -> invoke RESOLVER (LWW tiebreak or CRDT merge)
Redelivery: incoming vv = {MUM:3,VIR:5} == local or dominated -> NO-OP (idempotent)

Why this is right: version vectors detect concurrency exactly, so the system knows when it has a real conflict versus a clean causal update - which clock timestamps fundamentally cannot do. Dominance gives free idempotency (stale/duplicate deliveries are no-ops, closing replication loops), and it makes “newer” immune to clock skew for all causally-ordered writes. Wall-clock time is demoted to a last-resort tiebreak among truly concurrent writes, which is the only place it is safe. Region-granular vectors stay small, which is what makes this tractable at planetary scale.

3. Resolving conflicts deterministically - LWW, then CRDTs

The job: when version vectors say two writes are concurrent, pick a result that (a) is identical on every region no matter what order events arrived, and (b) ideally loses no information. The merge must be commutative, associative, and idempotent so convergence does not depend on delivery order.

Naive approach: last-write-wins by timestamp, overwrite the loser

The common default: among concurrent writes, keep the one with the highest wall-clock timestamp; discard the rest. Ties broken by, say, region id.

concurrent writes to "status": (MUM, ts=100, "away") vs (VIR, ts=101, "busy")
LWW -> keep "busy" (ts 101 > 100). "away" discarded.

Where it works and where it breaks:

  • It converges, which is the main thing. max(ts, region_id) is commutative, associative, and idempotent - every region independently computes the same winner regardless of arrival order. So LWW does give strong eventual convergence. For single-value, overwrite-semantics data (a user’s status, a “last known location,” a config flag) this is correct and cheap. This is why LWW is the sensible default.
  • It silently loses the concurrent write. “away” is gone. For a status, fine. For a shopping cart, catastrophic: Mumbai adds a book, Virginia concurrently adds a pen, LWW keeps one cart and the other item vanishes - the user loses an item they were told they added. LWW is lossy by design; it is only acceptable when overwrite is the correct semantics.
  • It still leans on clocks for the tiebreak. Among concurrent writes, the “winner” is whoever had the larger timestamp, which under skew is arbitrary. It converges (deterministic) but the choice is not meaningful - it is a coin flip the clocks make. For true last-writer semantics you want hybrid logical clocks (below) to make the tiebreak less arbitrary.

LWW is the right tool for overwrite data and the wrong tool for data where concurrent writes should combine. For the latter, you need a merge that keeps information.

Evolved approach: CRDTs - merge functions that combine concurrent writes losslessly

For data where both concurrent writes matter, use Conflict-free Replicated Data Types: types whose merge function is a mathematical join (least upper bound on a lattice), so merging is commutative, associative, idempotent, and information-preserving. No value is lost; the merge combines them.

  • LWW-Register. A single value with a timestamp; merge = keep the higher timestamp. This is LWW itself, formalized as a CRDT - use it for overwrite semantics (status, config). Deterministic, lossy by intent.
  • G-Counter / PN-Counter (grow-only / increment-decrement counter). The classic “global counter hit from every region.” Each region keeps its own per-region subcount; the counter’s value is the sum of all regions’ subcounts. A region only ever increments its own entry; merge = per-region max (or for PN, separate increment and decrement vectors). Because each region owns its slot, concurrent increments from different regions never conflict - they are added, not overwritten. Mumbai +1 and Virginia +1 concurrently yield +2 everywhere, always. This is the correct way to do a cross-region counter; LWW would have lost one of the increments.
PN-Counter "likes": per-region P (increments) and N (decrements) vectors
   MUM: P={MUM:10}  VIR: P={VIR:7}
   merge = per-region max of P and N, value = sum(P) - sum(N)
   after merge everywhere: P={MUM:10,VIR:7} -> value 17. Concurrent +1s both kept.
  • OR-Set (observed-remove set). A set supporting concurrent add and remove without the “add vs remove race” losing data. Each added element carries a unique tag (region + counter). Add = insert element with a fresh tag; remove = record the tags you observed as removed. Merge = union of adds minus observed removes. An add concurrent with a remove survives (its tag was not observed by the remover), which is usually the intent for a cart/collaborative set. This fixes exactly the LWW cart-loss bug: Mumbai’s book and Virginia’s pen both have distinct add-tags, merge = both present.
  • CRDT Map / nested CRDTs. A map whose keys map to CRDT values (registers, counters, sets), merged field-by-field. This composes the above into documents - a shopping cart as an OR-set of items, each item quantity a PN-counter, each with independent conflict-free merge.
  • Hybrid Logical Clocks (HLC) for better LWW tiebreaks. Where LWW is used, stamp writes with an HLC - a timestamp that is close to wall-clock but also captures causality (it never goes backward relative to observed events and increments a logical component on ties). This keeps LWW’s determinism while making the “winner” respect causality where the plain wall clock would pick wrong under skew. HLC is the pragmatic middle: physical-clock-friendly, causality-aware, bounded size.
  • Registering a type per key / per keyspace. The system lets the application declare a key’s type (LWW-register, counter, OR-set, map). The resolver dispatches to that type’s merge. Unregistered keys default to LWW-register. This is how you make “automatic conflict resolution” real: the type carries the merge law, so resolution needs no app code at apply time and no coordination.
ConcernLWW-RegisterPN-CounterOR-SetCRDT Map
Semanticsoverwrite, keep latestnumeric add/subset add/removedocument of CRDTs
Concurrent writesone wins (lossy)all combine (sum)all combine (union)per-field merge
Merge rulemax timestampper-region max, sumadds minus observed removesrecurse per field
Good forstatus, config, flagscounters, likes, inventorycarts, tags, membershipsstructured docs
Costtiny (1 value + ts)O(regions) subcountsO(elements + tags)sum of fields

Why this is right: LWW converges and is the correct, cheap default for overwrite data, so it stays the baseline - but it is lossy, so for data where concurrent writes must combine, CRDTs provide a merge that is provably order-independent (a lattice join: commutative, associative, idempotent) and lossless. The merge law lives in the data type, so resolution is automatic and needs zero cross-region coordination - every region computes the identical merged state from the same set of updates, which is exactly strong eventual consistency. HLC upgrades LWW’s tiebreak from “arbitrary under skew” to “causality-respecting.” This is the real heart of active-active: you do not prevent conflicts, you make the merge math guarantee convergence.

4. Anti-entropy - guaranteeing convergence, not hoping for it

The job: the streaming replication path is best-effort (events can be dropped beyond the retry window, a region can be down past log retention, bugs happen). “Eventual consistency” has to be a guarantee, so there must be a background process that detects and repairs any divergence between replicas.

Naive approach: trust the replication stream, re-sync everything periodically if worried

First cut: assume streaming delivers everything; if you are paranoid, periodically have regions ship their entire keyspace to each other and merge.

Where it breaks:

  • Full re-sync is impossibly expensive. 24 TB per region shipped to 4 peers, repeatedly, is petabytes of pointless transfer when 99.999% of keys already match. You cannot afford to re-send data that is already identical.
  • Trusting the stream is not a guarantee. Log retention expires while a region is down for a day; those events are gone from the stream. A dropped-and-never-retried event (bug, poison message) leaves a permanent silent divergence that streaming will never fix. Without a comparison mechanism, you never even know two regions disagree.

You need to find just the diverged keys cheaply, without comparing every key, and repair only those.

Evolved approach: Merkle-tree range comparison, repair only the diffs, re-run the resolver

Summarize each region’s data as a Merkle tree of hashes over key ranges, compare trees between regions to localize divergence to small ranges in logarithmic work, and exchange only the keys that actually differ.

  • Merkle tree over key ranges. Each region maintains a hash tree: leaves hash small key ranges (or individual keys/partitions), internal nodes hash their children. The root hash summarizes the whole dataset (or a shard). Two regions with identical data have identical root hashes.
  • Logarithmic divergence detection. To compare, two regions exchange root hashes. If equal, done - no divergence, almost no data moved. If different, they descend: compare child hashes, recurse only into subtrees that differ. Divergence is localized to the specific small ranges that mismatch in O(log n) comparisons and O(diff) data, not O(n). Finding a handful of diverged keys among billions costs a few round trips of hashes.
  • Repair by exchanging only diffed keys, through the resolver. For each key in a mismatched range, the regions exchange the key’s value and version metadata and run the same conflict resolver (version-vector dominance, then LWW/CRDT merge). Because the resolver is deterministic and the merge is a lattice join, repair converges to the identical state on both sides - anti-entropy uses the exact same merge law as streaming, so it can never introduce divergence, only remove it.
  • Scheduled and triggered. Anti-entropy runs continuously in the background at low priority (incremental range sweeps) and is triggered after a region rejoins from a long partition (streaming drains the recent backlog; anti-entropy catches anything past log retention). It is the safety net that makes the latency-optimized streaming path tolerable: streaming can be lossy because anti-entropy guarantees eventual repair.
  • Tombstones and delete convergence. Deletes are tombstones (a delete marker with a version), not immediate removals, so that a delete can win/lose a conflict and propagate like any write; a key deleted in Mumbai but concurrently written in Virginia resolves by the normal rules instead of “reappearing” because one region forgot it. Tombstones are garbage-collected only after they are provably propagated everywhere (past a GC grace period longer than the max partition/anti-entropy window), to avoid a resurrected delete.
MUM root hash  ==  VIR root hash ?  yes -> done (no transfer)
                                    no  -> descend
  range [a..m] hashes equal -> skip
  range [m..z] hashes differ -> descend
     subrange [t..v] differs -> exchange those keys + version metadata
        run RESOLVER on each -> both regions converge to merged value
Deleted key = tombstone{ver}; propagates & conflicts like a write;
   GC tombstone only after propagated everywhere + grace period

Why this is right: Merkle trees turn “are these two 24 TB replicas identical, and if not where do they differ” into a logarithmic-cost comparison that moves almost no data in the common (identical) case and pinpoints exactly the diverged keys when they differ. Repairing through the same deterministic resolver means anti-entropy can only converge, never diverge. This is what upgrades “eventual consistency” from a hope that streaming delivered everything to a guarantee: even if the stream drops events or a region is down past retention, background Merkle sync finds and heals the drift. Tombstones make deletes first-class in that convergence so a delete cannot be silently undone. Cassandra, DynamoDB, and Riak all use this exact Merkle-anti-entropy pattern for a reason.

API Design & Data Schema

API

Key-value / document API, served at the nearest region. Conflict metadata is exposed for clients that want it; most do not.

Core operations:

Put(key, value, type?, if_version_vector?) -> { version_vector, origin_region, hlc }
   type              => register|counter|orset|map (default: lww-register); set once per key
   if_version_vector => optional CAS: apply only if current vv matches (local-region guarded)
Get(key, with_siblings?) -> {
     value,                       // resolved single value (default)
     version_vector, hlc, origin_region,
     siblings?: [ {value, version_vector} ]   // only if with_siblings and unresolved conflict
   }
Delete(key) -> { version_vector }    // writes a tombstone, replicates like any write

CRDT-typed operations (resolve to merges, never lose concurrent ops):

Increment(key, delta)        -> { value }    // PN-counter; delta may be negative
SetAdd(key, element)         -> { }          // OR-set add (unique tag assigned)
SetRemove(key, element)      -> { }          // OR-set observed-remove
MapUpdate(key, field, op)    -> { }          // nested CRDT field update

Replication / operational (internal, region-to-region):

ReplicateStream(from_region, since_offset) -> stream of {
     key, value, type, version_vector, origin_region, hlc, offset, tombstone?
   }                                          // per-origin ordered, batched, compressed
AckOffset(to_region, offset)                 // receiver confirms durable apply up to offset
MerkleRoot(shard, range)     -> { hash }      // anti-entropy: compare
MerkleChildren(shard, range) -> [ {subrange, hash} ]   // descend into diffs
FetchKeys(shard, [keys])     -> [ {key, value, version_vector, hlc, tombstone?} ]  // repair

Consistency knobs (per request, client chooses the tradeoff):

Put/Get can request local consistency level within a region:
   W = ONE | LOCAL_QUORUM     (durability vs latency inside the origin region)
   R = ONE | LOCAL_QUORUM     (read freshness vs latency inside the serving region)
Cross-region is ALWAYS async (that is the point); there is no global quorum option.
Optional: session token for read-your-writes WITHIN a region (sticky routing).

Data model and storage

NoSQL, deliberately - specifically a sharded, multi-region key-value / wide-column store, not SQL. Here is the reasoning and the schema.

The choice is NoSQL because the requirements are a textbook fit and SQL is a textbook misfit:

  • Multi-master writes with per-key conflict resolution is not something relational engines do across regions; they assume a single writer or synchronous replication. A key-value model with per-key version metadata and pluggable merge is exactly what we need.
  • No cross-region joins or multi-key transactions (explicitly out of scope). We never need relational query power across regions; we need fast key lookups and key-local merges. Paying for SQL’s transactional machinery we will not use is wrong.
  • Horizontal sharding + full-copy-per-region replication with tunable local quorum is native to Cassandra/DynamoDB-style stores and awkward to bolt onto a relational system.
  • CRDT values and version vectors are schemaless per-key metadata that a wide-column/document store holds naturally.

So: a wide-column / KV store, sharded within each region (consistent hashing on the key), locally replicated (RF=3, LOCAL_QUORUM), with every region holding a full copy of all shards.

Primary record (per key, in each region):

Table: kv  (wide-column / document; partition key = key hash)
  key              string        PARTITION KEY (consistent-hash sharded within region)
  type             enum          register | counter | orset | map
  value            blob/json      resolved value materialized for fast Get
  version_vector   map<region_id,int64>   // causality: {MUM:52, VIR:17, TOK:4}
  hlc              int64          // hybrid logical clock for LWW tiebreak
  origin_region    int16          // region that produced the current value
  tombstone        bool           // true => deleted (GC after grace period)
  updated_at       int64          // local apply time (for metrics / TTL)

  Local secondary: shard -> Merkle tree over key ranges (for anti-entropy)

CRDT state (for non-register types, stored alongside value):

counter key:   pn = { region_id -> {p:int64, n:int64} }   // value = sum(p)-sum(n)
orset key:     adds = { element -> set<tag(region_id,counter)> }
               removes = set<tag>                           // observed-remove tombstones
map key:       field -> (nested CRDT state as above)

Change log (CDC, per shard, durable, ordered):

Topic/log per shard (Kafka-like, append-only, retained for backlog window):
  offset         int64         // monotonic per shard; replication cursor
  key, type, value
  version_vector, hlc, origin_region, tombstone
  committed_at   int64
  Consumed by Replicators; per-peer offset tracked in replication_state.

Replication state (per peer region, per shard):

Table: replication_state
  (shard, peer_region)  -> { acked_offset int64, last_heartbeat int64 }
  // Replicator streams from acked_offset+1; resumes here after a partition.

Why these choices, stated plainly: the store is NoSQL (sharded wide-column/KV) because the workload is per-key reads/writes with per-key conflict resolution, horizontal sharding, and full-copy multi-region replication - all native to this model and all awkward or impossible in a relational, single-writer engine; we explicitly have no cross-region joins or transactions to justify SQL. Version vectors + HLC live on every record because they are what make conflict detection and LWW tiebreaks correct without a global clock. CRDT state is stored alongside the value so merges are local and lossless for the types that need it, while plain keys stay cheap as LWW-registers. The durable per-shard change log is the backbone of lossless, resumable replication, and per-peer offsets give partition catch-up for free. The Merkle tree is maintained as derived state per shard so anti-entropy is cheap. Every region holds a full copy so any region serves any key locally - the whole point of active-active.

Bottlenecks & Scaling

Where it breaks first, in order, and the fix for each.

1. Inbound replication apply load (breaks first). Each region applies ~4x its own write rate from peers (the BoE showed inbound dominates). A hot write period floods every region’s apply path. Fix: shard the keyspace (consistent hashing) so apply parallelizes across many shards/nodes within a region; batch and compress replication streams; make apply cheap and idempotent (version-vector check is O(regions)); apply at LOCAL_QUORUM not full local RF to bound cost; scale apply workers horizontally. Shard key = the data key’s hash, chosen for even load spread.

2. Hot key with cross-region write conflict (the signature failure). A single shared key (global counter, popular item inventory) written from every region conflicts constantly; LWW would lose writes and thrash. Fix: make hot shared keys CRDTs - a PN-counter’s per-region subcounts mean concurrent increments from all regions never conflict (they sum), turning the worst case into a non-conflict; OR-sets do the same for shared sets. For a single scalar that genuinely must be a running total, the CRDT counter is the answer, not coordination. Where a key is read-hot too, serve from local replica + cache.

3. Replication lag blowing past a few hundred ms. Backlogs (traffic spikes, a slow link, a recovering region) push cross-region visibility up. Fix: parallel replication streams per shard so one slow shard does not stall others; batching with a latency cap (flush on size or on a few-ms timer, whichever first) to balance throughput and lag; compression to cut bandwidth; prioritize live streaming over anti-entropy; monitor per-peer lag and autoscale Replicator throughput. Accept that a partitioned region’s lag is unbounded until it reconnects - that is the AP tradeoff - and drain its backlog fast on heal.

4. Clock skew corrupting LWW. NTP drift makes wall-clock LWW pick physically-wrong winners and risks non-convergence on ties. Fix: use version vectors for detection (immune to skew - dominance is on counters), and HLC for the LWW tiebreak so the timestamp is causality-aware and monotonic, not raw wall clock; tight NTP (or better, a bounded-clock service) to keep HLC’s physical component close; region id as the final deterministic tiebreak so ties always converge even if clocks match.

5. Version-vector / metadata growth. One VV entry per region per key is small, but across 20B keys it is ~TB of metadata; per-actor vector clocks (if misdesigned) would explode. Fix: use region-granular vectors (bounded by 5-10 regions), not per-client - this is the key sizing decision; prune VV entries for regions provably caught up (below a watermark all regions have acked); cap and compact CRDT metadata (GC OR-set remove-tags once observed everywhere). Never let the conflict metadata be per-request-actor.

6. Tombstone accumulation and resurrected deletes. Deletes kept as tombstones pile up; GC them too early and a delayed replica resurrects the key. Fix: GC tombstones only after a grace period longer than the max partition + anti-entropy window and after they are provably propagated everywhere (all peers acked past that offset); size the grace period from the worst realistic region-down time. This trades disk for correctness, correctly.

7. Anti-entropy cost at 24 TB per region. Naive full compare is petabytes of transfer. Fix: Merkle trees make comparison logarithmic and transfer proportional to the actual diff (near zero when in sync); run anti-entropy incrementally and low-priority in the background; trigger a focused sweep after a region rejoins instead of always full-scanning. Streaming carries the latency-sensitive path; Merkle sync is the cheap backstop.

8. A region failing entirely. One region (and its clients) must fail over without data loss or global stall. Fix: because every region is a full independent replica, clients of a dead region are routed (GeoDNS / anycast) to the next-nearest region and keep reading/writing there; no data is lost (the dead region’s acked writes were already replicated, or drain from its log on recovery); the rest of the world is unaffected since there is no global coordinator to lose. On recovery the region catches up via log backlog + anti-entropy before taking traffic. This is the availability payoff of active-active.

9. Read-your-writes / monotonic reads surprises. A user writing in Mumbai then reading from Virginia may not see their write (async replication). Fix: sticky session routing (pin a session to its origin region) for read-your-writes and monotonic reads within that region; expose a version token the client can pass so a read can wait-for or be routed to a replica that has it; document that global read-your-writes is explicitly not offered (it would need coordination). Set client expectations rather than fake consistency.

10. Replication loops / duplicate apply at scale. In a full mesh with retries, events arrive multiple times and via multiple paths. Fix: idempotent apply (version-vector dominance makes a re-seen update a no-op) and origin tracking so an event is never usefully reflected back; per-peer offsets dedupe the stream. The merge being commutative + idempotent is what makes at-least-once, multi-path delivery safe - no exactly-once machinery needed.

Shard keys and placement, stated plainly: data is sharded within each region by key hash (consistent hashing, even spread, parallel apply); every region holds every shard (full copy, so any region serves any key locally - active-active requires it); writes serialize only to a local quorum, never globally; conflict resolution is per-key via version-vector detection + LWW/CRDT merge; the change log is partitioned per shard for parallel replication; replication cursors are per (shard, peer region). Nothing shards or coordinates globally - that absence is the design.

Wrap-Up

The trade-offs that define this design:

  • Availability and latency over global consistency (AP, and the EL of PACELC), on purpose. Every region writes and reads locally and never waits on another region, even during a total partition. We give up linearizable global reads and cross-region transactions to get it. A system that stays up and fast in every region, and converges a few hundred ms later, beats one that blocks writes waiting for an ocean round trip - for the data this fits (and we were explicit about what does not fit).
  • Convergence without coordination, bought with merge math. We do not prevent conflicts; we resolve them with functions that are commutative, associative, and idempotent, so the final state is independent of delivery order. Version vectors detect concurrency exactly (immune to clock skew); LWW+HLC resolves overwrite data deterministically; CRDTs resolve combinable data losslessly. The merge law lives in the data type, so resolution needs zero cross-region agreement.
  • Replication decoupled from the write path, lossless and resumable. Writes commit locally and hit a durable per-shard log; Replicators stream from the log with per-peer offsets, so a slow or partitioned peer never touches local latency and always catches up. Streaming is latency-optimized; anti-entropy via Merkle trees is the guarantee that makes “eventual” actually eventual, repairing any drift the stream missed in logarithmic cost.
  • LWW is the cheap default, CRDTs where loss is unacceptable. Overwrite data (status, config) uses LWW-registers - tiny and correct. Shared/combinable data (counters, carts, sets) uses CRDTs - a global counter hit from every region becomes a non-conflict (per-region subcounts sum), which is the single biggest win over naive timestamp LWW.
  • No global anything. No global leader, no global lock, no global clock, no synchronous quorum across regions. That absence is not a gap; it is the entire point - it is what lets any region keep serving when the rest of the planet is unreachable.

One-line summary: N symmetric regions each holding a full, locally-writable replica, committing writes to a local quorum and a durable change log, streaming them asynchronously with per-peer offsets, and converging every replica to byte-identical state through version-vector conflict detection plus deterministic LWW/HLC and lossless CRDT merges - backstopped by Merkle-tree anti-entropy - so every region stays available and fast at single-digit-ms local latency while cross-region state converges within a few hundred milliseconds, with no global coordination anywhere.