Highlights

Contents

Part VIII
08

Event-driven design

We step back from brokers to the way events shape a system’s design. Treating “an order was placed” as a published fact rather than a list of calls to make changes who depends on whom. We will cover events versus commands and the event bus, event schemas and their evolution, and eventual consistency, replay, event sourcing and CQRS.

CHAPTER ATLAS / FOLLOW THE READING PATHCHAPTER ATLAS / FOLLOW THE READING PATH1Why work leaves therequest2Consuming safely3Delivery semantics4Retries, poison messagesand DLQs5Kafka fundamentals6Kafka reliability7Running Kafka8Event-driven design9Outbox, inbox and sagas10Scheduled work and theorder end to end

#Section 23Events, commands and the event bus

Messages come in two flavours that look alike and behave differently. A command asks one specific service to do something, such as PlaceOrder or SendReceipt. It is phrased in the imperative, has one intended handler, and can be refused. The sender cares about the outcome. An event reports that something happened, such as OrderPlaced or PaymentCaptured. It is phrased in the past tense, is a fact that cannot be refused, and has no addressee. Its producer neither knows nor cares who reads it.

A COMMAND ASKS ONE SERVICE TO DO SOMETHING; AN EVENT TELLS EVERYONE IT HAPPENEDA COMMAND ASKS ONE SERVICE TO DO SOMETHING; AN EVENT TELLS EVERYONE IT HAPPENEDPlaceOrderto: order servicemay be refusednotice boardOrderPlaced 124kitchen, email, analytics, searchcommands are imperative and addressed; events are past tense, facts, and have no addressee
Figure 8.32A command is a letter to one service. An event is a notice pinned to a board for anyone to read.

The difference shapes dependencies. If the order service sends commands, “tell the kitchen”, “tell the email service”, “tell analytics”, it must know every downstream service and change each time one is added. If it publishes OrderPlaced and lets services subscribe, adding a loyalty-points service next quarter needs no change to the order service at all. That direction of knowledge is the main reason teams adopt events.

An event bus is the shared channel where events are published, in Wren’s case Kafka topics such as order-events. Services publish their own events and subscribe to others. This is publish-subscribe, pub/sub in the general sense, of which Redis pub/sub in Unit VII was a fire-and-forget special case. Kafka’s durable version lets subscribers be down for a while and catch up.

AN EVENT BUS: PRODUCERS DO NOT KNOW WHO LISTENSAN EVENT BUS: PRODUCERS DO NOT KNOW WHO LISTENSorder-eventsorderskitchenemailanalyticssearchadding a new consumer needs no change to the order service
Figure 8.33The order service publishes once. Four services subscribe, and a fifth could join tomorrow.

Events carry a cost in visibility. In a call chain, the code shows what happens next. With events, what happens after OrderPlaced depends on who subscribes, which lives in other repositories and in configuration. Teams counter this with an event catalogue that lists each event, its schema, its producer and its consumers, and with distributed tracing, Unit XIV, which follows a request across asynchronous hops by carrying a trace id in event headers.

A useful distinction is how much an event carries. A thin event, or notification, says “order 124 changed” and lets consumers call back for details, which keeps events small and couples consumers to the producer’s API. A fat event, or event-carried state transfer, includes the order’s relevant fields, so consumers need nothing else. Wren’s events carry the fields consumers need, since a callback storm to the order service after every event would undo much of the decoupling.

#Section 24Event schemas and evolution

Events outlive the code that produced them. A record written today will be read by consumers deployed next month and replayed by a service built next year. The event schema, the names and types of its fields, is therefore a contract, like the API contracts of Unit V, with a longer memory.

Formats with explicit schemas help. Avro, Protobuf and JSON Schema all describe fields and types, and Avro and Protobuf encode compactly in binary. A schema registry, such as Confluent Schema Registry or Apicurio, stores every version of each topic’s schema. Producers register a schema before using it, records carry a small schema id, and consumers fetch the matching schema to decode. The registry also checks each new version against a compatibility rule and refuses incompatible ones before any producer can use them.

A SCHEMA REGISTRY CHECKS EACH NEW VERSION BEFORE ANY PRODUCER USES ITA SCHEMA REGISTRY CHECKS EACH NEW VERSION BEFORE ANY PRODUCER USES ITOrderPlaced v1order_id: longuser_id: longtotal_paise: longOrderPlaced v2order_id: longuser_id: longtotal_paise: longtip_paise: long = 0registrycompatibility:BACKWARDnew field has a default,so v2 readers can read v1recordsrenaming or removing arequired field is refused
Figure 8.34Version 2 adds tip_paise with a default of 0. The registry accepts it under BACKWARD compatibility.

