Replication across regions and write conflicts
A copy that is behind
Section titled “A copy that is behind”A second region is only useful if it has the data. The replication module showed the two ways to copy it. With asynchronous replication the first region confirms a write and copies it afterwards, so the copy trails by the replication lag. With synchronous replication it confirms only once the copy exists. Across regions the distance makes the choice sharper, because the wait for a copy is no longer a millisecond in the same building: it is a round trip across a continent.
Whatever the lag is, it is also an answer to a question that operators ask about a failure: how much recent data can we lose? That is the recovery point objective, the RPO. AWS says it in these terms for DynamoDB’s default mode for global tables: changes are replicated to the other regions asynchronously, typically within a second or less, and the RPO equals the replication delay between the replicas. Its other mode copies each change to at least one other region before confirming a write, has an RPO of zero, and has higher write latency because the confirmation needs cross-region communication.
Try it: the copy that was not made
Section titled “Try it: the copy that was not made”The lab starts with asynchronous copying and a Replication lag of 2 s, and 10% of requests write, which at the peak of 1,200 requests a second is 120 writes a second. The last column of the table of regions, Writes not yet copied out, says how many writes each region has accepted and not yet sent: 96 in North America, 84 in Europe and 60 in Asia-Pacific. For North America it is 480 × 0.10 × 2, its requests a second times the share that write times the lag.
Users in North America, Europe and Asia-Pacific reach a service that runs in one, two or three regions. Choose active-passive or active-active, fail a region, and see where its users go, whether the regions left can hold them, how long the switch takes, and what data was not yet copied out. The numbers come from a model with illustrative inputs.
Regions: latency, failover and data at risk
Every number here is model output. The round-trip times, the traffic from each continent and the lag are illustrative inputs, not measurements of any provider.
A write is confirmed first and copied afterwards, so the copy trails by the lag.
- Mean round trip, user to region
- 20 msWith one region: 76 ms
- Each region must carry
- 900 req/s75% of the peak; each region can serve 800 req/s
- Average time to serve again
- —Fail a region to see it
- Data at risk (RPO)
- 2 s of writesThe latest writes, if their region fails
- With 3 regions, users are on average 20 ms from the region that serves them, and the worst-placed group 20 ms. With a single region (the best placed: North America) it would be 76 ms on average and 160 ms for the worst group.
- A region has 8 servers and can serve 800 requests a second. If one region is lost, the busiest region left would have to carry 900 requests a second, 75% of the 1,200 peak.
- Spread evenly, 3 regions need each at least 1/2 of the peak, 50%, which is 600 requests a second. At that size each region runs at 67% in normal times.
- Not big enough: if the wrong region is lost, up to 100 requests a second would not fit and would be refused.
- Replication is asynchronous with a lag of 2 s: the latest 2 s of writes exist only in the region that accepted them.
- Two regions accept writes, so two users can change the same record before either region has heard of the other's change: that is a write conflict.
| User group | Share of requests | Served by | Round trip | One region (North America) |
|---|---|---|---|---|
| Users in North America | 40% | North America | 20 ms | 20 ms |
| Users in Europe | 35% | Europe | 20 ms | 80 ms |
| Users in Asia-Pacific | 25% | Asia-Pacific | 20 ms | 160 ms |
| Mean over all users | 20 ms | 76 ms |
| Region | Load before | Load after | Capacity | Utilisation | State | Writes not yet copied out |
|---|---|---|---|---|---|---|
| North America | 480 req/s | 480 req/s | 800 req/s | 60% | Busy | 96 |
| Europe | 420 req/s | 420 req/s | 800 req/s | 53% | Busy | 84 |
| Asia-Pacific | 300 req/s | 300 req/s | 800 req/s | 38% | Healthy | 60 |
| Region lost | Busiest region left | Utilisation | Does not fit | State |
|---|---|---|---|---|
| North America | 900 req/s | 113% | 100 req/s | Overloaded |
| Europe | 900 req/s | 113% | 100 req/s | Overloaded |
| Asia-Pacific | 780 req/s | 98% | 0 | Saturated |
Users go to the nearest region that is left (active-passive: to the standby). Spread perfectly evenly, the load on each region left would be the peak divided by N − 1, where N is the number of regions. Nearest-region routing is rarely even, so the busiest region carries more.
| Record | Before | Written in North America | Written in Europe | Last-write-wins keeps | A merge keeps |
|---|---|---|---|---|---|
| Customer's first name | Ana | Anne | Anna | Anna · loses the write from North America | Anne / Anna · both versions, for a person to choose |
| Likes counter | 10 | 11 | 11 | 11 · loses the write from North America | 12 · both increments |
| Shopping cart | (empty) | book | lamp | lamp · loses the write from North America | book, lamp · both items |
Last-write-wins compares timestamps taken from each region's clock. If the second region's clock is behind, its later write can look older and lose. A merge rule, such as a conflict-free replicated data type (CRDT), combines the writes instead of dropping one. It suits a counter or a set; for a field like a name nobody can say which value is right, so the versions are kept for a person to choose.
Illustrative values, not benchmarks of any real product.
Model notes
Assumptions
- Users are in three places and send a fixed share of the requests: 40% from North America, 35% from Europe and 25% from Asia-Pacific. Two regions are in North America and Europe; the third is in Asia-Pacific. Every round-trip time in the lab (20 ms to the region on the same continent, 80 to 200 ms between continents) is an illustrative input, not a measurement.
- Every region has the same servers, and each server can serve 100 requests a second. A region is overloaded when it carries more than it can serve. The lab does not model the slowdown that comes before that.
- A health check runs on a fixed interval, and traffic is moved after the chosen number of failed checks in a row. The time shown is the longest this takes. A resolver keeps the answer it was given for up to the TTL, so the time left on a cached answer is spread evenly between zero and the TTL.
- Replication is to one other region. Asynchronous: a write is confirmed before it is copied, and the copy trails by the lag you set. Synchronous: a write waits for the nearest other region to confirm.
Simplifications
- Round-trip time stands in for latency. It leaves out the time a server needs, the number of round trips a request makes (name lookup, connection, TLS, the request itself), and congestion.
- Users go to the region with the lowest round trip in the table. Geographic DNS, anycast or a global load balancer decide by the network and not by the map, and may differ.
- After a failure every request to the failed region fails until its client has moved. There are no retries, and every client honours the TTL. Some resolvers and clients keep an answer longer than the TTL, and the model does not.
- The standby in active-passive mode is idle until it is told to take over. It then needs the promotion time you set and serves at once at full capacity. A cold standby that must also start servers takes longer, and is not modelled.
- The lab loses a whole region. A part of a region (one zone, one service) fails more often and in other ways, and a region can be reachable and still too slow.
- Data at risk is the writes a second that the failed region was accepting, times the lag. The writes that were not copied are stranded in the failed region, not necessarily destroyed: they come back if the region does. A real lag moves around and grows under load.
- The write conflicts are three illustrative records, written in two regions 0.2 seconds apart, before either write reaches the other region. How often real conflicts happen depends on the data, which the model does not have.
- Synchronous replication is modelled as a wait for the nearest other region. Protocols that agree on every write between regions (consensus) cost more round trips and are not modelled, nor is what happens to a write when the other region cannot be reached: it waits, or it is refused.
Parameter values are illustrative. They are not benchmarks of any real product.
Under Fail a region, choose North America. Data at risk (RPO) reads 2 s of writes, and below it the lab says: about 96 writes not yet copied out. They are not necessarily destroyed. They are in the region that failed, out of reach until it returns, and gone if its storage is lost, as the lesson on failover and lost writes showed for a primary. Now drag Replication lag to 10 s and Share of requests that write to 50%. The figure is 480 × 0.50 × 10, which is 2,400 writes. The lag and the write rate multiply.
Switch Copying data to another region to Synchronous. Data at risk (RPO) reads None: no write that was confirmed can be missing from another region. The price is shown under it: every write waits an extra 100 ms. A write is confirmed when the nearest other region has it, which is 80 ms away for North America and Europe, and 160 ms for Asia-Pacific. The average over the writes, weighted by where they come from, is (480 × 80 + 420 × 80 + 300 × 160) / 1200, which is 100 ms. Choose 2 regions and it falls to 80 ms, since the nearest other region is always the same one.
That is the PACELC trade-off from the lesson on CAP, drawn with distances: even when nothing is broken, a copy that is certain costs the round trip, and a copy that is fast may be behind. The lab models a wait for the nearest other region. Protocols that agree on every write between regions, such as the consensus of the coordination module, cost more round trips than that, and the lab does not model them.
Two regions, one record
Section titled “Two regions, one record”Replication is simple when only one region writes. With Active-passive, the lab says so: only the primary accepts writes, so writes cannot conflict. With Active-active, two users can change the same record in two regions before either region has heard of the other’s change. Neither is wrong when it acts. The conflict only appears when the changes meet.
The table at the bottom of the lab, with Active-active selected, writes three records in North America and in Europe 0.2 seconds apart, before either write has crossed the ocean. The column Last-write-wins keeps shows what a system that keeps the newest write ends with.
- Customer’s first name: it was Ana, and the two regions wrote Anne and Anna. Last-write-wins keeps Anna, and says it loses the write from North America.
- Likes counter: it was 10. Both regions read 10 and wrote 11, for one like each. Last-write-wins keeps 11. One like has vanished, and nothing reports it.
- Shopping cart: it was empty, and the regions added a book and a lamp. Last-write-wins keeps the lamp.
DynamoDB’s global tables use this rule by default: when the same item is modified in several regions at once, the modification with the latest internal timestamp wins on a per-item basis. The CRDT paper says what the rule costs in one sentence: last-write-wins ensures a total order of operations, at the cost of losing concurrent updates.
What happens if a clock runs behind?
Section titled “What happens if a clock runs behind?”The rule compares timestamps, and each region stamps with its own clock. The lesson on physical clocks showed what a skew does to the order of events. Here it decides which write survives. Set Clock behind in the second region to 0.5 s. The gap between the two writes is 0.2 s, so Europe’s write now carries an earlier timestamp than North America’s, although it happened later. The first name is Anne, the cart holds the book, and the counter still says 11. The write that lost is the other one. Nothing was repaired: a different write was dropped.
The rule is silent. Neither writer is told that a write was discarded, and the result looks like a valid value.
Merging instead of choosing
Section titled “Merging instead of choosing”If dropping a write is not acceptable, the alternative is to give the system a rule that combines the writes. The column A merge keeps shows the outcome of such a rule: for the counter, 12, both likes; for the cart, the book and the lamp; for the name, both versions, for a person to choose, because no rule can tell which spelling is right.
A conflict-free replicated data type, a CRDT, is a data type designed so that any two replicas can be merged by a rule that gives the same result in any order. The paper by Shapiro and his colleagues defines strong eventual consistency as the property that replicas that have received the same updates are in the same state, and builds its types on mathematical properties that guarantee it. The simplest one is the counter. Each replica keeps a slot of its own and increments only that slot; a merge takes the larger value of each slot; the value of the counter is the sum of the slots. Merging is the same in any order and gives the same result when repeated, so replicas can exchange their states whenever they like.
// Two regions accept a write to the same record before either has heard of the other's. Last-write-wins keeps one of the// two writes, and which one depends on two clocks. A G-counter (a conflict-free replicated data type) keeps both.using ShardCraft.Playground;
// --- Last-write-wins: the register keeps the value with the larger timestamp. -----------------------------------------var truth = new FakeClock();var regionA = truth.UtcNow; // region A's clock is rightConsole.WriteLine("last-write-wins, both clocks right");Register a1 = new("Anne", regionA); // A writes at t = 0.0 sRegister b1 = new("Anna", regionA + TimeSpan.FromSeconds(0.2)); // B writes at t = 0.2 s, B's clock says 0.2 sConsole.WriteLine($" A holds {a1.Value}, B holds {b1.Value}, after the exchange both hold {Register.Merge(a1, b1).Value}");
Console.WriteLine("last-write-wins, B's clock 0.5 s behind");Register b2 = new("Anna", regionA + TimeSpan.FromSeconds(0.2 - 0.5)); // the same write, stamped by a slow clockConsole.WriteLine($" A holds {a1.Value}, B holds {b2.Value}, after the exchange both hold {Register.Merge(a1, b2).Value}");
// --- A G-counter: each region increments its own slot, and a merge takes the larger value of each slot. ---------------Console.WriteLine("counter, both regions read 10 and add 1");var copyA = new Register("11", regionA);var copyB = new Register("11", regionA + TimeSpan.FromSeconds(0.2));Console.WriteLine($" last-write-wins keeps {Register.Merge(copyA, copyB).Value}");
var counterA = new GCounter(["base", "A", "B"]).Add("base", 10).Increment("A");var counterB = new GCounter(["base", "A", "B"]).Add("base", 10).Increment("B");Console.WriteLine($" G-counter: A holds {counterA.Value}, B holds {counterB.Value}, after the exchange both hold {GCounter.Merge(counterA, counterB).Value}");Console.WriteLine($" merging again, or in the other order, changes nothing: {GCounter.Merge(counterB, GCounter.Merge(counterA, counterB)).Value}");
record Register(string Value, DateTimeOffset Stamp){ // The later timestamp wins. The other write is dropped, and nobody is told. public static Register Merge(Register x, Register y) => y.Stamp > x.Stamp ? y : x;}
sealed class GCounter{ private readonly Dictionary<string, int> _slots;
public GCounter(IEnumerable<string> replicas) => _slots = replicas.ToDictionary(r => r, _ => 0);
private GCounter(Dictionary<string, int> slots) => _slots = slots;
public int Value => _slots.Values.Sum();
public GCounter Add(string replica, int amount) { var next = new Dictionary<string, int>(_slots); next[replica] += amount; return new GCounter(next); }
public GCounter Increment(string replica) => Add(replica, 1);
// Per slot, the larger value: commutative, associative and idempotent, so the order and the repeats do not matter. public static GCounter Merge(GCounter x, GCounter y) => new(x._slots.ToDictionary(slot => slot.Key, slot => Math.Max(slot.Value, y._slots[slot.Key])));}last-write-wins, both clocks right A holds Anne, B holds Anna, after the exchange both hold Annalast-write-wins, B's clock 0.5 s behind A holds Anne, B holds Anna, after the exchange both hold Annecounter, both regions read 10 and add 1 last-write-wins keeps 11 G-counter: A holds 11, B holds 11, after the exchange both hold 12 merging again, or in the other order, changes nothing: 12This is the exact code that produced this output, run with the .NET SDK when the site was built. Nothing runs in your browser.
The output shows the whole lesson in eight lines. With both clocks right, last-write-wins keeps Anna. With a clock 0.5 s behind, the same two writes leave Anne. For the counter, last-write-wins ends at 11, and the G-counter ends at 12, where A has recorded one like and B has recorded one.
CRDTs have limits. A merge rule exists for counters and sets, which are the examples in the paper, and not for every kind of data: a field like a name has no rule that makes the right choice, and the lab says so. A CRDT also guarantees that replicas converge, not that every business rule holds. Two regions that both add the last item to stock still agree on the count, and still sold it twice.
Write conflicts: last-write-wins against a merge
This quiz needs JavaScript to check your answers.
A likes counter reads 20 in two regions. Region A adds 2 likes and writes 22. Region B, 0.2 seconds later, adds 3 likes and writes 23. Both writes happen before either region hears of the other. The regions use last-write-wins and both clocks are right.
What does the counter hold once the regions have exchanged their writes?
Enter a number and choose its unit.
The same two writes, but the counter is a G-counter. Each region keeps its own slot, and a merge takes the larger value of each slot. Both regions start from a shared base of 20.
What is the value of the counter after the merge?
Enter a number and choose its unit.
Two regions write the same record 0.2 seconds apart, and the later write is made in region B. Region B’s clock runs 0.5 seconds behind region A’s. The regions use last-write-wins on timestamps.
Which write survives?
Choose one answer.
Three ways out
Section titled “Three ways out”AWS’s disaster-recovery whitepaper names three strategies for writes in an active-active design.
- Write global. Every write goes to one region, and the others serve reads from their copy. If the region fails, another is promoted. Aurora global database fits: one primary region accepts writes and the secondaries replicate from it, typically with a latency under a second. Writes from far away pay the round trip to the primary.
- Write local. Every region takes writes for its own users, and conflicts are resolved afterwards. DynamoDB global tables do this, with last writer wins.
- Write partitioned. Each record is assigned a home region, by a key such as the user’s id, and only that region writes it. Conflicts cannot happen, because no record has two writers. A user who travels is served from the home region of their data, which can be far away.
The first and third avoid the problem, and the second accepts it and chooses a rule. The right choice depends on what a lost write is worth, which is a question about the data and not about the infrastructure.
- The lag between regions is the data at risk, the RPO. At 10% writes and a 2 s lag, North America holds 96 writes that no other region has:
480 × 0.10 × 2. At 10 s and 50% it is 2,400. - Synchronous replication brings the risk to none and adds the wait for the nearest other region: 100 ms on average with three regions, 80 ms with two.
- Active-passive has one writer, so writes cannot conflict. Active-active can have two writers on one record.
- Last-write-wins keeps the newest timestamp and loses the other write without notice. A clock 0.5 s behind makes the older write look newer. The counter ends at 11 and a merge gives 12.
- A CRDT merges so that no write is lost, for types with a merge rule such as counters and sets. Otherwise choose write global, write local or write partitioned.
Next: global traffic routing, how users reach the right region and how that changes when one is lost.
Your progress
Built by GhaziAlibi.
© ShardCraft. All rights reserved.