Systemsfor Aravinda
0 / 78 core
Week 5 · Messaging

Event sourcing and CQRS

2 hours · core path

Read first: Queues and logs, Choosing a database

In one sitting

The log of events is the source of truth, and a balance is the fold of that log, so a wrong projection can be rebuilt from the start. A wrong old event is not fixed by editing it, because other readers may already have acted, so you append a correction and you version every shape. CQRS means the read model and the write model differ, it does not require this log, and most CRUD should stay a row you update.

A row is a convenience. It answers “what is true now” and throws away how it became true. That is the right trade for a display name. It is the wrong trade when the how is the product: a balance you must explain, a projection you might want to rebuild next year, a second team that needs the same facts. Event sourcing keeps the how, and makes the now into something you compute.

Core concepts

The log is the source of truth. An event is an immutable fact in the past tense. Deposited, with an amount, an account, an event id, and a position in that account’s stream. You append. You do not update an event in place as a normal write path. Current state is not stored as the authority. Current state is a projection, which means a fold: start from a known initial value and apply each event in order. If the projection and the fold disagree, the projection is wrong. You rebuild it by reading the log again. Queues and logs is why this is a log and not a queue. Readers keep offsets, many projections can share the stream, and replay is the feature you paid for.

The fold has to be deterministic. Same events, same order, same result, on every machine that runs it. A fold that calls the clock, or a random source, or a network service, will rebuild into a different answer next Tuesday. Put those effects outside the fold. The event can record that a rate was 3 percent at the time. The fold multiplies. It does not go and ask.

You will have more than one projection. The balance row is one. A monthly statement is another. A fraud feature vector is a third. They can lag each other, because each has its own offset. That lag is acceptable when the screens do not pretend to be one atomic view. It is a bug when the account page adds two projections that are not from the same point in the log and presents the sum as now. Either read them from one projection you built to be consistent, or show the version each number came from.

Versioning is the cost of never throwing the past away. The code that folds will change. The bytes already in the log will not, unless you take on a rewrite. Every event needs a shape name and a version. An upcaster is a function that reads an old shape and produces the shape the current fold expects. Old events stay on disk in the shape they were written. New code learns to read them. You do not deploy a fold that only understands the new JSON and then act surprised when a year of history stops loading.

Versions exist because someone will get one wrong in production. A field that meant dollars last month and cents this month is not a documentation issue. It is two different events that happen to share a name. Without a version, the upcaster is a guess about a deploy window. With a version, the guess is confined to one numbered shape, and you can test it.

Replay doubles any side effect you left in the consumer. Rebuilding a balance should set the balance to the folded value. Rebuilding must not send the receipt email a second time. If the mailer is a consumer of the same log, it has to remember which event ids it already turned into mail. That is Delivery guarantees again. A projection that sets state is naturally idempotent if you replace the row with the fold. A projection that increments on each delivery is not, and a replay or a duplicate delivery will drift it. Prefer “balance is 125” over “add 40” at the sink, or store the event id and ignore one you have applied. The fold itself, run from the start of the stream, is idempotent in the useful sense: running it twice from offset zero produces the same row. Running it twice on each new event, as two increments, does not.

CRUD wins when the row is the product. A settings page stores a display name. The user overwrites it. Nobody rebuilds 2019 to answer the request. Nobody else consumes the sequence. One database holds the invariant. Choosing a database plus Transactions and isolation is the whole design. An audit table, if security wants one, can record the overwrite and still not be the source of truth. The product reads the row. Event sourcing that display name means you now version NameChanged forever, you now operate a fold, and you now have a plan for a buggy old event, in exchange for nothing the form needed. Ordinary CRUD does not need a log as its authority. Take the log when you have a real reason to replay or to fan the same facts out. A reason you might have later is a weak reason. You can add an audit log beside a row when the day comes. You cannot easily delete a log you made the authority.

CQRS is a different decision. The write model and the read model are different shapes. Commands hit a model that protects invariants. Queries hit a model shaped like a screen: balance, last four transactions, a fraud flag, one round trip. Building that screen from the write tables might be an ugly query, so you keep a second shape and you accept that it trails. CQRS does not require event sourcing. A job can copy rows from the write database into the read database. Event sourcing does not require CQRS either. You can fold events into one row and serve that row to both commands and queries. What CQRS always requires is tolerance for lag. The user deposits and immediately reads the read model. The deposit may not be there. Read-your-writes, for their own account, means serving that read from the write side, or handing back a version and waiting until the read model has caught up. That is the same family of problem as replication lag. If you cannot explain what the user sees in that second, you do not have a CQRS design. You have two copies and a wish.

The signal that you want neither: one service, one database, queries that are fine against the write tables, no second consumer of a history. Two models is two places to be wrong. A log as authority is a versioning project. Pay for them when a constraint forces the split, not when a diagram looks current.

A worked example

Account 88 is a fold. The events below are the log. The number on the right is the balance after that event. Dollars, for reading. The initial value is 0. Nothing in this list is a stored balance. The stored authority is the left-hand column.

