Sub topic 7
Replicating Data Across Regions
This chapter assumes you know basic cloud networking, stateless services behind load balancers, and the difference between relational and NoSQL stores. It also assumes you have read the earlier chapters on CAP, PACELC and consistency models. Here you will see how data moves between regions, what each approach costs, and where it breaks.
Why replication is the hard part
Compute is easy to run in many regions because it holds no state. Data is different. Every region must read and write it, and the speed of light limits how fast regions can agree. A round trip between us-east-1 and eu-west-1 takes roughly 70 to 90 ms. Between the US and Asia-Pacific it can exceed 200 ms. These delays set a floor on any design that makes regions coordinate.
Replication copies a write made in one region to the others. Three questions define a design:
- When does the write count as done: before or after other regions have it?
- Which regions are allowed to accept writes?
- What happens when two regions change the same item at the same time?
This chapter covers the first two. Write ownership and conflict resolution have their own chapters, and this one points to them where they apply.
Synchronous and asynchronous replication
With synchronous replication, the writing region waits for one or more remote regions to confirm the write before it tells the client "done". With asynchronous replication, the region commits locally, answers the client, and ships the change in the background.
| Property | Synchronous | Asynchronous |
|---|---|---|
| Write latency | Local latency plus a cross-region round trip | Local latency only |
| RPO on region loss | Zero for acknowledged writes | Up to the replication lag |
| Write availability during a link failure | Writes block or fail | Writes continue |
| Conflicts | Avoided, because writes are ordered | Possible when regions write the same item |
| Typical use | Small, critical data where losing a write is unacceptable | Most active-active data |
This is the PACELC trade-off in practice. Synchronous replication buys consistency and pays in latency and availability. Asynchronous replication buys latency and availability and pays in consistency.
A middle path is quorum replication. A write succeeds when a majority of replicas acknowledge it. With three regions, one region can be down or slow and writes still succeed. You pay the latency of the second-fastest region, not the slowest. Systems based on consensus protocols such as Paxos or Raft work this way.
Replication topologies
The shape of the replication graph determines who talks to whom.
| Topology | How it works | Strength | Weakness |
|---|---|---|---|
| Single leader, read replicas | One region accepts writes. Others replicate from it. | No write conflicts | Remote writes pay a cross-region trip. Leader loss needs promotion. |
| Multi-leader | Each region accepts writes and replicates to the others. | Local writes everywhere | Conflicts must be resolved |
| Leaderless quorum | Clients write to several replicas and read from several. | Tolerates slow or failed replicas | Needs careful quorum settings and repair |
| Partitioned ownership | Each item has one home region. Others hold copies. | Local writes for most items and no conflicts | Needs a routing rule and a plan for moving ownership |
Single leader is not active-active for writes. Reads are served from every region, but writes all go to one place. Many systems that are called active-active in marketing are really this design. Check where the write path goes before you accept the label.
Multi-leader gives local writes in every region and is the usual meaning of active-active for data. Its price is conflict handling. In a full mesh, every region sends changes to every other region. This is simple but needs N times (N minus 1) links. A hub-and-spoke or ring topology uses fewer links but adds delay and makes one node a point of failure.
How changes travel
Most databases replicate by shipping a log of changes, not by copying whole tables. There are three common forms.
- Physical (block or WAL) replication ships low-level storage changes. It is fast and exact but needs identical database versions and usually supports only one writer.
- Logical replication ships row-level changes such as "row 17 now has these values". It can cross versions and filter tables. PostgreSQL logical replication and MySQL row-based binlog work this way.
- Application-level replication sends domain events through a message bus, and each region applies them. It is flexible but you own ordering and retries. The later chapters on cross-region messaging and idempotency cover this.
Managed services package these. Amazon DynamoDB global tables replicate asynchronously between regions and resolve conflicts with last-writer-wins. Aurora Global Database uses one writer region with storage-level replication to read-only secondary regions, typically with lag under a second. Aurora also offers write forwarding, where a secondary region forwards writes to the primary. Cosmos DB, Spanner and CockroachDB offer multi-region writes with different consistency options. Check each service's current documentation, because limits and features change.
Replication lag
Replication lag is the delay between a write committing in one region and becoming visible in another. Under normal load it is often tens to hundreds of milliseconds. It grows during bursts, large transactions, network congestion, or when a replica is overloaded.
Lag has three consequences you must design for:
- Stale reads. A user writes in one region and reads in another before the change arrives.
- Data loss on failover. Writes not yet replicated when a region fails are lost or stranded until the region returns. This lag is your real RPO.
- Wider conflict windows. The longer the lag, the more likely two regions change the same item before either sees the other's change.
Read-your-writes problems are common. A user updates a profile in the EU, the next request is routed to the US, and the old profile appears. Typical fixes are:
- Pin a user to a region for a session, so reads follow writes.
- Return a version token with each write and have the reader wait or retry until its local replica has caught up to that version.
- Read from the writing region for a short time after a write.
The following sketch shows the version-token idea. The replica reports the highest version it has applied. The reader accepts the read only when that version is at least the one the client saw.
import time
class Replica:
def __init__(self):
self.applied_version = 0
self.data = {}
def apply(self, version, key, value):
self.data[key] = value
self.applied_version = max(self.applied_version, version)
def read_after(replica, key, min_version, timeout=1.0, poll=0.05):
"""Return the value once the replica has reached min_version.
Raise TimeoutError so the caller can fall back to the writing region."""
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
if replica.applied_version >= min_version:
return replica.data.get(key)
time.sleep(poll)
raise TimeoutError("replica too far behind")
eu = Replica()
eu.apply(1, "name", "Ada")
print(read_after(eu, "name", min_version=1)) # Ada
try:
read_after(eu, "name", min_version=2, timeout=0.2)
except TimeoutError as e:
print("fallback:", e) # fallback: replica too far behindThis sketch assumes versions apply in order. Real systems must handle gaps, which is why many use a per-partition log position instead of a single counter.
Ordering and causality
Asynchronous replication can deliver changes in a different order than they happened. Suppose a user creates a comment and then deletes it. If a region sees the delete first, it has nothing to delete, and then the create arrives and the comment reappears.
Three tools address this:
- Per-key ordering. Send all changes for one key through one ordered stream. Most log-based systems do this per partition.
- Version vectors or logical clocks. These record which changes each region had seen, so a region can tell "this change came after that one" from "these two were concurrent".
- Tombstones. Keep a marker for deleted items so a late create does not resurrect them. Remove tombstones only after every region has had time to see them.
The next chapters cover conflict resolution in detail. For now, remember that replication without an ordering rule can produce results that no single region ever intended.
Common errors
- Treating lag as constant. Alert on lag as a distribution, and watch the maximum, not the average.
- Counting on replicated writes during failover. Plan for the last few seconds of writes to be missing, and decide how to reconcile them when the failed region returns.
- Replicating everything the same way. A shopping cart, an audit log, and a payment ledger need different guarantees. Choose per data set.
- Ignoring schema changes. A migration that reaches regions at different times can break replication. Make changes backward compatible and roll them out in stages.
- Replicating secrets and personal data without a review. Some data cannot leave its home region. A later chapter covers residency.
- Unbounded replication backlog. If a region is down for hours, the queue of changes grows. Know how your system catches up, and whether it needs a full resync.
Choosing an approach
Use these questions in order.
- Can any data loss be tolerated on region failure? If not, use synchronous or quorum replication for that data and accept the latency.
- Do users need to write from anywhere with low latency? If yes, use multi-leader or partitioned ownership.
- Can you assign each item a home region? If yes, prefer partitioned ownership, because it removes most conflicts.
- Must two regions update the same item concurrently? If yes, pick a merge rule such as last-writer-wins or a CRDT.
- Is a single writer acceptable? If so, single leader is the simplest and cheapest design.
Exercise
Your service uses asynchronous multi-leader replication between us-east-1 and eu-west-1. Typical replication lag is 200 ms. us-east-1 fails, and its last 3 seconds of writes had a lag spike and were not replicated. What is the effective RPO for this event, and name two ways to reduce a user-visible effect of the lag during normal operation?
Show answer
The effective RPO is the unreplicated window, here about 3 seconds of writes, not the typical 200 ms. The typical lag is only an average. The spike is what determines loss. To reduce visible effects of lag, pin a user to one region per session so reads follow writes, or return a version token with each write and have the reader wait until its local replica reaches that version. Reading from the writing region briefly after a write also works.
Exercise
A team says their database is active-active because every region has a read replica of a database in us-east-1. What question tells you whether this is true, and what is the answer in this case?
Show answer
Ask which regions accept writes. Here only us-east-1 does, so this is single leader with remote read replicas. Reads are served locally, but writes from other regions cross the network to us-east-1, and a us-east-1 outage stops all writes until a replica is promoted.