The compatibility modes say which readers must understand which writers. Backward compatibility means consumers using the new schema can read records written with the old one, so consumers upgrade first. Adding a field with a default and removing a field are backward compatible. Forward compatibility means consumers using the old schema can read records written with the new one, so producers can upgrade first. Adding a field is forward compatible, since old readers ignore it. Full compatibility is both, and the safe moves under it are adding or removing optional fields with defaults. Kafka’s history makes transitive modes, which check against every earlier version rather than only the last, the safer default.

WHO MUST UNDERSTAND WHOMWHO MUST UNDERSTAND WHOMmodenew readers read old dataold readers read new dataBACKWARDyesnot promisedFORWARDnot promisedyesFULLyesyesupgrade consumers first under BACKWARD, producers first under FORWARD, either order under FULLsafe changes for FULL: add or remove optional fields that have defaults
Figure 8.35Which side must be upgraded first under each mode.

Some changes are never compatible, renaming a field, changing its type from integer to string, or changing its meaning while keeping its name. For those, Wren follows expand and contract from Unit VI. It adds the new field alongside the old, has producers write both, migrates consumers, and stops writing the old field later. When an event’s meaning changes fundamentally, it publishes a new event type or topic, OrderPlaced.v2, and runs both until consumers have moved.

Every event also carries an envelope with metadata, an event id for idempotency, the event type and version, the time it occurred, the producer, and trace and correlation ids. The CloudEvents specification, a CNCF standard since 2019, defines a common envelope that many teams adopt.

#Section 25Eventual consistency, replay, event sourcing and CQRS

When services react to events, their views of the world update at different moments. Order 124 is committed in the order database at time 0. The relay publishes the event at 40 ms. The kitchen board shows it at 120 ms. For 120 ms the order exists and the kitchen does not know. This is eventual consistency. Every view converges to the same state if no new changes arrive, with a delay. Designing for it means deciding which delays users can see and making them acceptable, such as showing “sending to the restaurant” until the kitchen confirms.

EVENTUAL CONSISTENCY: THE ORDER EXISTS BEFORE THE KITCHEN SCREEN KNOWSEVENTUAL CONSISTENCY: THE ORDER EXISTS BEFORE THE KITCHEN SCREEN KNOWSorders DBKafkakitchen viewmscommit order 124relayed at 40 msshown at 120 msthe inconsistency window
Figure 8.36Committed at 0, relayed at 40 ms, displayed at 120 ms. In between, the views disagree.

Because Kafka keeps history, consumers can replay it. A new search service starts from the earliest retained offset and builds its index from a week of events. A consumer with a bug is fixed, its offsets reset to before the bug, and it reprocesses. Replay works only if consumers are idempotent and deterministic, and if side effects such as emails are switched off during the replay.

Event sourcing takes this to its conclusion. Instead of storing an order’s current state and updating it, the system stores every event that happened to the order, placed with total 450, tip added 30, item removed 80, paid 400, refunded 80, and computes the current state by folding over them. The events are the source of truth, and the current state is derived. Banking ledgers, accounting systems and version control have always worked this way.

EVENT SOURCING: STORE WHAT HAPPENED; DERIVE WHAT ISEVENT SOURCING: STORE WHAT HAPPENED; DERIVE WHAT ISPlaced 450TipAdded 30ItemRemoved −80Paid 400Refunded 80foldorder 124total 400, paid 400refunded 80, status refundedthe state is a function of the history; replay the events and you get it backsnapshots every N events keep replays short; events are never edited, only appended
Figure 8.37Five events folded into one state. Replaying them always gives the same answer.

Event sourcing gives a complete audit trail, the ability to answer “what did this order look like at 8:03 p.m.”, and the freedom to build new views from old history. It costs complexity. Reading current state means replaying events or maintaining snapshots. Changing event schemas is harder, because old events can never be rewritten. And querying across entities, “all orders over 500 rupees today”, needs a separate read model. Most teams use it for a few domains where history matters, such as payments and ledgers, not for everything.

CQRS, command query responsibility segregation, a term from Greg Young around 2010, separates the model that handles writes from the models that serve reads. Commands go to a write model, which enforces rules and emits events. Read models, projections, subscribe to those events and build whatever shape each query needs, a kitchen board keyed by restaurant, a user’s order history, a search index. Each projection can use a different store and can be rebuilt by replay.

CQRS: ONE MODEL TO DECIDE, OTHERS SHAPED FOR READINGCQRS: ONE MODEL TO DECIDE, OTHERS SHAPED FOR READINGwrite sideread sidecommandsorderseventskitchen boarduser historysearch indexeach read model is a projection, rebuilt by replaying events, and lags the write side
Figure 8.38One write model decides. Several read models, each shaped for its queries, follow the events.

CQRS pairs naturally with event sourcing but does not require it. Wren’s order service writes to ordinary PostgreSQL tables and publishes events through an outbox, and its read models are projections of those events. The price is eventual consistency between the write and read sides, which the UI must handle, for example by showing the user’s own new order from the write side until the projection catches up.