Event sourcing: store what happened, not just where you ended up
A normal table keeps only the latest state of an order, so FTGO loses its history and must write a second record to publish each change. Event sourcing makes the events themselves the record: history is never lost, and publishing becomes part of saving.
key idea / coordinator service / good path in progress / watch out problem / failure neutral
In chapter 09 we kept data consistent across services with sagas: each step is a local transaction that publishes an event to trigger the next step, and compensations undo the steps that already ran. That left one problem open: every step still updates a row and publishes an event, two writes that must be kept in step, and the updated row no longer knows how it got to its current state.
What if the events were the data? By the end you can store an aggregate as a list of events, rebuild it, handle concurrency, snapshots, duplicates and schema changes, decide whether the broker can be the event store, and judge when event sourcing is worth its cost.
A table row forgets how it got there
A customer calls FTGO support: "I cancelled order 101 before the restaurant accepted it, but you still charged my card." Order Service's ORDER table holds one row for order 101: status CANCELLED, last updated at 19:42. Every update overwrote the one before, so support cannot see whether the approval came before or after the cancel. On top of that, each change had to be published as an event for the saga, through the outbox from chapter 6: a second write that a developer can forget to add.
Traditional persistence maps each aggregate to rows that hold its current state. History, an audit log and event publishing all have to be bolted on, and each bolt-on can disagree with the table. The mapping between rich objects and flat tables (the object-relational mismatch) adds friction of its own.
Do not store the current state. Store every change to an aggregate as an event, appended to an EVENTS table and never updated or deleted. The current state is whatever you get by replaying those events in order.
Now support can read the exact sequence for order 101, with a time on every step. The events are the data, so there is no separate audit log to drift away from the truth.
The current state is no longer stored anywhere. Every time Order Service wants to read or change an order, it must rebuild it first, and that changes how aggregate code is written.
No row to load: rebuild state by replaying events
Event sourcing fixed the history, but it took away the row that every update used to start from.
The customer adds a dessert to order 101, and Order Service receives a ReviseOrder command. There is no row to load and update. How does the service find out what the order looks like now, and what does it save afterwards?
To load an aggregate, read its events, create an empty object, and apply each event to it in order. In functional terms this is a fold (a reduce) over the list of events.
Split every update in two. process(command) checks the business rules against the current state and returns the events that describe what happened, without changing anything. apply(event) changes the state and cannot fail. The service then appends the new events to the store.
For the dessert, process() checks that the kitchen has not started the order yet and returns an OrderRevised event. If the kitchen had already started, it would reject the command and no event would be saved. The same apply() methods serve both jobs: changing state live and rebuilding it from history.
This is a new programming model, and the team must learn it. Loading by replay also raises new questions: what if two instances append to the same order at once, what if an aggregate has thousands of events, and who publishes the saved events to other services?
The event store: concurrent writers, publishing and long histories
Those three questions are answered by the database that holds the events, the event store.
Two Order Service instances load order 101 at the same moment. One handles the customer's revise, the other the restaurant's reject. Both decide based on the same old state, and both append. The order now holds an OrderRevised after an OrderRejected, which no business rule allows.
An event store usually keeps three tables. EVENTS holds every event. ENTITIES holds one row per aggregate with its current version. SNAPSHOTS holds saved states, which we come to below.
When an instance loads order 101 it remembers the version, say 4. It may append its events only if the version in ENTITIES is still 4, and the append bumps it to 5. The second writer finds version 5, fails, reloads the order and runs process() again against the new state.
The second question, publishing, answers itself. Saving new events is one atomic insert into one table, so the EVENTS table already is the outbox. An event relay reads it, for example by tailing the database's transaction log as in chapter 6, and passes each event to the broker. The "update a row and also publish" double write from the saga chapter is gone.
The third question is speed. An order has a handful of events, but some aggregates live for years. Say a Restaurant aggregate collects a menu change most days: after a few years, every load replays thousands of events.
Every so often, save the aggregate's full state as a snapshot. To load it, read the latest snapshot and apply only the events that came after it.
Versions, retries after a conflict and snapshots are more code and more storage. And the store keeps every event forever, so every mistake in how events are received or shaped is kept forever too.
Events live forever: duplicates, new shapes and forgetting
A table can be patched in place. An append-only store cannot, so three everyday problems need a plan from the start.
Accounting Service is event-sourced. The broker delivers OrderApproved twice, as at-least-once delivery from chapter 5 allows, and Accounting appends two CardCharged events. A year later, the Order team reshapes OrderCreated, but a year of old events in the store keep the old shape. And a customer who leaves FTGO asks for their personal data to be deleted, which an append-only log was built never to do.
Duplicates. An event-sourced consumer must recognize a message it has already handled. How depends on the store.
A NoSQL store often cannot update two tables in one transaction, so the message id travels inside the events it produced. If a message produced no events, the consumer saves a small pseudo event just to record the id.
New shapes. Old events cannot be rewritten, and the aggregate code should not carry every past version of every event. Chapter 7 covered how to change an event schema safely; event sourcing adds one tool.
When events are loaded, pass old versions through an upcaster that converts them to the current shape. The stored event stays as it was; the aggregate only ever sees the latest version.
Forgetting. A permanent log clashes with the right to be forgotten under laws such as the GDPR.
Encrypt each customer's personal data in the events with a key that belongs to that customer alone. When the customer leaves, destroy the key. The events stay in the log, but nobody can read them any more.
Each of these must be designed in from the start: duplicate tracking in every consumer, an upcaster for every changed event, and key management for every service that holds personal data. And so far the events live in a database table and are copied to a broker. Many teams wonder whether that broker alone could do the job.
Event-driven is not event-sourced
Before moving the events onto the broker, be clear about what event sourcing is, because many systems that publish events are not event-sourced.
Kitchen Service keeps tickets in a normal table and publishes TicketAccepted and TicketReady to RabbitMQ. The team calls this event sourcing. Then the business asks for a new view, average preparation time per restaurant over the last year. The events are gone: each one was removed from the queue once consumed. And on the day a publish failed, the table and the events stopped agreeing.
The difference is where the truth lives. In an event-driven service, state lives in a table and events announce changes to it, so the two can drift. In an event-sourced service, the events are the entity, and the latest state is what you get by applying all of them.
The broker matters too. A traditional broker such as RabbitMQ is built for destructive consuming: once a consumer acknowledges a message, it is removed. A durable log such as Kafka keeps messages after they are read, so new consumers can start from the beginning and existing ones can reprocess.
If you want replay, the events must live somewhere that keeps them: an event store, or a broker built as a durable log. A queue that deletes on acknowledge is fine for short-lived work, but it cannot rebuild anything.
A durable log must be sized and retained for the long term. And a service that keeps an event store and also publishes to a durable log now holds the same events in two places.
One copy of the events: the broker as the event store
If the log keeps every event anyway, the events table may be one copy too many.
Restaurant Service appends menu events to its EVENTS table, and a relay copies them to a Kafka topic. Every part of the pipeline in between can lag or fail, and the team spends time proving that the two copies agree.
Skip the events table and keep the events only on the durable log. The service validates commands and appends events to the log. A read model consumes the same stream and builds a query-friendly projection.
A Kafka feature makes this practical: a compacted topic keeps only the latest message for each key. If Restaurant Service publishes one whole document per menu item, keyed by its id, the topic behaves like a table that anyone can read from offset zero.
New consumers and rebuilds then need no special tool. A read model is rebuilt by the same code that handles live events, reading from the start, and more instances make it go faster.
The price is that a log is not a database. Loading the events of one aggregate may mean scanning a whole topic; Kafka Streams state stores can help. A business rule that needs a query, for example "at most 25% of a restaurant's dishes may cost over 40" (an illustrative rule), must read an eventually consistent view, so it can decide on stale data.
One copy of the events, but loading a single aggregate and checking rules that span many aggregates both get harder. And as more services publish to durable logs, consumers start to need data from several logs at once.
Too many streams for one consumer: joining them into one event
A log per service is easy to publish to. It is harder to consume when one decision needs facts from three of them.
To schedule a courier, Delivery Service needs the order's items from Order Service, the pickup address from Restaurant Service and the drop-off address from Consumer Service. These arrive on three streams with different keys and different speeds. A consumer's address change may arrive before or after the order it applies to. Getting ordering and concurrency right across three streams, inside Delivery Service, is hard and easy to get wrong.
Put a small component in front of the consumer that reads all three streams, merges them and publishes one denormalized event, such as a "delivery job", for that boundary. Ordering and concurrency are handled once, in one place.
OrderAddressChanged; build a document or fat event only for consumers that need many fields at once.Another component to run, and large events that carry copies of other services' data. With all its tools in view, it is time to ask whether event sourcing pays for itself.
Is it worth it?
Event sourcing gives FTGO a full history and reliable publishing, and asks for a different way of writing code.
The "time machine" is the benefit that is hardest to get any other way: when the business asks a new question about the past, such as how many orders were revised after approval last year, the answer is already in the events. Use the table below to decide per service, not for FTGO as a whole.
| Good fit | Poor fit |
|---|---|
| Complex query needs (with CQRS read models) | Simple, isolated services |
| Core domain, where new projections will be wanted later | Small data, strong consistency, rare change |
| Strong audit requirements | Teams not ready for snapshots and retention work |
Support now wants a list: "every order of consumer 1234 in the last month, with its kitchen and delivery status". The event store can load order 101 by its id, but it cannot filter all orders by consumer and date. And the kitchen and delivery status are not in Order Service at all.
An event store is good at one thing: loading one aggregate by id. Almost every other query needs a separate read model built from the events, which is the CQRS pattern of the next chapter.
Patterns in this chapter
| Pattern | Problem it solves | What it costs |
|---|---|---|
| Event sourcing | Updating rows loses history and needs a second write to publish events | State must be rebuilt; a new programming model |
| Process and apply | No row to update: how a command changes an event-sourced aggregate | Every operation split into deciding and applying |
| Optimistic locking on the version | Two instances append conflicting events to the same aggregate | The loser must reload and retry |
| Event store as outbox | Saving state and publishing events are two writes that can drift | Needs an event relay that tails or polls the store |
| Snapshots | Long-lived aggregates take too long to replay | Extra storage; snapshot format must evolve too |
| Processed message ids | Duplicate messages create duplicate events | An id table, or ids and pseudo events inside the stream |
| Upcasting | Old events in the store have an outdated shape | An upcaster for every changed event type |
| Crypto shredding | Personal data must be erasable from a permanent log | Key management per user |
| Durable log | Events deleted on acknowledge cannot be replayed | Long-term retention and sizing |
| Log as event store, compacted topic | Keeping events in a table and on a broker means two copies | Loading one aggregate and cross-aggregate rules get harder |
| Process manager joining streams | One consumer needs data from several streams with different keys and speeds | Another component; large denormalized events |
Recap
- Event sourcing stores an aggregate as the append-only list of events that changed it, so the full history is kept and the events are the only source of truth.
- A service rebuilds an aggregate by applying its events in order;
process()turns a command into events andapply()changes the state. - The event store uses a version for optimistic locking, doubles as a reliable outbox for publishing, and uses snapshots to keep long histories fast to load.
- Because events live forever, consumers must track processed message ids, old event shapes are upcast on load, and crypto shredding makes personal data erasable.
- Event-driven is not event-sourced: replay needs a durable log, which can even be the event store itself, for example as a compacted topic of documents.
- Event sourcing pays off for core, audited domains with changing query needs, but almost every query beyond "load by id" needs a separate read model.
Quick check
Show answer
It loads the order's events (or the latest snapshot plus the events after it), creates an empty Order and calls apply() for each event in order.
Show answer
Optimistic locking. Each instance may append only if the aggregate is still at the version it loaded. The first append moves it to version 5. The second finds version 5, fails, reloads the order with the new event applied and runs process() again, which may now reject its command.
Show answer
The old events are gone, so there is nothing to replay, and the table holds only each ticket's latest state. The service was event-driven, not event-sourced. Storing ticket events in an event store, or keeping them on a durable log such as a Kafka topic, would let a new read model be built from the start of the history.
The event store can load one order by id, but it cannot answer "show this consumer's orders this month", and many screens need data that lives in several services at once.