ealeng

Episode 31 of 55 · Distributed transactions

Event sourcing and CQRS: read, add one, write back lost 55% of cart items, and a version check lost none

Twenty writers added items to fifty shopping carts at once, with a 5 ms pause between reading a cart and writing it back. Read-add-one-write-back kept 9,032 of 20,000 additions and lost 10,968, with no error. An event store that appended each addition at the version it had read lost none, at the cost of 384 retries and about twice the time. The same lab rebuilt a read model from a million events in 3.1 s, or 1.1 s from snapshots, showed that a CQRS read model was 7 ms behind and missed 99.8% of reads right after a write, and found that only two of ten Avro schema changes were compatible in both directions.

Lab 13 · Distributed Transactions and Event Patterns13 min read
Video transcript9:33

0:00Cold open

0:01

Twenty writers added items to the same fifty shopping carts, all at once, with a short pause to widen the race. Twenty writers, twenty items each: every cart should have ended with four hundred.

0:14

With the usual code, read the cart, add one, write it back, the carts ended with between a hundred seventy-two and a hundred eighty-seven. More than half the additions vanished, and nothing reported a failure.

0:29

The same test on an event store: four hundred in every cart.

0:35

So what is an event store, what does it cost, and do you even need one?

0:41Intro

0:43

Hands-on system design, part thirty-one.

0:46

Today: storing what happened instead of what is.

0:50Meet Lucía

0:52

I’m Lucía, a platform engineer.

0:55

Usually a database keeps the current state of an order. With event sourcing, it keeps every event that happened to it, in order: created, item added, item added, item removed, submitted. The table that holds them is the event store. An order’s version is how many events it has, like a line number on a statement.

1:16

The current state is worked out by going through the events: here, submitted, with one item.

1:23

Think of a bank account. Each event is one line on the statement. The state is the balance: you get it by adding up the lines. That adding up is called a fold.

1:3501 · What you need

1:37

To run it yourself: Docker for Postgres, Kafka, and a schema registry, which we’ll meet later. The quick tests run in a couple of seconds, without Docker.

1:48

No cloud, and nothing to pay for.

1:5302 · The fold, in code

1:54

Here is the fold.

1:57

Start from an empty order, and apply each event, one at a time.

2:03

An item added adds its quantity to the item count.

2:08

But events live forever, and the format changes. The old format of “item added” had no quantity at all. So an upcaster translates old events as they’re read: no quantity means one.

2:2203 · A million events

2:24

Can you really rebuild everything from events? I generated a million synthetic events: a hundred thousand orders, ten events each. Half of the item events in the old format.

2:37

Replaying all of them, in one Python process: three point one seconds. About three hundred thirty thousand events a second.

2:47

Faster: a snapshot, a balance carried forward. Save each order’s state at version eight, its eighth event, and replay only what came after: two events per order, two hundred thousand in all. One point one seconds, with exactly the same result: the same checksum, a fingerprint of all hundred thousand orders.

3:08

Taking the hundred thousand snapshots cost two point three seconds, once. So the first rebuild with them takes three point four seconds, no faster than three point one. From the second rebuild on, each takes one point one instead of three point one.

3:2604 · A model for reading

3:27

Reading by replaying is fine for one order. For a page that lists thousands, you keep a separate table shaped for reading: the read model. A projector updates it from the events. Writing and reading through different models is called command query responsibility segregation, or CQRS. A command is a request to change something.

3:50

Two hundred commands a second, for thirty seconds. The projector applied all six thousand and two events. Half reached the read model within seven milliseconds, and ninety-nine in a hundred within fourteen. Most likely: the relay checks for new events every ten milliseconds, plus one Kafka hop.

4:11

After each command, the client read the read model right away. How often did it see its own change?

4:19

Fourteen times out of six thousand and two. Ninety-nine point eight percent of those reads missed it. The command took about a millisecond, and the read model was about seven behind.

4:32

Seven milliseconds is still enough to break “I just added it, why isn’t it in my cart?”. The simplest fix, as in part sixteen: read your own changes from the event store.

4:4505 · Twenty writers

4:47

