Case Study 34 โ€” Multi-Region Active-Active Database

Design a multi-region active-active database where applications in US, EU, and APAC read and write concurrently with low latency, accepting that networks partition and clocks skew. Cover conflict detection, vector clocks, CRDT basics, and when to choose last-write-wins (LWW) vs stronger guarantees.

1. Problem

A global SaaS product (notes, shopping carts, user profiles) wants:

  • Local read/write in each region (< 20 ms to app)
  • High availability โ€” region failure doesn't halt global service
  • No single-region bottleneck for writes

Traditional primary-replica replication gives one write region; failover promotes a replica but isn't active-active. True active-active means concurrent writes to the same logical object from multiple regions โ€” conflicts become inevitable.

You must define conflict resolution, consistency tiers per entity, and replication mechanics without pretending CAP doesn't apply.

2. Requirements

Functional (MVP)

  • Replicate entities: User, Document, Cart across 3 regions
  • CRUD from any region; changes propagate asynchronously
  • Conflict detection on concurrent updates to same field
  • Resolution strategies per entity type: LWW, application merge, CRDT counter
  • Read-your-writes within a region (session stickiness)
  • Admin: list conflict history; manual merge for critical entities
  • Tombstones for deletes (replicate delete, not silent resurrection)

Out of scope (initially)

  • Serializable global transactions across regions
  • Automatic semantic merge for arbitrary JSON (MVP: field-level or CRDT types)
  • Blockchain-style immutable audit
  • Full Spanner TrueTime external consistency (different design point)

Non-functional

  • Local write latency p99 < 30 ms (regional quorum or local WAL + async replicate)
  • Cross-region replication lag p99 < 5 s under normal load
  • Survive single region loss with RPO < 1 min, RTO < 5 min
  • Monotonic reads per region after write
  • Capacity: 50K regional writes/s aggregate; 500K reads/s

3. Back-of-the-envelope

These numbers are rough order-of-magnitude math โ€” not a Spanner deployment plan. In interviews, the goal is to show you know what to count and which resource breaks first. A useful shortcut: 1 QPS sustained โ‰ˆ 86,400 requests/day (86,400 seconds in a day). Active-active multi-region is write-modest globally but conflict-prone locally โ€” the surprise is concurrent edits, not raw QPS.

Why we estimate

Multi-region active-active means concurrent writes to the same logical object from different continents. Estimates tell us:

  • Whether cross-region replication bandwidth or conflict resolution is the real bottleneck
  • Which entity types can use CRDTs / LWW vs which must stay single-leader
  • How vector clocks and replication lag affect the conflict rate

Assumptions

AssumptionValueWhy it matters
Regions3 (US, EU, APAC)Each can accept local writes
Active users100MTotal user base
DAU10MUsers who write daily
Writes per DAU per day5 opsProfile edits, cart updates, doc saves
Conflict-prone writes20% of writesSame key edited in 2+ regions within 5 s
Avg record size2 KBJSON document or cart row
Total records500MUsers + documents + carts

Step A โ€” Traffic (QPS / throughput) with labeled arithmetic

Global write rate:

Writes/day        = 10M DAU ร— 5 ops = 50,000,000 writes/day
Avg write QPS     = 50M รท 86,400
                  โ‰ˆ 580 writes/second (global)

Per region (even split):
  โ‰ˆ 200 writes/second per region average

Global read rate (assume 10:1 read:write):

Avg read QPS      โ‰ˆ 580 ร— 10 โ‰ˆ 5,800 reads/second (global)
Per region        โ‰ˆ 1,900 reads/second

Conflict rate (concurrent edits โ€” the hard part):

Conflict-prone    = 20% of 580 writes/s โ‰ˆ 116 writes/s globally
  where two regions touch the same key within the replication lag window (~5 s)
  โ†’ Need resolution path: LWW, CRDT merge, or application-level merge

Step B โ€” Storage

Logical data (single copy):

Total records     = 500,000,000
Bytes per record  = 2 KB

Logical storage   = 500M ร— 2 KB โ‰ˆ 1 TB

Replicated across 3 regions:

Storage ร— 3 regions โ‰ˆ 1 TB ร— 3 โ‰ˆ 3 TB (before compression)
  Each region holds a full replica for local read latency

Vector clock overhead (negligible):

