Chapter 07 of 27 · Part 4: Transactional messaging and domain events

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

Where we are

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.

This chapter

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

Problem

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.

Town crier: small event, then ask The consumer receives a notification and calls the owner to fetch the rest. Order svc owns the address Broker OrderAddressChanged Delivery svc needs full address Dashed: a synchronous fetch. Simple to build, but delivery now fails when order is down.
Solution · Event-carried state transfer (bee events)

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.

Bee: carry the state with the event Consumers keep a local copy of the fields they need and update it with each event. Order svc publishes changes Broker partial events Delivery svc local order view No remote call, so no coupling at runtime. The copy holds only what delivery needs.

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.

Cost

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.

Problem

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:

Three event sizes Town crier OrderStreetNumberChanged Small and clear intent Consumer must call back Goldilocks OrderAddressChanged Full address included Less exact intent Document OrderDocument Whole entity, one event Intent is lost Town crier is also called event notification. A document keeps the latest state per id.
Solution · Goldilocks event

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.

PatternIdeaTrade-off
Town crierSmall notification; the consumer fetches the rest.Easy and quick, but a synchronous dependency returns and the data may be stale.
BeeConsumers store the event data locally.No runtime coupling; each service keeps and maintains a view.
GoldilocksThe event carries what its consumers need.Best fit when you control the schema; the producer must know its consumers.
Document on a compacted topicThe latest full state per key stays on the log.Consumers lose the meaning of the change.
DenormalizedA 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.

Denormalizing with a process manager A process manager merges order, ticket and restaurant events into one delivery event. Order events Ticket events Restaurant events Process manager joins by order id Delivery event one large stream The delivery service no longer juggles concurrency across three sources.
Rule of thumb: design events with their consumers in the room. If you own the event, aim for Goldilocks. If you cannot change it (a legacy or external source), prefer bee over town crier, and keep town crier callbacks as a quick fix only. Do not pull another domain's data into your event: Order Service should not publish the restaurant's opening hours. And a very large event can hint that a service has too much responsibility.
Cost

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.

Problem

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.

Solution · Event metadata in headers or an envelope

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.

An event with metadata and payload OrderCreated Metadata (headers) Payload (the fact) event id correlation id source version timestamp user id OrderId: 3621 MenuItemId: 2184 Quantity: 2 UserId: 164
MetadataWhat it is for
Event idUnique per event. Lets a consumer detect duplicates (chapter 6).
Correlation idTies together every event caused by one request, for tracing across services.
Source and timestampWho published it and when, which helps debugging and ordering checks.
VersionTells consumers which schema the body follows (and, as an aggregate version, which state is newer).
Priority and user idPriority 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.

Standard first: CloudEvents is a specification that defines a common set of these attributes, so tools from different vendors understand your events. Prefer it over inventing your own names.
Cost

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.

Problem

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.

Solution · Anti-corruption layer

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.

Anti-corruption layer Outside event their wording Translator adapts and filters Inside event our language The layer keeps domain logic and information inside the boundary.

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.

Cost

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.

Problem

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:

CompatibilityMeaningUpgrade firstExample change
BackwardThe new schema can read data written with the old one.ConsumersRemove UserName
ForwardThe old schema can read data written with the new one.ProducersAdd a Country field
FullBoth directions work.Any orderAdd Description with a default value
NoneNeither can read the other. Needs a coordinated cutover.Both togetherChange UserId from a number to a UUID
Solution · Compatibility rules enforced by a schema registry

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.

Cost

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.

Problem

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.

Solution · Split the change in two

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.

Splitting an incompatible change Add new field forward compatible Both exist consumers move over Remove old field backward compatible Set a deadline for the old field so consumers have a fixed window to move.

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.

Two-step breaking change Publish both versions side by side, migrate consumers, then retire the old one. v1 only all consumers on v1 v1 and v2 producer writes both Migrate consumers move v2 only drop v1 Never remove a field the consumers still read. Add the new one first, then remove the old one later.
Solution · Stream per schema version, with a downscaler or upscaler

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.

Stream per schema version with a downscaler Order service publishes v2 orders v2 stream New consumers (v2) Downscaler new to old shape orders v1 stream Old consumers (v1)

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.

Cost

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

PatternProblem it solvesWhat it costs
Town crier (event notification)Announcing a change cheaply, with clear intentConsumers 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 eventEach consumer stores and maintains its own copy
Goldilocks eventConsumers must act without calling back, and intent must stay clearThe producer must know its consumers' needs
Document on a compacted topicConsumers need the full current state of every entityThe meaning of each change is lost
Denormalized event via a process managerA consumer must combine several streams and their timingOne more component that joins streams
Headers or envelope (CloudEvents)Ids, correlation, versions and times added inconsistently, or buried in the bodyEvery producer must fill them; envelope changes touch every event
Anti-corruption layerAnother context's language and model leaking into your domainA translator to build and keep up to date
Compatibility rules and schema registryA schema change silently breaks consumers or old eventsShared infrastructure; limits on what producers may change
Two-step changeAn incompatible field change across teams with different release plansTwo releases, a period with duplicate fields, and a deadline to enforce
Stream per version with downscaler or upscalerA deep redesign that old and new consumers must surviveTwo streams to keep in step; converters to run and retire

Recap

Quick check

Delivery Service receives 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.

Can Order Service remove a field from 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.

You must change the address in order events from a string to a structured object, without a big-bang release. What do you do?
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.

Still open

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.

Next: 08 Database per service and the shared database →