Assumptions for the later arithmetic, separate from this one account:

  • 1 million balance-changing events a day across all accounts. A sketch.
  • A typical account’s stream is 200 events long. An assumption about this product, so you can feel the difference between folding one account and folding the year.
  • A year is about 3 × 10^7 seconds.
Opened                          0
Deposited 100                 100
Deposited 40                  140
Withdrew 15                   125

The projection row says 125. If the row says 130, you do not patch the row and walk away. The next rebuild will write whatever the fold says, and your patch dies. You fix the fold or you fix the events, then you rebuild.

Now the bug in an old event. The third event was supposed to be a deposit of 40. A serializer dropped a decimal point and the log says 4000. The email projection has already sent “we received 4000.” The balance projection shows a fortune.

Opened                                  0
Deposited 100                         100
Deposited 4000     bug, meant 40     4100
Withdrew 15                          4085

append, do not edit:
Adjustment minus 3960, cites the bad deposit
4085 - 3960                         = 125

the stream you wish you had written
0 + 100 + 40 - 15                   = 125

Both endings are 125. They are not the same history. The adjustment stream tells the truth about what the system did: it recorded 4000, it mailed that number, then a person appended a correction. The wished stream is a rewrite. Editing the old event in place fails in three concrete ways.

First, consumers that have already passed that offset will not see the edit. The mail was sent. The fraud model scored a 4000 deposit. Their offsets are ahead of the event, and a log does not push mutations into the past. You would have to rewind every consumer, and any consumer that is not idempotent will re-apply the withdrawal and double it.

Second, a rebuild after a silent edit hides the incident. Next quarter someone asks why a receipt says 4000, and the log says 40. You have made the source of truth disagree with the outside world it already touched.

Third, you may not be allowed to pretend the bad event never happened if the receipt is a record you have to stand behind. The correction is a new fact. The fold learns to apply Adjustment. The mailer, if it is idempotent on event id, will not resend the original deposit, and it can send a new message for the adjustment if the product wants one. If you needed the original mail to have been right, you are too late. Say that to the person asking for a rewrite.

A different bug lives in the fold, and the repair is the opposite. The statement projection used integer division and dropped cents for a year. The events are right. Editing events would make this worse. You fix the code and you replay the year into the statement projection. You do not hand-edit the statement table and leave the bug in the fold. The next replay would bring the bug back and overwrite the hand edit. Two bugs, two directions. Bad fold: fix code, replay. Bad event: append a correction, then replay. People mix these up and rewrite history for a display bug, or they patch a table for a poisoned event and watch the poison return on the next rebuild.

Versioning is how the 4000 happened in a way you can detect. Suppose version 1 events carry an amount as a decimal string of dollars, and version 2 carries an integer number of cents and a currency code. The upcaster for version 1 multiplies by 100 and assumes US dollars. That is a written assumption, testable on a fixture of real version 1 payloads. The dangerous deploy is the one that writes version 2 cents into the version 1 field because a flag flipped halfway. The upcaster multiplies those by 100 again. Balances jump by a hundredfold. The symptom is a projection that is internally consistent and still nonsense. A version on every event from the first day confines the upcaster. A fixture of captured payloads, including a few from the bad window if you kept them, tells you the upcaster is wrong before you replay a year. “We will remember which deploy did it” is not a version.

events per second, the sketch
  1,000,000 / 86,400 = 11.6
  shortcut: 1,000,000 / 100,000 = 10

a year at that rate
  11.6 * 3e7 = about 350 million events

one account, assumed 200 events
  fold on read is 200 steps
  rebuilding every account is the year-sized job

Folding account 88 on a request is cheap if the stream stays short. Rebuilding every statement after the cents bug is a job over hundreds of millions of events under this sketch, not a button on the request path. Per-account streams are why the fold stays small. One global log you fold from the beginning on every page view will not stay small. Partition the stream by account. Partitioning and sharding applies: the account id is the key, one account stays ordered, a hot account is a hot partition, and you do not fix that hot account by folding it on the user’s request thread if 200 events is actually 2 million.

flowchart LR
  opened[Account opened] --> dep100[Deposited 100]
  dep100 --> depBug[Deposited 4000 bug]
  depBug --> withdrew[Withdrew 15]
  withdrew --> wrong[Fold is 4085]
  wrong --> corr[Adjustment minus 3960]
  corr --> fixed[Fold is 125]

The receipt that already left the building is not on this diagram. The diagram is the log after you chose to append. The mail is a side effect of an earlier offset. A correction does not travel backward down a queue that has already deleted the work.

Tradeoffs

