Chapter 10 of 27 · Part 5: Data management

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

Where we are

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.

This chapter

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

Problem

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.

Two ways to save an Order Traditional persistence Current state in one ORDER row Updates overwrite history Events and audit log are bolted on Object-relational mismatch Event sourcing Many rows in an EVENTS table Append only: history kept Events are the data Simple, serializable events
Solution · Event sourcing

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.

EVENTS table for one order An order is stored as a list of events, never updated, only appended. EVENTS table (append only) event_id event_type entity 102 OrderCreated Order 101 103 OrderApproved Order 101 104 OrderShipped Order 101 105 OrderDelivered Order 101 Current state = replay these 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.

Cost

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.

Problem

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.

Rebuilding an aggregate Load events for one aggregate new Order() empty object apply(event) once per event Current state ready to use This is a fold (reduce) over the list of events.
Solution · Commands become events (process and apply)

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.

Process and apply Command e.g. ReviseOrder process() checks rules returns events apply(event) changes state cannot fail Save events append to store process() decides. apply() just records what happened.

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.

Cost

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.

Problem

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.

Parts of an event store Event store database + broker EVENTS every event ENTITIES aggregate + version SNAPSHOTS saved states Optimistic locking uses the version to stop two writers overwriting each other.
Solution · Optimistic locking on the aggregate version

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.

Reliably publishing events Save events one atomic insert EVENTS table permanent record Event relay tails the DB log Message broker subscribers read Saving an event is atomic, so event sourcing doubles as reliable event publishing.

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.

Solution · Snapshots

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.

Snapshots speed up loading Events 1 to N skipped Snapshot N saved state Event N+1 apply Event N+2 apply Load the latest snapshot, then only the events after it.
Cost

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.

Problem

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.

Handling duplicate messages Relational event store Insert id into PROCESSED_MESSAGES In the same transaction as the events NoSQL event store Store message id inside the new events If none: save a pseudo event

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.

Solution · Upcasting

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.

Evolving events with upcasting Old event v1 stored forever Upcaster converts on load Event v2 current shape Aggregate only knows v2

Forgetting. A permanent log clashes with the right to be forgotten under laws such as the GDPR.

Solution · Crypto shredding

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.

Crypto shredding Encrypt one key per user Log keeps encrypted events User leaves destroy the key Unreadable events remain Only encrypt in services that hold sensitive data, or do it in a shared sidecar.
Cost

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.

Problem

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.

Two ways to use events Event-driven State saved in a table Events announce changes Table and events can drift Event-sourced Events are the entity State = replay of events One source of truth In an event-sourced entity, the latest state is what you get by applying all its events.

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.

Ephemeral queue versus durable log Ephemeral queue Consumer acks Message is removed Best for fast, short-lived work Durable log Consumer reads Message stays Replay and new consumers
Solution · Keep events on a durable log

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.

Cost

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.

Problem

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.

Solution · The log as the event store

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.

Events stored on the broker Restaurant service validates commands Event log stores the events Read model denormalized view Rebuild the read model, or start a new one, by reading the log from the start.

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.

Log compaction by key Before (key = menu item id) off 1 key A off 2 key B off 3 key C off 5 key C off 8 key C After compaction (older C removed) off 1 key A off 2 key B off 8 key C Example offsets. This example keeps offset 8.

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.

A cousin: command sourcing. Instead of events, store the commands as they were received. You can then replay user requests after fixing a bug, or compare two versions of an algorithm on the same input. It also brings asynchronous feedback problems, because a command that is rejected is only discovered later. Most of the time, event sourcing is enough.
Cost

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.

Problem

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.

Solution · Process manager that joins streams

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.

A process manager builds a delivery job Order events items, total Restaurant events pickup address Consumer events drop-off address Process manager merges, no domain logic Delivery job one fat event Fat events are the price. In return, ordering and concurrency are solved once, by design.
Keep the manager thin. Its job is to adapt and merge, so it acts like an anti-corruption layer. Business rules stay in the owning services. Inside an event-sourced service, prefer small, intent-revealing events such as OrderAddressChanged; build a document or fat event only for consumers that need many fields at once.
Cost

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.

Benefits and drawbacks of event sourcing Benefits Reliable event publishing Complete, accurate history Avoids object-relational mismatch Time machine for new needs Drawbacks New programming model Event schemas must evolve Deleting data is tricky (GDPR) Querying needs CQRS

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 fitPoor fit
Complex query needs (with CQRS read models)Simple, isolated services
Core domain, where new projections will be wanted laterSmall data, strong consistency, rare change
Strong audit requirementsTeams not ready for snapshots and retention work
Problem

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.

Cost

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

PatternProblem it solvesWhat it costs
Event sourcingUpdating rows loses history and needs a second write to publish eventsState must be rebuilt; a new programming model
Process and applyNo row to update: how a command changes an event-sourced aggregateEvery operation split into deciding and applying
Optimistic locking on the versionTwo instances append conflicting events to the same aggregateThe loser must reload and retry
Event store as outboxSaving state and publishing events are two writes that can driftNeeds an event relay that tails or polls the store
SnapshotsLong-lived aggregates take too long to replayExtra storage; snapshot format must evolve too
Processed message idsDuplicate messages create duplicate eventsAn id table, or ids and pseudo events inside the stream
UpcastingOld events in the store have an outdated shapeAn upcaster for every changed event type
Crypto shreddingPersonal data must be erasable from a permanent logKey management per user
Durable logEvents deleted on acknowledge cannot be replayedLong-term retention and sizing
Log as event store, compacted topicKeeping events in a table and on a broker means two copiesLoading one aggregate and cross-aggregate rules get harder
Process manager joining streamsOne consumer needs data from several streams with different keys and speedsAnother component; large denormalized events

Recap

Quick check

How does an event-sourced Order Service know the current state of order 101?
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.

Two instances of Order Service handle a revise and a reject for the same order at the same moment. Both load version 4. What stops a broken history, and what happens to the slower one?
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.

FTGO's Kitchen Service saves tickets in a table and publishes events to a queue that deletes messages once they are acknowledged. The business wants a new report on last year's preparation times. What breaks, and what would have made it possible?
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.

Still open

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.

Next: 11 Queries: API composition and CQRS →