Domain events: design and schema evolution
An event that carries too little forces consumers to call back, one that carries too much couples everyone to the producer, and any change to its shape can break consumers that read it for years. This chapter shows how FTGO decides what goes into an event and how to change it safely.
key idea / coordinator service / good path in progress / watch out problem / failure neutral
In chapter 6 we made FTGO's messaging reliable: the transactional outbox and change data capture publish exactly what was saved, and idempotent, versioned, partitioned consumers handle duplicates, races and late events. That left one problem open: nothing yet says what an event should contain, or how to change its shape without breaking the services that consume it.
How much data should OrderCreated or OrderAddressChanged carry, what metadata belongs around it, and how can Order Service change it next year while Kitchen, Delivery and Accounting keep running? By the end you can choose an event size, design headers or an envelope, translate events at a context boundary, and plan compatible and breaking schema changes.
A thin event forces a call back
A customer fixes a typo in the house number of an open order. Order Service publishes OrderStreetNumberChanged with just the order id and the new number. Delivery Service needs the full address to send the courier, so it calls Order Service's REST API for the rest. On a busy evening Order Service restarts, the call fails, and the courier is sent with an old address. Even when the call works, it may return data that is already stale.
An event that only says "something changed, ask me for details" is called a town crier event (also known as event notification). It is small and its intent is clear. But it brings back the synchronous dependency that chapter 5 worked to remove: Delivery is now only as available as Order Service.
Let the consumer keep its own copy of the data it needs, built from the events as they arrive, like a bee collecting pollen. Delivery stores the address of every open order and updates it from each address event, so it never has to ask.
A new consumer can build its copy from scratch by replaying a durable log from offset 0, as chapter 5 showed. Bee events are also the best fallback when you cannot change the event at all, for example when it comes from a legacy system or an outside company.
Every consumer stores and maintains a copy, and copies of the same data spread across services. If the events are tiny fragments, rebuilding the full picture is fiddly. When FTGO owns the event, there is a better option: put the right data into the event in the first place.
Right-size the event for its consumers
Bee events work around a thin event. When you own the producer, you can design the event to fit the people who read it.
The Order team argues about how big order events should be. One engineer wants tiny events, one per field. Another wants every event to carry the whole order "just in case". Delivery needs the full address, Accounting needs the address for invoices, and a planned dispatch feature needs order, ticket and restaurant data together.
There are three common sizes, shown here for an order whose street number changed:
Make the event "just right": it keeps a clear business meaning, and it carries the extra fields its consumers need to act without calling back. OrderAddressChanged with the full address serves both Delivery and Accounting.
Two more shapes complete the set. A document on a compacted topic (chapter 5) keeps the latest full state per order, at the price of the change's meaning. A denormalized event goes further: a process manager joins several streams into one larger event, so the consumer reads one stream instead of several.
| Pattern | Idea | Trade-off |
|---|---|---|
| Town crier | Small notification; the consumer fetches the rest. | Easy and quick, but a synchronous dependency returns and the data may be stale. |
| Bee | Consumers store the event data locally. | No runtime coupling; each service keeps and maintains a view. |
| Goldilocks | The event carries what its consumers need. | Best fit when you control the schema; the producer must know its consumers. |
| Document on a compacted topic | The latest full state per key stays on the log. | Consumers lose the meaning of the change. |
| Denormalized | A process manager merges streams into one larger event. | The consumer sees one stream; the process manager is one more component. |
The dispatch feature is a good case for denormalizing. Delivery needs the order, the ticket's ready time from Kitchen, and the restaurant's pickup address. Instead of consuming three streams and coping with their timing, it reads one event that a process manager builds by joining on the order id.
The producer now has to know what its consumers need, and every extra field is something it must keep publishing. Sizing the payload also leaves a second question open: the ids, times and versions that consumers in chapter 6 relied on are still added differently by every team.
Data every event needs: headers and envelopes
The payload states the business fact. Around it sits information that every event needs, whatever the fact.
Kitchen's idempotent consumer needs a unique event id, but Order Service puts it in the body as id and Restaurant Service as eventId. Support wants to follow one customer's order through Order, Kitchen and Accounting, but nothing ties the events together. Restaurant Service's version check from chapter 6 has to parse every body just to find the version.
Separate the shared metadata from the payload, the way HTTP separates headers from the body. Put the same fields, with the same names, on every event: id, correlation id, source, timestamp, version and, where needed, user id.
| Metadata | What it is for |
|---|---|
| Event id | Unique per event. Lets a consumer detect duplicates (chapter 6). |
| Correlation id | Ties together every event caused by one request, for tracing across services. |
| Source and timestamp | Who published it and when, which helps debugging and ordering checks. |
| Version | Tells consumers which schema the body follows (and, as an aggregate version, which state is newer). |
| Priority and user id | Priority routes urgent events to a faster queue. User id supports auditing and erasure, such as the crypto shredding from chapter 5. |
There are two places to put it. Broker headers are optional and flexible, and the broker or a consumer can read them without deserializing the body, so routing and filtering stay cheap. An envelope wraps the payload in a fixed structure, so it can force fields to be present, but changing the envelope touches every event in the system. Keep logic-driving business flags out of both; they belong in the payload.
Every producer must fill the metadata correctly, which usually means a shared library or the service chassis. Agreeing on the envelope also says nothing about the payload's vocabulary, and events from another context arrive in its words, not ours.
Keep another context's language out: translation
Inside a bounded context (chapter 3), words have one agreed meaning. Events that cross a boundary carry the other side's meaning with them.
Accounting consumes events from the card processor, which talks about "charges", "captures" and merchant account codes. Restaurant Service consumes CDC events from the monolith's menu tables, which carry column names such as ITM_PRC_2. If those concepts spread through Accounting's and Restaurant's code, every change on the other side ripples into FTGO's domain logic.
Put a translator at the boundary. It receives the outside event, maps it to the context's own language, drops what the inside does not need, and publishes or hands on an inside event. Only the translator knows the outside model.
This is also where the CDC pipeline from chapter 6 should turn raw row changes into domain events, such as a price column update into MenuItemRepriced.
The translator is one more component to write, test and run, and it must change whenever the outside model changes. That is the point: the change stops there. Our own events, though, change too, and their consumers have no translator to protect them.
Change an event without breaking consumers
An event schema is a contract, as hard to change as an API (chapter 4), and harder in one way: a durable log keeps old events for months or years.
The Order team removes the UserName field from OrderCreated and deploys on Tuesday. Notification Service still reads UserName to greet the customer and starts failing on every new event. On Wednesday the team adds a Country field; Kitchen's old deserializer rejects the unknown field. And a new Delivery instance replaying the log from offset 0 must read events written in every shape the schema has ever had.
Four kinds of compatibility describe what a change does to old and new readers:
| Compatibility | Meaning | Upgrade first | Example change |
|---|---|---|---|
| Backward | The new schema can read data written with the old one. | Consumers | Remove UserName |
| Forward | The old schema can read data written with the new one. | Producers | Add a Country field |
| Full | Both directions work. | Any order | Add Description with a default value |
| None | Neither can read the other. Needs a coordinated cutover. | Both together | Change UserId from a number to a UUID |
Agree on the compatibility level for each event type, and register every schema version in a schema registry that rejects incompatible versions when a producer tries to publish them. Breaks are then caught at build or deploy time, not in Notification's logs.
Full compatibility depends on default values for added and removed fields. Avro and Protobuf support defaults; plain JSON has no schema to declare them in, so JSON consumers must be written to tolerate missing and unknown fields themselves. The safe habit: never remove a field that consumers still read, and add new fields as optional.
A registry is one more piece of shared infrastructure, and compatibility rules limit what a producer may change. Some changes still cannot be made compatible, such as turning the address string into a structured object or changing the type of UserId.
When a change must break: two steps and versioned streams
An incompatible change cannot be made in one release without breaking someone. It can be made in several.
Order Service wants to replace the single Address string in its events with a structured object (street, number, postcode, city), so Delivery can geocode it. Kitchen, Accounting and Notification all read the old string and belong to three teams with their own release plans.
First add the new field next to the old one, a forward compatible change. Give consumers a fixed deadline to move over. Then remove the old field, a backward compatible change.
For a deep redesign, where many fields change at once, apply the same idea to whole versions of the event. The producer publishes v1 and v2 side by side, consumers migrate when they are ready, and v1 is retired.
Give each major version its own stream. Order Service publishes only v2; a separate downscaler turns each v2 event back into the v1 shape for consumers that have not moved yet. An upscaler does the reverse, republishing old v1 events in the v2 shape so new consumers read one version only.
The domain service stays clean because only the converter knows the old shape, and you switch the downscaler off once every consumer has moved. Copying old events into the new stream lets a new consumer replay the full history in one shape.
Two streams must carry the same events, in the same order, for the whole migration, and someone must chase consumers to meet the deadline. Events are now designed and versioned with care. But underneath the events, several FTGO services still read and write tables in the one database the monolith left behind, so they remain coupled where no event schema can help.
Patterns in this chapter
| Pattern | Problem it solves | What it costs |
|---|---|---|
| Town crier (event notification) | Announcing a change cheaply, with clear intent | Consumers call back synchronously and may read stale data |
| Bee (event-carried state transfer) | Consumers need data a thin event does not carry, and you cannot change the event | Each consumer stores and maintains its own copy |
| Goldilocks event | Consumers must act without calling back, and intent must stay clear | The producer must know its consumers' needs |
| Document on a compacted topic | Consumers need the full current state of every entity | The meaning of each change is lost |
| Denormalized event via a process manager | A consumer must combine several streams and their timing | One more component that joins streams |
| Headers or envelope (CloudEvents) | Ids, correlation, versions and times added inconsistently, or buried in the body | Every producer must fill them; envelope changes touch every event |
| Anti-corruption layer | Another context's language and model leaking into your domain | A translator to build and keep up to date |
| Compatibility rules and schema registry | A schema change silently breaks consumers or old events | Shared infrastructure; limits on what producers may change |
| Two-step change | An incompatible field change across teams with different release plans | Two releases, a period with duplicate fields, and a deadline to enforce |
| Stream per version with downscaler or upscaler | A deep redesign that old and new consumers must survive | Two streams to keep in step; converters to run and retire |
Recap
- A town crier event forces consumers to call back, which restores the synchronous coupling messaging was meant to remove.
- When you own the event, make it Goldilocks: clear intent plus the fields consumers need; when you cannot change it, let consumers keep their own copy from bee events.
- Documents on a compacted topic give the latest full state, and a process manager can denormalize several streams into one event for a demanding consumer.
- Shared metadata such as event id, correlation id, source, timestamp and version belongs in headers or an envelope, preferably following CloudEvents.
- An anti-corruption layer translates events from other contexts, including raw CDC row changes, into your own language.
- Schema changes follow backward, forward or full compatibility checked by a schema registry, and incompatible changes are split into two steps or moved to a new versioned stream with a downscaler.
Quick check
OrderStreetNumberChanged but needs the full address, so it calls Order Service for every event. On a busy evening Order Service restarts and couriers go to old addresses. What is wrong, and what are the options?
Show answer
The town crier event created a synchronous dependency, so Delivery fails whenever Order Service is down and may read stale data. Have Order Service publish a Goldilocks OrderAddressChanged with the whole address, or let Delivery keep its own copy of each order's address built from the events (bee). If Delivery needs order, ticket and restaurant data together, a process manager can merge the streams into one event.
OrderCreated that Notification still reads?
Show answer
Not directly. Removing a field is only safe once no consumer reads it. Add any replacement first, give consumers a deadline to stop using the old field, then remove it. A schema registry with a compatibility rule would have rejected the early removal.
Show answer
Add the structured field next to the old string (a forward compatible change), let consumers migrate by an agreed deadline, then remove the string (a backward compatible change). For a larger redesign, publish a v2 stream and run a downscaler that keeps feeding the v1 stream until every consumer has moved.
FTGO's events are now right-sized, carry consistent metadata, and can evolve safely. But several services still share one database underneath, so a column change by one team can still break another, with no event in between.