ealeng

Episode 47 of 55 · Multi-region

Last write wins vs CRDTs across regions: 5,397 likes confirmed, the counter said 1,799, and a merging counter kept all of them

Three regions each took likes and cart changes for the same post, with every region accepting writes, and confirmed all 5,397 likes. With last-write-wins, every region ended at 1,799: two thirds gone, and no error anywhere. A CRDT counter, which keeps one count per region and merges by taking the larger count, kept all 5,397, even with Europe cut off for 60 seconds. Then the clock: with one region's clock half a second slow, the earlier write won all 20 rounds. A shared document saved last-wins lost 508 of 984 words over five runs; a text CRDT lost none.

Lab 19 · Multi-Region and Geo-Distribution12 min read
Video transcript8:14

0:00Cold open

0:01

Three regions took likes for the same post, and confirmed every one: five thousand three hundred ninety-seven.

0:09

With last write wins, the counter ended at one thousand seven hundred ninety-nine. Two thirds gone, and nothing had failed.

0:19

A counter that merges kept all of them, even with one region cut off for a minute.

0:26

And when two regions edited one document, one way threw away one side’s work. The other kept every word.

0:34

So how do you lose likes when nothing breaks?

0:39Intro

0:41

Hands-on system design, part forty-seven.

0:44

Today: writing in every region at once, why last write wins loses data, and the data types that merge instead.

0:53Meet Lucía

0:55

I’m Lucía, a platform engineer. Last time, a write across the ocean cost a full round trip. So now every region, a data center in one part of the world, takes writes itself.

1:07

That’s called active-active: each region answers at once, and sends its copy to the others later.

1:14

Here, each region sends its copy about every half second: it waits a fifth of a second, then sends to the other two, one at a time.

1:24

The catch: two regions can change the same thing at the same time. Whose change counts?

1:31

Think of three shops selling tickets for one raffle, each with its own tally sheet. Last write wins keeps the sheet written last, and bins the others. A counter that merges keeps one column per shop, and adds the columns up.

1:4801 · What you need

1:49

To run it yourself: Docker, for a small key-value database per region, all on one laptop, with the distances added on the links between them.

2:00

Quick tests, no Docker needed, check that merging in any order gives the same answer. No cloud, nothing to pay for.

2:1002 · The test

2:11

The test: three regions, the US, Europe and Asia. Each gets twenty likes a second on one post, and twenty changes to a shopping cart, for ninety seconds.

2:23

First, last write wins. A like makes the region read its own copy, add one, and write it back, stamped with its clock. When two copies clash, the later stamp wins.

2:35

Side by side, the same likes, and a cart doing the same kind of changes, also go to CRDTs, conflict-free replicated data types: a counter and a set built to merge.

2:49

The score: every like and cart change that got a “done” should show up at the end, in every region.

2:5703 · Last write wins

2:59

Last write wins, with every link up. Five thousand three hundred ninety-seven likes confirmed.

3:06

What do you think the counter said at the end?

3:11

One thousand seven hundred ninety-nine, in every region. Two thirds of the likes, gone. And not one error anywhere.

3:20

The cart lost items the same way. All three regions agreed, on the wrong answer.

3:2804 · Why

3:29

Why? Each region writes every fifty milliseconds. A copy from each other region comes about every half second.

3:38

By the timing, a copy almost always lands after the region has written again, so it looks older and is dropped. When it does win, it replaces one region’s number with another’s. The numbers never add up.

3:53

So the counter ended at one region’s worth. Three regions at the same rate: a third. How often the same thing gets written decides this. A profile edited once a day rarely clashes.

4:0705 · A counter that merges

4:08

A counter that merges, in code. It keeps one count per region, and a region only ever adds to its own.

4:17

To merge two copies, take the larger count for each region. The value is the sum of the counts.

4:24

Here: about eighteen hundred per region, added up, five thousand three hundred ninety-seven. Taking the larger count means a repeated or late copy can’t count anything twice.

4:3806 · A set that merges

4:39

The cart is a set that merges. Every add gets a tag: a random label for that one add.

4:47

A remove deletes the tags it has seen.

4:51

Merging takes everything from both sides. Say Europe removes milk while the US adds milk again. The US add has a new tag Europe never saw, so after the merge, milk stays. The quick tests check exactly that.

5:0707 · With CRDTs