3 regions โ†’ 3 integers per write version
  โ‰ˆ 12 B per write โ€” irrelevant compared to 2 KB records

Conflict log / tombstones:

116 conflicts/s ร— 86,400 ร— 2 KB โ‰ˆ 20 GB/day conflict metadata
  โ†’ Admin merge UI + audit trail for critical entities

Step C โ€” Bandwidth / other

Cross-region replication (async):

580 writes/s ร— 2 KB ร— 2 remote copies โ‰ˆ 2.3 MB/s inter-region bandwidth
  Modest โ€” WAN bandwidth is NOT the bottleneck; conflicts and consistency are

Replication lag target:

p99 lag < 5 s under normal load
  โ†’ Conflicts happen when lag < edit frequency on same key
  โ†’ Session stickiness gives read-your-writes within a region

Regional write latency:

Target p99 < 30 ms โ†’ local WAL + async replicate (not cross-region quorum on every write)

Step D โ€” Ratios and capacity table

MetricGlobal avgPer regionNotes
Write QPS~580/s~200/sActive-active โ€” all regions write
Read QPS~5,800/s~1,900/s10:1 read:write
Conflict rate~116/s~40/s20% of writes โ€” needs resolution
Logical storage~1 TBโ€”500M ร— 2 KB records
Replicated storage~3 TB~1 TB/regionFull replica per region
Cross-region bandwidth~2.3 MB/sโ€”Modest; not the bottleneck

What the numbers tell us

  • 580 writes/s global is modest โ†’ raw QPS is not the hard problem; conflicts and consistency tiers are
  • ~116 concurrent conflicts/s โ†’ classify data: counters โ†’ CRDTs; profiles โ†’ LWW + field merge; inventory โ†’ avoid active-active
  • 3 TB replicated storage is small โ†’ this design point is about CAP trade-offs, not petabyte scale
  • 2.3 MB/s cross-region replication โ†’ WAN bandwidth is fine; 5 s lag window creates conflict surface
  • Read-your-writes via session stickiness โ†’ route user to same region after write
  • Vector clocks are cheap โ†’ use them to detect concurrency; resolution strategy is per entity type

Common mistake for this problem

Applying active-active to inventory or financial balances โ€” concurrent decrements cause overselling even with CRDTs. Interviewers want you to classify data by consistency needs: shopping cart and user profile โ†’ active-active with merge; SKU inventory โ†’ single leader per SKU or reservation + TTL. Another mistake: pretending CAP doesn't apply โ€” you must choose AP with conflict resolution or CP with a single write region.

4. High-Level Design (HLD)

Components

ComponentRole
Regional DB nodeLocal storage + apply loop; serves regional traffic
Change log (WAL)Ordered regional writes with vector metadata
ReplicatorPull/push changes cross-region; handles backpressure
Conflict resolverCompare vector clocks; invoke policy
Metadata service (CP)Region registry, shard map, feature flags โ€” etcd/Spanner lite
Session routerPin user to home region; optional sticky writes
Tombstone GCCompact deletes after retention window
Conflict audit storeRecord concurrent pairs for ops review

Flows

Local write (happy path)

  1. App writes to nearest regional DB
  2. Assign/update vector clock {US:4, EU:1, APAC:0}
  3. Append to regional WAL; ack client
  4. Async replicate to remote regions

Remote apply

  1. EU receives US change for doc:1 with vector (US:4, EU:1, APAC:0)
  2. Compare with local state (US:3, EU:2, APAC:0)
  3. Neither dominates โ†’ concurrent conflict
  4. Run resolver: e.g., field-level merge on title, CRDT-G counter for likes
  5. Increment EU component โ†’ (US:4, EU:3, APAC:0); persist; replicate back

Delete

  1. Write tombstone { deleted: true, vector, ttl }
  2. Replicate tombstone; readers treat as absent
  3. GC physical row after 30 days globally synced

Trade-offs

  • Active-active vs single-leader โ€” Active-active: lower latency, conflicts; leader: simpler, higher cross-region write RTT
  • LWW vs CRDT โ€” LWW simple but loses data; CRDT preserves intent for commutative types
  • Vector clocks vs version vectors vs HLC โ€” VC precise causality; HLC smaller but approximate
  • Sync cross-region quorum vs async โ€” Quorum = higher latency; async = conflicts + lag
  • Home region pinning โ€” Reduces conflicts; hurts traveling users