Now the cold open’s test. Twenty writers each add twenty items to each of fifty carts, at once. I added a five millisecond pause between reading and writing, to make the race easy to hit.

5:01

Read, add one, write back: a hundred seventy-two to a hundred eighty-seven per cart. Ten thousand nine hundred sixty-eight of twenty thousand additions lost: fifty-five percent. Two writers read forty-one, both write forty-two, and one addition is gone.

5:19

The event store: four hundred in all fifty carts. Three hundred eighty-four times, a writer was told someone got there first, and tried again.

5:30

The price: thirteen point eight seconds, against seven point two. Retries were only three hundred eighty-four of twenty thousand. Not measured, but each add makes more database round trips: two reads, then the event and its outbox row in one transaction.

5:4906 · The version check

5:50

Here are both. The usual way: read the cart’s items, then write back the number you worked out. Nothing checks that the cart didn’t change in between. Two tellers both overwrite the balance with forty-two.

6:04

The event store appends the new event at the version it read, plus one. And the table allows each version of an order only once: its primary key is the order and the version. Only one teller can write line forty-two.

6:20

So if someone else already wrote that version, the database refuses, the service answers “conflict”, and the writer reloads and tries again. That’s called optimistic concurrency: assume no one else writes, and check only at the end.

6:36

To be fair, a plain “set items to items plus one” in the database should also be correct here, though I didn’t test it. The lesson is narrower: never write a value you worked out from a read that may be stale.

6:5107 · Changing the format

6:52

Events other teams read from Kafka often use Avro, a format where each event is written with a schema: its fields and their types. Old events stay for years, so changes need checking. I tested an order-placed event: an order id, a product, a quantity.

7:11

Three questions. Backward: can new code read old events? Forward: can old code read new events? Full: both.

7:20

Ten changes, three judges: a schema registry, the service that stores schemas and checks each new one; forty lines of my own rules; and actually reading the data. Thirty answers, all the same. Only two changes were safe both ways: adding a field with a default, the value a reader fills in when it’s missing, and removing one that had a default.

7:43

A rename breaks both ways. Keeping the old name as an alias fixes it one way only: new code reads old events, old code can’t read the new name.

7:5608 · The registry says no

7:57

The registry stores each kind of event’s schemas under a name, a subject. Ours was left at backward, the default. First schema: accepted. Adding a coupon with a default: accepted.

8:11

Then renaming qty to quantity: refused, with HTTP four-oh-nine. New code looks for quantity, old events only have qty, and quantity has no default. The new schema never got an id, so a producer that registers schemas before sending can’t use it.

8:31

But backward only protects new code reading old events. It would have allowed removing a field without a default, which breaks old consumers. When consumers upgrade on their own schedule, set it to full.

8:46Back to Lucía

8:47

So, three lessons.

8:50

Never write a value you worked out from a read that may be stale. A version check turns a silent loss into a retry.

8:59

A read model is usually a little behind. Read your own writes from the write side.

9:05

And only add or remove fields that have a default. Let the registry refuse the rest.

9:13

Next time: counting an endless stream of events, and getting the same answer a batch job would.

9:20

For today: keep the statement.Lucía: Keep the statement.

9:23Summary

9:25

Check the version, read your own writes, and change schemas only with defaults.

Key takeaways

  • ✓Read, add one, write back lost 10,968 of 20,000 additions (55%): with 20 writers adding to the same 50 carts and a 5 ms pause between read and write, every cart ended between 172 and 187 items instead of 400, and nothing reported a failure.
  • ✓An event store keeps what happened, not what is: an order is a list of events (created, item added, item added, item removed, submitted), and its current state is a fold, which applies the events in order, so that list folds to submitted with one item.
  • ✓Rebuilding is a replay: 1,000,000 synthetic events (100,000 orders of 10 events each) were folded into the read model in 3.06 s in one Python process, about 330,000 events a second, and the old-format ItemAdded events were translated on read.
  • ✓Snapshots save a state at version 8 so a rebuild reads 2 events per order instead of 10: 200,000 events in 1.06 s, with the same checksum as the full replay. For one order with 10,000 events, loading took 25.7 ms at the median without a snapshot and 4.1 ms with one.
  • ✓The CQRS read model, the separate table built from events for reading, was 7 ms behind at the median and 14 ms at the 99th percentile; a client that read its own write right after making it saw the old state in 5,988 of 6,002 reads (99.8%).
  • ✓Optimistic concurrency, which assumes no one else wrote and checks at the end, turned the same 20-writer race into 384 refused appends and retries, with 0 additions lost, in 13.8 s against 7.2 s for read-modify-write.
  • ✓Of ten changes to an Avro event schema (a binary format where each event is written with its field list), only adding a field with a default and removing a field that had a default were compatible both ways; renaming qty to quantity was refused by the schema registry with HTTP 409 at its default level, BACKWARD.