Choice What you gain What you spend
Row update, CRUD One place to write, a transaction, no versioning project The past is gone unless you added a separate audit
Event log as the authority Rebuild a projection, add a new one later, explain a balance Versioned events, deterministic folds, a plan for bad history
Fix a bad fold and replay The log stays honest, the new code rebuilds the view Replay time, and any side effect in that consumer runs again unless you guarded it
Edit an old event in place The fold looks clean if you only read the log Consumers that already passed the offset keep the old world, and the outside effects are now unexplained
Append a correction History matches what happened, rebuilds converge The fold must understand corrections, and you still cannot unsend the mail
CQRS on top of ordinary tables Read shape matches the screen, write shape keeps the invariant Lag, and a path for read-your-writes
CQRS on top of events The read model is just another projection you can rebuild You operate both the log and the lag
One model for reads and writes No lag to explain The write shape and the screen shape have to be the same, or the query gets ugly

“Just another projection” in that row is the trap in the compliment. A projection you can rebuild is a gift when the consumer sets state. It is an incident when the consumer charges a card. Do not put the charge in the fold. Record Captured after the charge has succeeded, and let the fold count Captured events. The charge itself stays at the edge from the delivery page, with a key.

Pitfalls

  • Storing commands in the log. PleaseDebit is a request. Replay will ask again. Debited is a fact. Replay will fold it. Symptom: a rebuild sends a second charge or a second mail. If the command might fail, it is not yet an event.
  • Incrementing a projection on delivery. Symptom: every replay and every at-least-once redelivery drifts the balance upward. Replace the row with the folded value, or dedupe on event id.
  • Patching the projection by hand after an incident. Symptom: the on-call looks fixed until the next deploy replays, and the bug returns. Repair the log or the code, then rebuild.
  • Editing a bad event because “nobody will notice.” The mailer already noticed. Symptom: a customer holds a receipt the log no longer explains. Append a correction.
  • A fold that reads the wall clock. Symptom: two rebuilds of the same account produce different numbers, and you cannot tell which deploy did it. Pass time in the event.
  • No version on the payload. Symptom: one upcaster misreads a year, and you cannot separate old dollars from new cents. Stamp the version at write time.
  • CQRS with no answer for the user’s own read. Symptom: the user deposits, refreshes, and files a ticket that the money vanished. Serve their read from the write model, or block until the read model has their version.
  • One global stream folded on the request path. Symptom: the hottest account, or the whole year of events, sits on the user’s latency. Fold per account, snapshot if the streams grow, rebuild offline.

In the interview

Start with the authority. “The source of truth is the log of facts for that account. The balance is a fold. If the row disagrees, I rebuild the row. I use this when I must explain or rebuild. A display name stays a row in one database.” Mention CQRS only if the read shape is actually different, and in the same sentence say the read model lags and how the user reads their own write.

The number is the size of a rebuild, not a slogan. A million events a day is about 12 a second, and a year of that is a few hundred million events. Folding one account is a small loop. Rebuilding the world is a job. The bottleneck is a hot account if you keyed badly, or the replay itself if you put a side effect in it. The tradeoff: you can add a projection later, and you must version events and refuse to silently edit the past.

Skip framework names. Skip a claim that event sourcing is how serious systems store everything. The question that follows is almost always “how do you fix a bad event?” Answer with the correction event and the thing you cannot unsend. If they ask whether this replaces transactions, say no. One database, one invariant, one commit, still wins.

Check yourself

The balance row shows 125 and a fold of the log shows 140. Which one do you change?

The row. The log is the authority, so the row is a cache of the fold that has drifted. Patching the row only lasts until the next rebuild, which will write 140 again. Find out whether the fold code is wrong or the row writer is wrong, fix that, and rebuild the row from the log.

A deposited event says 4000 because a decimal point was dropped, and a receipt was already sent. Why is editing that event not the repair?

Readers that have passed that offset will not observe the edit, and the receipt already in the customer’s hands would no longer match the log. Rewinding every consumer re-applies later events unless each consumer is idempotent. Append an adjustment that cites the bad event, teach the fold to apply it, and treat the receipt as a fact you cannot recall. A new message can announce the correction. The old one stays explained.

The monthly statement dropped cents for a year, and the events are correct. What do you replay, and what do you refuse to hand-edit?

Replay the statement projection after you fix the fold. The log does not need a correction, because the events were right. Hand-editing the statement table leaves the bug in the code, and the next replay overwrites the edit with the same wrong numbers. A bad fold is a code repair plus a rebuild. A bad event is a new event plus a rebuild. This is the first one.

Does a read model shaped for the home screen require an event log? What does it require either way?

No. CQRS is the split between a write shape and a read shape. A copying job between two tables is enough. Either way the read model lags the write model, so a user who just wrote must have a defined way to see that write: read the write model for their own account, or wait for a version. Event sourcing is one way to feed the read model, not a prerequisite.

Why is the current display name a poor event-sourced aggregate?

The product reads the current row, overwrites are the update, and no consumer needs to rebuild the name from history. You would take on versions, a fold, and a bad-event plan for a form that a single database row already serves. An audit table beside the row can record changes without becoming the source of truth. Keep the log for state you must explain or fan out.

Based on: Designing Data-Intensive Applications, Kleppmann and Riccomini; Jay Kreps, Neha Narkhede, and Jun Rao.