5. Low-Level Design (LLD)

APIs

PUT /v1/objects/{type}/{id}
Headers: { "X-Region": "us-east", "If-Vector": "US:3,EU:1,APAC:0" }
Body: {
  "fields": { "title": "Hello", "likes": { "type": "g-counter", "US": 5 } },
  "clientId": "device-abc"
}
โ†’ {
  "id": "doc:1",
  "vector": { "US": 4, "EU": 1, "APAC": 0 },
  "conflict": false
}

GET /v1/objects/{type}/{id}?consistent=region
โ†’ { "fields": { ... }, "vector": { ... }, "deleted": false }

GET /v1/objects/{type}/{id}/conflicts
โ†’ {
  "conflicts": [
    {
      "detectedAt": "...",
      "local": { "title": "Bonjour" },
      "remote": { "title": "Hello" },
      "resolved": { "title": "Hello" },
      "policy": "LWW"
    }
  ]
}

POST /v1/objects/{type}/{id}/resolve
Body: { "mergedFields": { "title": "Hello / Bonjour" }, "baseVector": "..." }

Internal replication message:

ChangeRecord {
  objectKey:   "doc:1",
  region:      "us-east",
  vector:      { US: 4, EU: 1, APAC: 0 },
  fields:      { ... },              // delta or full snapshot
  tombstone:   false,
  timestamp:   HLC,                  // tie-break for LWW only
  recordId:    UUID
}

Schema

Regional store (Postgres/Cockroach-style or custom):

objects (
  object_key     VARCHAR PRIMARY KEY,     -- type:id
  fields         JSONB NOT NULL,
  vector_us      INT NOT NULL,
  vector_eu      INT NOT NULL,
  vector_apac    INT NOT NULL,
  deleted        BOOLEAN DEFAULT FALSE,
  updated_at     TIMESTAMPTZ,
  hlc            VARCHAR(32)              -- hybrid logical clock string
)

change_log (
  seq            BIGSERIAL PRIMARY KEY,
  object_key     VARCHAR,
  payload        JSONB,
  vector         JSONB,
  replicated_to  BITMAP,                -- ack tracking per region
  created_at     TIMESTAMPTZ
)

conflict_audit (
  id             UUID PRIMARY KEY,
  object_key     VARCHAR,
  local_vector   JSONB,
  remote_vector  JSONB,
  local_fields   JSONB,
  remote_fields  JSONB,
  resolution     JSONB,
  policy         VARCHAR(32),
  created_at     TIMESTAMPTZ
)

CRDT embedded types (in fields JSON):

G-Counter: { "type": "g-counter", "US": 5, "EU": 3, "APAC": 1 }
           merge = per-region max

PN-Counter: { "type": "pn-counter", "p": { ... }, "n": { ... } }

LWW-Register: { "type": "lww-register", "value": "x", "ts": "...", "node": "US" }

OR-Set: { "type": "or-set", "adds": { tag: ts }, "removes": { tag: ts } }

Modules

RegionalAPI
WriteCoordinator
VectorClockService
ReplicationWorker
ChangeLogTailer
ConflictDetector
ResolutionPolicyRegistry
  LWWResolver
  FieldMergeResolver
  CRDTMergeEngine
TombstoneGC
ConflictAuditLogger
SessionAffinityRouter

Algorithm โ€” vector clock compare

function compare(vA, vB):
  // returns: DOMINATES | DOMINATED_BY | CONCURRENT | EQUAL

  aDominates = all i: vA[i] >= vB[i] and exists j: vA[j] > vB[j]
  bDominates = all i: vB[i] >= vA[i] and exists j: vB[j] > vA[j]

  if vA == vB: return EQUAL
  if aDominates: return DOMINATES
  if bDominates: return DOMINATED_BY
  return CONCURRENT

Algorithm โ€” local write with vector increment

function write(objectKey, fields, clientVector, region):
  obj = store.get(objectKey) or empty

  if clientVector provided:
    cmp = compare(clientVector, obj.vector)
    if cmp == DOMINATED_BY:
      return 409 STALE_WRITE

  newVector = increment(obj.vector, region)   // region component++

  record = ChangeRecord(objectKey, fields, newVector, hlc=nowHLC(region))
  store.applyLocal(record)
  changelog.append(record)
  replicateAsync(record)
  return 200, newVector