5:09

The same run, the CRDT side. The counter: five thousand three hundred ninety-seven. Not one like lost.

5:18

The cart: every item that should be there, none lost.

5:23

No removed item came back, and every region held the same values.

5:3008 · Cut off

5:31

Next, I cut Europe off from the other two for about a minute. That’s a partition. Its own clients could still reach it, and kept writing.

5:41

The CRDTs: still every like and every cart item. When Europe came back, the copies merged.

5:49

Last write wins: the very same likes lost.

5:54

The partition barely mattered. The trouble was regions writing the same thing at once.

6:0209 · Whose clock

6:03

One more weakness. Europe writes a value. A tenth of a second later, Asia writes a new one. Twenty rounds.

6:11

With one shared clock, the later write won every time.

6:16

Then I made Asia stamp its writes half a second early. That’s clock skew. Now the earlier write won every time: Asia’s stamp looked about four tenths of a second older.

6:29

So last write wins really means: the write with the latest clock wins.

6:3610 · One document

6:37

Last: a shared document, like one you edit in a browser. Two regions, Europe and the US, cut off from each other. Simulated in one program.

6:48

Each side makes two hundred edits: it inserts a new word, or deletes one it added. Then they reconnect.

6:56

Over five runs, last save wins lost five hundred eight of the nine hundred eighty-four new words: always the whole other side’s.

7:07

A CRDT built on Yjs, a text library: every one kept, both copies identical, and no deleted word came back.

7:17

Each time, they swapped about ten kilobytes, both ways together: every edit, with where it goes.

7:25Back to Lucía

7:27

So, three lessons.

7:30

Last write wins drops updates whenever writes overlap. Here, the counter kept one region’s worth, with nothing broken.

7:39

A CRDT merges instead of choosing: one count per region, added up; a set that remembers what it has seen.

7:48

And last write wins trusts the clock. A clock half a second behind made the earlier write win.

7:56

Next time: security.

7:59

For today: count per region, and add them up.Lucía: Count per region. Add them up.

8:03Summary

8:05

Overlapping writes vanish with last write wins. Merge them instead, and don’t trust the clock.

Key takeaways

  • ✓Active-active means every region accepts writes itself: with three regions each taking 20 likes a second for 90 seconds, last-write-wins confirmed 5,397 likes and ended at 1,799 in every region, so 3,598 (67%) were lost with no failure and no error.
  • ✓Last-write-wins keeps only the copy with the latest timestamp, and every region writes every 50 ms while copies arrive every 200 ms plus the link delay, so a copy almost always looks older than the region's own last write and is dropped: the counter held one region's worth, not the sum.
  • ✓A CRDT (a conflict-free replicated data type, a structure built to merge without a coordinator) counter keeps one count per region and merges by taking the larger count for each region, so the same run confirmed 5,397 likes and lost 0, in every region, including the 60 seconds Europe spent cut off.
  • ✓An observed-remove set (OR-Set) tags every add with a unique label and lets a remove delete only the tags its region has seen, so the cart held 3,235 of 3,235 expected items with the CRDT and 1,107 of 3,257 with last-write-wins.
  • ✓Clock skew decides last-write-wins: with Asia's clock set 500 ms slow, its write, made 100 ms after Europe's in real time, lost in all 20 rounds, and with the clocks in sync the later write won all 20.
  • ✓A text CRDT (Yjs, a shared-text library, here through the Python binding pycrdt) kept every one of the 984 words that should survive across five simulated document runs, with both copies identical and 0 deleted words back, while saving the whole document last-wins kept 476 and lost 508.

Three regions took likes for the same post and confirmed every one: 5,397. With last-write-wins, the counter ended at 1,799 in every region, and nothing had failed. With a counter that merges, all 5,397 survived, even with one region cut off for a minute. This chapter explains why the first design loses updates when nothing breaks, what a CRDT is and what it costs, and why last-write-wins also trusts the clocks.

The examples come from Lab 19 (Multi-Region and Geo-Distribution) of the system design labs: script 03_active_active.py for the likes, the cart and the clock, and script 04_editor.py for the shared document. The shared CRDT code is in crdt.py, and each region runs a small key-value node from region/kvnode.py. The setup is the same laptop as the earlier chapters, an Apple M4 Max with Docker Desktop and 16 virtual CPUs. The three regions are containers, with the distance between them added by Toxiproxy, a network-delay proxy. Each configuration is one recorded run, except the document test, which has five seeded runs.