Twenty writers added items to the same fifty carts at once, and the usual code kept 9,032 of the 20,000 additions. The other 10,968 vanished, and no request reported a failure. An event store that appended each addition as a new event, at the version the writer had read plus one, kept all 20,000. This chapter explains why the first design loses updates, what storing events instead of state changes, how a read model is built from them, and how the same event log has to survive schema changes.

The examples come from Lab 13 (Distributed Transactions and Event Patterns) of the system design labs. Two scripts produced the numbers: 04_event_sourcing.py (the rebuilds, snapshots, the read model's lag, and the 20-writer race) and 05_schema_evolution.py (ten schema changes checked three ways). Both ran on the earlier chapters' laptop, an Apple M4 Max with Docker Desktop, with Postgres 17, Kafka 4.1.1, the Confluent Schema Registry 8.1.0 and Python 3.14. Each figure is one recorded run, and the lab's results files are the source. The lab's two-phase commit part is covered in chapter 29.

Why read, add one, write back loses updates

The usual way to add an item to a cart is three steps: read the row, change the number in the application, write the number back. Nothing in that sequence checks whether the row changed in between. Two requests that read the same value both write their result, and one of the two additions disappears.

Take the simplest case. A cart holds 41 items. Writer A reads 41, and so does writer B. Each adds one. Both write 42. The cart shows 42, two additions were made, and one is gone. The database did nothing wrong, and neither request failed.

The lab ran the worst version of this on purpose. Twenty writers each added twenty items to each of fifty carts, all at once, with a 5 ms pause between reading a cart and writing it back, so the race was easy to hit. Every cart should have ended with 400 items. Read-modify-write left each one between 172 and 187: 10,968 of 20,000 additions lost, 55%. It took 7.2 seconds.

The fix in the lab is not a lock. It is an append that says which version it is based on. Compare the two in the widget below.

Try it · Twenty writers, fifty cartsrecorded run, 5 ms between read and write
400 wantedcart 1: 175 itemscart 2: 177 itemscart 3: 181 itemscart 4: 174 itemscart 5: 172 itemscart 6: 172 itemscart 7: 174 itemscart 8: 178 itemscart 9: 187 itemscart 10: 183 itemscart 11: 187 itemscart 12: 175 itemscart 13: 185 itemscart 14: 182 itemscart 15: 181 itemscart 16: 183 itemscart 17: 185 itemscart 18: 173 itemscart 19: 186 itemscart 20: 183 itemscart 21: 181 itemscart 22: 182 itemscart 23: 174 itemscart 24: 183 itemscart 25: 184 itemscart 26: 184 itemscart 27: 182 itemscart 28: 176 itemscart 29: 183 itemscart 30: 187 itemscart 31: 183 itemscart 32: 176 itemscart 33: 185 itemscart 34: 180 itemscart 35: 173 itemscart 36: 183 itemscart 37: 183 itemscart 38: 178 itemscart 39: 181 itemscart 40: 186 itemscart 41: 187 itemscart 42: 178 itemscart 43: 182 itemscart 44: 179 itemscart 45: 181 itemscart 46: 183 itemscart 47: 185 itemscart 48: 174 itemscart 49: 183 itemscart 50: 183 items
Each cart ended with
172–187
Additions lost
10,968 of 20,000
Seconds
7.2
Conflicts retried
not counted

Two writers read 41, both wrote 42, and one addition vanished. No request reported an error.

Store what happened, not what is

With event sourcing, the database does not keep an order's current state. It keeps every event that happened to the order, in order: created, item added, item added, item removed, submitted. The table that holds them is the event store. An order's version is how many events it has so far, like a line number on a statement.

The current state is computed by a fold: start from an empty order, apply each event in turn, and keep the result. A bank statement works the same way. Each event is one line, and the balance is what you get by adding the lines up. The fold for the five events above ends at submitted, with one item: two items were added, one was removed.

Events live forever, though, and their format changes. The lab's old format for "item added" had no quantity field at all. An upcaster is the function that translates an old event into the current format as it is read, so the fold never sees the old shape. Here, an old ItemAdded with no quantity counts as a quantity of one.

Try it · The fold, as a statementillustrative order from the lesson, not lab data

Events, in order (version = line number)

  1. 1Createdorder opened
  2. 2ItemAddedone item added+1
  3. 3ItemAddedone item added+1
  4. 4ItemRemovedone item removed-1
  5. 5Submittedorder submitted
Balance (items)
1
Status
submitted

The current state is never stored here. It is recomputed by folding the events from the first line, the way a bank balance is the sum of its statement lines.

Rebuilding from events

Can you really rebuild everything from the events? The lab generated a million synthetic events: 100,000 orders, ten events each, with half of the item events written in the old format. Folding all of them into the read model, in one Python process, took 3.06 seconds. That is about 330,000 events a second. Because the events are the record, the read model can be thrown away and built again whenever its shape changes.

Replaying everything is slow for long histories, so the lab also took a snapshot: the state of each order at version 8, saved in its own table. A rebuild from snapshots then reads only the events after version 8, which is 2 per order, or 200,000 in all. It took 1.06 seconds. The two rebuilds produced the same checksum, a fingerprint of all 100,000 orders' states, so the snapshot did not change the answer.

Snapshots are not free, and they do not help short histories. Taking the 100,000 snapshots took 2.27 seconds, so the first rebuild that used them took 3.4 seconds in all, no faster than the full replay. The gain came from the second rebuild on. For a 10-event order, replaying is cheap, which is why the lab's point is about long streams: one order with 10,000 events loaded in 25.7 ms at the median without a snapshot, and in 4.1 ms with one.

A model for reading

Replaying events to answer "what is this order's state?" is fine for one order. A page that lists thousands of orders needs a table shaped for that page. This is the read model, a table built from the events for queries. A projector process reads new events and updates it.

Splitting the write side (commands, which change things, and the event store) from the read side (the read model) is called command query responsibility segregation, or CQRS. A command is a request to change something, such as "add an item".

The projector takes time to catch up. The lab sent 200 commands a second for 30 seconds over 2,000 orders. The projector applied all 6,002 events, and the read model was 7 ms behind at the median and 14 ms at the 99th percentile (the slowest one in a hundred). The likely cause is the outbox relay (the process that publishes events from an outbox table, which here polls for new rows every 10 ms) plus one Kafka hop. The lab did not time those parts separately.

A 7 ms lag is enough to break "I just added it, why isn't it in my cart?". After each command, the lab's client read the read model right away. The command took about 1 ms, so the read came back before the projector had caught up. It returned the old state in 5,988 of the 6,002 reads, 99.8%. The simplest fix is to read your own changes from the event store, or to return the new state from the command itself. Chapter 16 covers the same read-your-writes problem with replicas.

Optimistic concurrency: the version check

Now the cart race again. The event store's add works like this. The writer loads the cart's events and knows the version it read, say 41. It appends its new event as version 42, and the table's primary key is the pair (stream, version). Only one writer can insert version 42 for a given cart.

If someone else already wrote version 42, the database refuses the second insert. The service answers "conflict", the writer reloads the cart, now at version 43, and tries again. This is called optimistic concurrency: assume that no one else writes, and check only at the end. Over the 20-writer race, the event store had 384 conflicts, each one retried, and all 400 items per cart survived.

The price was time: 13.8 seconds against 7.2 for read-modify-write. The lab did not measure the retries separately, but 384 retries against 20,000 additions is under 2% of the work, and the extra time comes from each add making more round trips to the database: two reads, then the event and its outbox row written in one transaction.

The lesson is narrow. Never write a value you worked out from a read that might be stale, without checking that the value is still current. For a plain counter, a single SQL update such as SET items = items + 1 would also have been correct. The lab did not test that, so treat it as the usual expectation, not a measured result.

Changing an event's format

Events that other teams read from Kafka are often written in Avro, a binary format where each event is written with a schema: its name, its fields and their types. The lab's example is an OrderPlaced event with an order id, a product id (sku) and a quantity (qty). Old events stay in the log for years, so a schema change has to be checked against both old and new data.

There are three directions to check:

  • BACKWARD: can new code read old events? This matters when you replay history or upgrade a consumer first.
  • FORWARD: can old code read new events? This matters when producers upgrade before consumers.
  • FULL: both.

Avro's rule for a missing field is to fill in its default, so the rules follow. Adding a field is safe with a default. Removing a field is safe if it had a default. Renaming a field breaks both ways. A rename with the old name kept as an alias (an alternative name the reader accepts) fixes only one direction: new code reads old events, but old code cannot read the new name.

The schema registry is the service that stores each event type's schemas under a name, its subject, and checks every new version against the previous one at the subject's level. The lab tested ten changes, each under all three levels, with three judges: the registry, a checker written for the lab (schema_compat.py), and fastavro, a Python Avro library that actually reads records written with one schema using the other. All 30 verdicts agreed.

Try it · Ten changes to an Avro eventrecorded: registry, our checker and fastavro agree 30 of 30

BACKWARD: new code can read old events (what a replay needs).

ChangeBACKWARD
add a field with a defaultcompatible
add a field without a defaultbreaks
remove a field that had a defaultcompatible
remove a field without a defaultcompatible
rename a fieldbreaks
rename, keeping the old name as an aliascompatible
widen int → longcompatible
narrow long → int (from a long v1)breaks
make it nullablecompatible
change int → stringbreaks

6 of 10 changes pass at BACKWARD. Only adding a field with a default and removing one that had a default pass at FULL. Verdicts agreed on 30 of 30 checks.

The registry's default level, BACKWARD, protects replay, not old consumers. It would allow removing a field without a default, which breaks every consumer that has not been upgraded. When consumers upgrade on their own schedule, the lab's advice is FULL.

The lab's second test used a subject at BACKWARD, the default. The first schema was accepted, and so was a second version that added a coupon field with a default. Then a rename of qty to quantity was refused with HTTP 409 (the status for a conflict). The registry's reason: READER_FIELD_MISSING_DEFAULT_VALUE, because the new field quantity has no default and is missing from the old events. The breaking schema was never given an id, so a producer that registers its schema before sending events could not send it.

The workflow and the results

The sources, in the order the lab runs them:

  1. Race. 20 writers each add 20 items to each of 50 carts, with a 5 ms pause between read and write. Read-modify-write: carts ended at 172 to 187, 10,968 of 20,000 lost, 7.2 seconds. Event store with the version check: every cart ended at 400, 384 conflicts retried, 13.8 seconds.
  2. Rebuild. One million events folded in 3.06 s, and from snapshots at version 8, 200,000 events read in 1.06 s, with the same checksum. Taking the snapshots cost 2.27 s, once.
  3. Long stream. One order with 10,000 events: 25.7 ms at the median without a snapshot, 4.1 ms with one.
  4. Read model lag. 6,002 events over 30 seconds at 200 commands a second. Lag 7 ms at the median, 14 ms at the 99th percentile, 33 ms at most. 5,988 reads right after a write were stale.
  5. Schema matrix. Ten changes, three levels, three judges: 30 of 30 verdicts agreed.
  6. Subject at BACKWARD. v1 accepted (version 1), an added coupon field with a default accepted (version 2), the rename refused with HTTP 409.

Caveats

  • One recorded run per experiment, on one laptop. The runs used a 16-CPU Docker Desktop, and the machine's load average was about 5 when they started. Read the shapes and the orders of magnitude, not the last digit.
  • The 55% needs its 5 ms pause. The pause was added to widen the race. The lab did not measure how often read-modify-write loses updates without it.
  • The cause of the 13.8 against 7.2 seconds is inferred. Retries were under 2% of the additions, and the extra round trips were not timed separately.
  • The read model lag is one load level. The lab ran one projector at 200 commands a second. It did not test lag under heavier load, a slow projector, or a projector restarting.
  • A plain SQL increment was not tested. The chapter's claim that items = items + 1 would also be correct is the usual expectation, not a measured result.
  • The schema tests cover one record type. The ten changes were applied to OrderPlaced, with string, int and nullable fields. The checker handles records, unions and nested records, but changes to enums, arrays, maps and logical types were not tested.
  • Rollouts were not run. The lab checked compatibility verdicts. It did not run a real rolling upgrade of producers and consumers, or the transitive levels (BACKWARD_TRANSITIVE and FULL_TRANSITIVE, which check against every earlier version), which the README leaves as an exercise.
  • Privacy deletes were not tested. An event that holds personal data cannot be edited in place. The usual answers, such as keeping personal data out of events or deleting a per-user encryption key, were not built or measured here.

The checklist

  1. Never write a value you computed from a read that may be stale. Either append at the version you read, or make the database compute the change (items = items + 1).
  2. Expect the refusal, and retry on it. A conflict is not an error to hide. Reload the stream and try again; in the lab that cost less than 2% of the work.
  3. Store what happened and fold it into state. Keep the events; treat every read model as a rebuildable view.
  4. Snapshot long streams, not short ones. For 10-event orders a snapshot cost more than it saved; for 10,000 events it cut the load time by about six times.
  5. Expect the read model to lag, and read your own writes from the write side. The lab's 7 ms of lag was enough to miss 99.8% of immediate reads.
  6. Add or remove fields only with defaults, and set the registry to FULL when consumers upgrade on their own schedule. Let the registry refuse the rest.

Quiz

Try it · Check your understanding0 of 3 answered
  1. 1.Two writers read a cart that holds 41 items. Each adds one and writes back 42 with read-add-one-write-back. What happens?

  2. 2.The event store appends each addition at the version the writer read plus one, and the table allows each version of a stream only once. What does the second of two colliding writers get?

  3. 3.A subject (the registry's name for one event type's schemas) is set to BACKWARD. A producer renames qty to quantity, and quantity has no default. Why is the registry right to refuse it?

Check your understanding

Try each question before opening its answer.

Why does the version check turn a lost update into a retry, instead of letting the second writer win?

Because the second writer's append names a version that is already taken. The event store's primary key is the pair (stream, version), so the database refuses the insert. The service reports a conflict, and the writer reloads the stream, which now has the other writer's event, and tries again on fresh state. Nothing is overwritten.

A fold of the five events in the chapter gives "submitted, with one item". Why is the answer one and not two?

Two items were added and one was removed. The fold applies each event in order: created sets the state to open with no items, each ItemAdded adds one, the ItemRemoved takes one away, and submitted sets the status. The state is never stored in the event log itself, only recomputed from it.

Snapshots made the rebuild faster, but the first rebuild with them took longer than the full replay. Why, and when do they pay off?

Taking the 100,000 snapshots cost 2.27 seconds, so the first rebuild that used them took 3.4 seconds in all, against 3.06 for the full replay. They pay off from the second rebuild on, which read only 200,000 events and took 1.06 seconds. For a long stream, a snapshot also cut one order's load from 25.7 ms to 4.1 ms.

Why is a rename with an alias a partial fix, and which direction does it fail in?

An alias lets new code read old events under the old name, so it passes BACKWARD. It fails FORWARD: old code still looks for the old name and cannot read the new name, so consumers that haven't upgraded break. The lab's matrix shows the same split: the rename with an alias is BACKWARD only, and FULL refuses it.

The registry's default level is BACKWARD, and it allowed removing a field without a default. Why is that a problem if the registry is doing its job?

BACKWARD checks only that new code can read old events. Removing a field without a default passes that check, because new code simply ignores the field in old events. But consumers that have not been upgraded still expect the field, so they break. When consumers upgrade on their own schedule, FULL catches this case.

Next up: Chapter 32, stream processing, watermarks and checkpoints: counting an endless stream of events, and getting the same answer a batch job would. The lab's next script takes the events this chapter stored and computes over them as they arrive.

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.