Algorithm โ€” apply remote change

function applyRemote(record):
  obj = store.get(record.objectKey)

  if record.tombstone and compare(record.vector, obj.vector) != DOMINATED_BY:
    // may still lose to concurrent non-tombstone โ€” resolve below
    pass

  cmp = compare(record.vector, obj.vector)

  if cmp == DOMINATES or cmp == EQUAL:
    store.replace(obj, record)
    return

  if cmp == DOMINATED_BY:
    return                                      // stale โ€” drop

  // CONCURRENT โ€” conflict
  policy = registry.getPolicy(record.objectKey.type)

  merged = policy.resolve(obj.fields, record.fields, obj.vector, record.vector)
  newVector = pointwiseMax(obj.vector, record.vector)
  newVector = increment(newVector, localRegion)

  audit.logConflict(obj, record, merged, policy.name)
  store.replace(objectKey, merged, newVector)
  changelog.append(localResolutionRecord)
  replicateAsync(resolution)

Algorithm โ€” LWW register resolution

function lwwResolve(local, remote):
  if remote.hlc > local.hlc:
    return remote
  if remote.hlc < local.hlc:
    return local
  // tie-break by region id lexicographic โ€” deterministic globally
  return maxByRegionId(local, remote)

Algorithm โ€” G-Counter CRDT merge

function mergeGCounter(a, b):
  result = {}
  for region in allRegions:
    result[region] = max(a[region] or 0, b[region] or 0)
  return { type: "g-counter", ...result }

function incrementGCounter(counter, region, delta):
  counter[region] += delta
  return counter

Algorithm โ€” OR-Set add/remove merge

function mergeORSet(a, b):
  adds = union(a.adds, b.adds)                  // tag โ†’ unique add UUID
  removes = union(a.removes, b.removes)
  visible = { t for t in adds if t not in removes
              or adds[t] > removes[t] }       // simplified; use dot clocks in prod
  return ORSet(visible)

Algorithm โ€” hybrid logical clock (HLC) for LWW tie-break

function hlcNow(localHLC, physicalNow, lastSeenRemote):
  l = { pt: physicalNow, lc: 0 }
  if physicalNow > localHLC.pt:
    l.lc = 0
  else:
    l.pt = localHLC.pt
    l.lc = localHLC.lc + 1
  if lastSeenRemote dominates l:
    l = bumpTo(lastSeenRemote)
  return l

Concurrency & correctness

  • Vector clocks detect true concurrency โ€” not wall clock alone
  • LWW loses concurrent edits โ€” acceptable for lastSeenAt, bad for balance
  • CRDTs need restricted types โ€” not every JSON field is CRDT-able
  • Tombstones prevent delete/resurrect cycles; delay GC until all regions ack
  • Read-your-writes โ€” route reads to same region; or read from local WAL tail
  • Inventory / balances โ€” use per-entity leader region or distributed lock, not blind active-active

Failure modes

FailureRiskMitigation
Region partitionSplit brain writesCP metadata; conflict on reunite; business merge
Replication backlogStale reads in remoteMonitor lag; shed load; priority tiers
LWW on financial fieldSilent data lossClassify: strong leader or CRDT PN-counter
Tombstone GC too earlyZombie recordsGC only after global ack + retention
Vector clock inflationLarge metadataPeriodic downshift if region retired
Hot key globalConflict stormShard; home region; split object

6. Scale evolution

StageChange
MVP2 regions; LWW + audit; async repl
3+ regionsVector per region; CRDT counters for metrics
High write ratePartition change log; dedicated repl workers
Stronger guaranteesSpanner/Cockroach geo-partitioning for tier-1 entities
CRDT documentsAutomerge/Yjs for collaborative fields only
ComplianceEU data residency โ€” shard users; repl filtered by jurisdiction

7. Recap

  • Active-active = conflicts are normal โ€” detect with vector clocks, don't hide them
  • Pick resolution per type โ€” CRDT for counters/sets, LWW for low-stakes fields, leader for money
  • Replicate changes, not queries โ€” regional WAL + async merge
  • Deletes need tombstones โ€” or deleted data comes back
  • CAP: you get AP across regions with eventual consistency; tighten per object when needed

Practice: two regions concurrently increment a G-Counter and edit a title field โ€” write the vector clock states before/after and show merge results; explain why LWW would lose one title change.