Active-active: every region takes writes

The previous chapter's setup had one primary region, and a write from far away paid a full round trip. Active-active removes that wait: every region accepts writes locally, answers at once, and sends its copy to the other regions afterwards. In the lab there are three regions: the US, Europe and Asia. Each one pushes its whole state to the others every 200 ms, over links with 40 ms (US to Europe), 75 ms (US to Asia) and 90 ms (Europe to Asia) each way.

The catch is that two regions can change the same thing during the same moment. A like counter has one value, and each region is reading and adding to its own copy. Whose change counts?

Think of three shops selling tickets for one raffle, each keeping a tally sheet. Each shop adds to its own sheet. When the sheets are combined, the question is whether you keep the sheet written last and throw the others away, or add up every shop's marks. The two designs in this lab are those two answers.

Last write wins, and why the clock decides

Last-write-wins (LWW) stores one value per key, with a timestamp. A like makes the region read its copy, add one, and write the new total back with the current time on it. When two copies meet, the one with the later timestamp replaces the other.

It sounds harmless, and it is harmless when writes to the same key are rare. The lab wrote every 50 ms per region: 20 likes a second, each one a read-add-write of the whole total. Each region's own latest write was always newer than anything it had heard from the others, because the others arrived about every 200 ms plus the link delay. So a copy from another region almost always looked older, and it was dropped. When one did win, it replaced this region's total with the other region's total. The numbers never added up, so at the end each region held about one region's worth of likes: 1,799, which is 5,397 divided by three.

The same thing happened to the cart. Each cart operation was an add of a new item, or (one time in five) a removal of an item the region had added before. The cart lost 2,150 of 3,257 expected items, and all three regions agreed on the same, wrong, final cart of 1,107.

The loss is about overlap, not failure. In the lab, the partition test below changed nothing for last-write-wins, because nearly every write landed within the replication delay of another region's write. A profile that one person edits from one device once a day rarely clashes. A counter that three regions update twenty times a second clashes all the time.

CRDTs: merge instead of choose

A conflict-free replicated data type (CRDT) is a structure designed so that copies can always be merged, in any order, and end up equal. The merge function is commutative (order of arrival does not matter), associative (grouping does not matter) and idempotent (a copy applied twice changes nothing). The lab uses three of them from crdt.py:

  • G-Counter, a grow-only counter. It keeps one count per region, and each region only adds to its own count. To merge two copies, take the larger count for each region. The value is the sum of the counts.
  • PN-Counter, a counter that can go up and down. It is two G-Counters, one for increments and one for decrements. The likes only ever add, so only the increment half is used.
  • OR-Set, an observed-remove set, used for the cart. Every add gets a unique tag: a random label for that one add. A remove deletes the tags its region has seen. Merging takes everything from both sides, so a tag that one region never saw survives. Say Europe removes milk while the US adds milk again. The US add has a tag Europe never saw, so after the merge milk stays. The lab's property check covers exactly that case.

Each merge keeps every increment and every add, and a removed item stays removed unless someone adds it again. The G-Counter's merge works because the larger count per region already contains every add that region has made. A late or repeated copy can only repeat counts that are already there.

What each design loses

Both designs give up something.

  • Last-write-wins gives up correctness whenever writes overlap. It is simple, it stores one value, and it never needs the other regions' history. The price is silent loss, and it depends on the clock.
  • A CRDT keeps every increment, but its state grows. A G-Counter has one entry per region that ever wrote. An OR-Set keeps a tag for every add, and a removed item's tags stay behind as tombstones: markers that stop a deleted item from coming back on the next merge. They can only be cleared safely once every copy has seen the removal. The lab did not measure this growth for the counter or the cart. Deletes need care, as the build notes below show: a CRDT cannot be reset by clearing each node locally, because the nodes that were not cleared push their old state back.

The workload decides which cost you pay. A CRDT is the right type for things that many regions change at once: counters, carts, sets of tags. Last-write-wins is fine for values that one person changes from one place at a time.

The workflow and the results

The 03_active_active.py script ran the likes and the cart in each region, 20 operations a second for 90 seconds, once with all links up and once with Europe cut off from the other two between 20 and 80 seconds. It counted every operation that was acknowledged, then compared it with the final value in each region.

