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.
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.
Events, in order (version = line number)
- 1Createdorder opened
- 2ItemAddedone item added+1
- 3ItemAddedone item added+1
- 4ItemRemovedone item removed-1
- 5Submittedorder 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.
BACKWARD: new code can read old events (what a replay needs).
| Change | BACKWARD |
|---|---|
| add a field with a default | compatible |
| add a field without a default | breaks |
| remove a field that had a default | compatible |
| remove a field without a default | compatible |
| rename a field | breaks |
| rename, keeping the old name as an alias | compatible |
| widen int → long | compatible |
| narrow long → int (from a long v1) | breaks |
| make it nullable | compatible |
| change int → string | breaks |
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:
- 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.
- 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.
- Long stream. One order with 10,000 events: 25.7 ms at the median without a snapshot, 4.1 ms with one.
- 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.
- Schema matrix. Ten changes, three levels, three judges: 30 of 30 verdicts agreed.
- 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 + 1would 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
- 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). - 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.
- Store what happened and fold it into state. Keep the events; treat every read model as a rebuildable view.
- 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.
- 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.
- 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
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.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.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.