Try it · Three tally sheetsLab 19 · 03_active_active.py · recorded

Likes confirmed in three regions, one post, 90 seconds

Last write winsheld 1,799 of 5,397 confirmed

Cart: 1,107 items held, 3,257 expected

CRDT counterheld 5,397 of 5,397 confirmed

Cart: 3,235 items held, 3,235 expected

LWW likes lost
3,598
LWW cart items lost
2,150
CRDT likes lost
0
CRDT cart items lost
0

Recorded results, one run per row. All three regions agreed on the final value in every run, which is why the wrong answer went unnoticed. The bar is the share of confirmed likes each design still held.

Run Design Likes confirmed Likes at the end Likes lost Cart items expected Cart items lost All regions agree
All links up Last write wins 5,397 1,799 3,598 (67%) 3,257 2,150 (66%) yes
All links up CRDT 5,397 5,397 0 3,235 0 yes
Europe cut off 60 s Last write wins 5,397 1,799 3,598 (67%) 3,257 2,136 (66%) yes
Europe cut off 60 s CRDT 5,397 5,397 0 3,235 0 yes

The two designs had different cart totals (3,257 and 3,235) because each design ran its own random sequence of cart operations, so compare the loss rates within a design rather than the expected counts between them. Every run had 0 removed items come back.

The shared-document test, 04_editor.py, is a separate experiment described below. It used five seeded runs, each with 200 edits on each side.

Clock skew: the clock decides the winner

A last-write-wins register is only as good as its timestamps. Two regions write the same key: Europe writes first, and Asia writes 100 ms later in real time. With the clocks in sync, the later write wins. The lab ran 20 rounds, and the later write won all 20.

Then the lab set Asia's clock 500 ms slow. Asia's write is still later in real time, but its timestamp reads 400 ms earlier than Europe's. The earlier write won all 20 rounds. Last-write-wins, read honestly, means that the write with the fastest clock wins.

Try it · Whose clock winsLab 19 · 03_active_active.py · skew test

Europe writes at 0 ms. Asia writes 100 ms later, with its clock offset

-500 ms
-250 ms
0 ms
150 ms
Europe stamp 0 ms
Asia stamp 100 ms

The Asia write has the later stamp, so it wins: it was written later in real time, and its clock agreed.

Rounds: later write won
20 of 20
Rounds: earlier write won
0 of 20

The round counts are recorded (20 rounds per setting). The stamps are the lab's arithmetic: the clock offset is a setting, not a drifting clock, and the real gap is fixed at 100 ms.

The lab does not fix the clock. A hybrid logical clock, which keeps time order even with skew, is listed as an exercise, and the lab's own question is whether a 500 ms skew would still make the later write lose under it. The answer is not in the results.

Two regions, one document

The shared-document test is the same problem in text. Europe and the US each hold a 60-word document, and during a partition each side makes 200 edits: it inserts a new word at a random place, or (one in four times) deletes a word it inserted before. Then the partition heals, and the two copies are merged. The two designs are:

  • Last save wins: the whole document is one value, and the later save replaces the other.
  • A text CRDT: the document is a Yjs text structure, a shared-text library with a CRDT at its core. The Python binding is pycrdt. Each side sends only the updates the other has not seen.

The test ran in one process, with each region as its own document and the network as bytes passed between them.

Design Words that should survive Survived Lost Copies identical Deleted words back
Last save wins (five runs, combined) 984 476 508 (52%) yes, all runs 0
Text CRDT (five runs, combined) 984 984 0 yes, all runs 0

Last save wins threw away the other side's half of the work every time. The text CRDT exchanged about 9.1 to 10.4 KB per run, both ways together, which is the size of the edits and their positions.

Caveats

  • One run for the counter and cart, 20 rounds for the clock, five for the document. The counter and cart results are single recordings on one laptop, so the exact figures will move between runs. The clock result is 20 rounds per setting.
  • The regions are containers, and the distances are added delays. Toxiproxy adds a fixed delay in each direction. Real links add jitter, packet loss and bandwidth limits that the lab did not model.
  • The clock skew is a setting. Asia's clock was offset by a fixed amount in the node's configuration. The lab did not test real clock drift, nor what happens when skew varies over time.
  • The document test is a model. It runs in one process, so the network is a list of bytes passed between two documents, and the partition is a delay on that list. It shows what each merge rule keeps, not what a real editor's network does.
  • No CRDT size or memory was measured for the counters or the cart. The text CRDT's update size was measured, but the state growth of the counter and the OR-Set (one entry per region, and tombstones for removed tags) was not.
  • Deletes were the hard part of the build. In the first version, the run cleared each node's state one after another, and the nodes not yet cleared pushed their old state to the cleared ones within 200 ms. The second run's CRDT counter read 10,794 for 5,397 increments. Each run now uses fresh keys. In production, deleting from a CRDT needs tombstones or a coordinated reset, not a local delete.
  • Not covered: a partition of more than one region at a time, skew on more than one region, the bandwidth of pushing whole state every 200 ms (the lab lists delta CRDTs, which send only what changed, as an exercise), and hybrid logical clocks, which combine a wall-clock reading with a counter so that order is kept even when clocks disagree.

The checklist

  1. Decide per data type. A counter or a cart changed from many regions needs a merge rule, such as a CRDT. A value that one user changes from one place can use last-write-wins.
  2. Count the overlap, not the failures. Last-write-wins lost two thirds of the likes with every link up, because the regions wrote more often than they heard from each other.
  3. Give a counter one count per region. Merge by the larger count, and read the value as the sum. A late or repeated copy then changes nothing.
  4. Tag every set add. A remove deletes only the tags it has seen, so an add made in another region survives the merge.
  5. Do not trust the clock to order concurrent writes. A clock 500 ms slow reversed the outcome in all 20 rounds.
  6. Plan the deletes. A CRDT needs tombstones or a coordinated reset. A local delete comes back on the next merge.

Quiz

Try it · Check your understanding0 of 3 answered
  1. 1.Three regions each count about 1,800 likes and store the total as one number that each write replaces. With last-write-wins, what is the total at the end?

  2. 2.A G-Counter merges two copies by taking the larger count for each region. Why can a copy that arrives twice, or late, not add likes twice?

  3. 3.Asia's clock is 500 ms slow. Asia writes 100 ms after Europe in real time, and the register is last-write-wins. Which write wins?

Check your understanding

Try each question before opening its answer.

Three regions each count about 1,800 likes, and last-write-wins stores the total as one number. Why did the lab end at 1,799 in every region, instead of 5,397?

Each write replaced the whole total, so the copies could not add up. A copy from another region almost always looked older than the region's own latest write, so it was dropped, and when one did win it replaced the total with another region's total. The regions ended with one region's worth, 1,799 out of 5,397 confirmed, and they agreed on it.

Why does the G-Counter's merge take the larger count for each region, instead of adding the copies?

Adding would count the same likes twice whenever a copy arrived twice or was resent. Taking the larger count means each region's count only moves forward to the highest value any copy has shown, so a repeated or late copy changes nothing. Each region only ever adds to its own count, so the larger count is always the complete one.

Asia writes 100 ms after Europe, and its clock is 500 ms slow. Why does Europe's write win, even though Asia's write came later?

Asia's timestamp is its real time plus the clock offset: 100 ms minus 500 ms is minus 400 ms, while Europe's stamp is 0 ms. Last-write-wins compares the timestamps, not the real order, so the earlier write has the later stamp. The lab's 20 rounds with this setting all went to the earlier write.

Why did the cart test compare the loss rates within each design instead of the expected counts between designs?

Each design ran its own random sequence of cart operations, so the expected counts differ: 3,257 for last-write-wins and 3,235 for the CRDT. Each design's loss is measured against its own expected count: 2,150 of 3,257 (66%) for last-write-wins, and 0 of 3,235 for the CRDT.

The document test kept 476 of 984 words with last save wins and 984 with the text CRDT. Why does the CRDT keep every edit, not just the one from the side that saved last?

The text CRDT does not store the document as one value. Each insert and delete is a separate, uniquely identified change, and merging keeps every change from both sides. Both copies then end up with the same set of changes, and so the same text, and no deleted word comes back.

Next up: Chapter 48, broken authorization: this chapter decided how writes from several regions combine. The next one asks who is allowed to read or change them at all.

Learning something useful?

New labs, articles, and videos on evaluating and testing AI systems come out regularly. Follow along so you don't miss the next one.