Lesson 18 of 28Architecture
Event-Driven Architecture
Design events and their schemas, publish reliably with an outbox, handle duplicates and ordering, and trace flows across a broker.
When an order is placed, six things should happen: charge the card, reserve stock, email a receipt, update analytics, notify the warehouse, award loyalty points. If the order service calls all six directly, it is coupled to all six, and one slow email server slows down checkout. Event-driven architecture flips this: the order service announces "an order was placed", and everyone who cares reacts on their own. Most large commerce and payment systems work this way, and system design interviews lean on it heavily.
Events vs commands
These look similar and mean different things.
| Command | Event | |
|---|---|---|
| Grammar | Imperative: ChargeCard, SendEmail | Past tense: OrderPlaced, PaymentFailed |
| Meaning | "Please do this" | "This already happened" |
| Receivers | Exactly one handler | Zero, one or many listeners |
| Can be refused? | Yes | No, it is a fact |
| Sender knows the receiver? | Yes | No |
The last row is the important one. A publisher of OrderPlaced does not know that the loyalty service exists. You can add the loyalty service next month without touching the order service.
Is each message an event or a command?
Pub/sub with an in-memory bus
Pub/sub (publish/subscribe) is the Observer pattern from the behavioral lesson, stretched across a system. Publishers send events to a topic. The broker (Kafka, RabbitMQ, Amazon SNS with SQS, Redis Streams) delivers a copy to every subscriber. Here is the core idea in memory:
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.A real broker adds what memory cannot: events survive restarts, slow consumers catch up at their own pace, and a failed handler gets the event again later.
Designing the event itself
Publishing is the easy part. The hard decisions are what goes in the event, because once other teams consume it, the event is a public contract. Martin Fowler's 2017 essay "What do you mean by Event-Driven?" separates two styles that people mix up.
Thin events (event notification) say that something happened and little else: OrderPlaced { order_id: 42 }. A consumer that needs details calls the order service back to fetch them.
Fat events (event-carried state transfer) include the state consumers need: OrderPlaced { order_id, customer_id, lines, total_cents, currency, placed_at }. Consumers can keep their own local copy and never call back.
| Thin (notification) | Fat (state transfer) | |
|---|---|---|
| Payload | Ids only | The relevant state |
| Consumers call back? | Yes, to fetch details | No |
| Runtime coupling | High: the source must be up when consumers react | Low: consumers work even if the source is down |
| Schema coupling | Low: few fields to keep stable | High: every field is part of the contract |
| Risk | A callback storm on the source under load | Stale copies, and personal data spread to every consumer |
A thin event has a quiet trap. By the time the consumer calls back, the order may have changed again, so it reads a newer state than the event described. If it matters what the order looked like at that moment, the data has to be in the event.
Most teams settle in the middle: include the fields most consumers need, and leave out large or sensitive data. Two more rules help a lot:
- Separate domain events from integration events. Inside a service, events can be as detailed and short-lived as you like. Events published to other teams are a deliberate, documented, versioned API. Do not publish your internal table changes as events and call it a design.
- Keep personal data out unless it must be there. Every topic is a copy that lives for its retention period, and every consumer becomes a system that holds that data. Deleting a user's data later is far easier when events carry
customer_idinstead of name, email and address.
OrderPlaced { order_id } and then calls GET /orders/{id}. During a sale, the order service slows to a crawl. What is the most likely cause, and the usual fix?The event envelope: CloudEvents
Every event needs the same metadata around its payload: a unique id, what kind of event it is, who sent it, when. If every team invents its own field names (eventId, event_id, uuid, msgId), shared tooling such as routing, dedupe and tracing has to understand all of them.
CloudEvents is a CNCF specification for that envelope, and many brokers and cloud services can read it. Version 1.0 requires four attributes: id, source, specversion and type. Common optional ones are time, subject, datacontenttype and dataschema. The payload goes in data.
{
"specversion": "1.0",
"id": "evt_01JB7Z3T9Q2W",
"source": "/services/orders",
"type": "com.shop.order.placed.v1",
"subject": "order/42",
"time": "2026-10-22T09:14:03Z",
"datacontenttype": "application/json",
"dataschema": "https://schemas.shop.example/order-placed/v1.json",
"data": { "order_id": 42, "customer_id": 9, "total_cents": 4999, "currency": "GBP" }
}The spec says source plus id must be unique for each distinct event, which makes that pair a natural dedupe key for idempotent consumers. On HTTP and Kafka the attributes can travel as headers (prefixed with ce- or ce_ depending on the binding) while the body stays the plain payload. Check the CloudEvents site for the exact binding rules for your broker.
You do not have to use CloudEvents. You do need one envelope that every team uses. Adopting the standard saves the argument.
Versioning event schemas
APIs can be versioned by URL and old versions turned off. Events are harder: consumers deploy on their own schedule, topics keep old messages for days, and an event-sourced store keeps events forever. Any change you make has to work for consumers you do not control, reading messages written before the change.
The safe rules:
- Only add, and make additions optional. A new optional field is safe. Renaming, removing, or changing a field's type is a breaking change.
- Consumers are tolerant readers. Ignore fields you do not know. Only read the fields you need. Never fail on extra data.
- Breaking change means a new event type. Publish
order.placed.v2alongsidev1, move consumers over, then stop publishingv1once nobody reads it. - Enforce it with a schema registry. Tools like Confluent Schema Registry (with Avro, Protobuf or JSON Schema) reject a new schema that breaks the compatibility rule you chose, at publish time instead of in production.
Compatibility modes have precise meanings. Backward compatible means a consumer on the new schema can read data written with the old one, so you upgrade consumers first. Forward compatible means a consumer on the old schema can read data written with the new one, so producers can upgrade first. Full means both.
For stored events, the usual technique is the upcaster: a function that turns an old event into the current shape as it is read, so the rest of the code only ever sees the latest version.
Press Run (⌘ Enter) to see what happens.The stored events are never rewritten. The upcaster sits on the read path, and old events stay exactly as they were written, which is the whole point of an audit log.
Event sourcing and CQRS, in plain words
Most apps store current state: balance = 70. Event sourcing stores the history instead: every event that ever happened to the account. Current state is computed by replaying (folding) the events. You get a perfect audit log and can answer "what was the balance last Tuesday?" for free. The cost: more complex queries and the need to version events forever.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.CQRS (command query responsibility segregation) means using different models for writing and for reading. Writes go through the domain model with all its rules. Reads come from a separate, denormalised read model (a projection) shaped for the screen, kept up to date by listening to events. An "order history" page reads one flat table instead of joining six. CQRS pairs naturally with event sourcing, but you can use either one alone, and most apps need neither.
What does this print?
events = [("add", "mug"), ("add", "cap"), ("remove", "mug"), ("add", "bag")]
cart = []
for kind, item in events:
if kind == "add":
cart.append(item)
else:
cart.remove(item)
print(cart)The outbox pattern: publishing reliably
Here is a subtle bug. The order service saves the order to Postgres, then publishes OrderPlaced to Kafka. If the process crashes between those two steps, the order exists but nobody is ever told. Do it in the other order and you can announce an order that was never saved. This is the dual write problem: two systems cannot be updated atomically.
The transactional outbox fixes it. In the same database transaction as the order, insert the event into an outbox table. A separate relay process reads unsent outbox rows, publishes them, and marks them sent.
Both rows commit together or not at all. There is no moment where one exists without the other.
Sagas: transactions across services
Without a shared database, "reserve stock, charge card, create shipment" cannot be one transaction. A saga runs it as a sequence of local steps, each with a compensating action that undoes it. If step 3 fails, run the compensations for steps 2 and 1 in reverse.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.That is an orchestrated saga: one coordinator calls each step. In a choreographed saga there is no coordinator; each service listens for the previous event (StockReserved → charge, PaymentFailed → release stock). Choreography is looser but harder to follow once there are more than three or four steps. Tools like Temporal or AWS Step Functions run orchestrated sagas durably.
A saga runs reserve stock → charge card → book courier. Booking the courier fails. Order what happens next.
- Tap the steps below in the right order.
This lesson keeps the outbox and sagas at the level you need to design with them. The System Design lesson "Sagas, Outbox, and Two-Phase Commit" covers the hard parts: log-tailing relays, saga state machines, timeouts on steps that never answer, and why two-phase commit is rarely used between services.
Idempotent consumers
Brokers deliver at least once. Retries, relay restarts and consumer rebalancing all produce duplicates. A consumer that adds money to a ledger must not add it twice. An idempotent consumer produces the same result however many times it sees the same event. The usual trick: every event carries a unique event_id, and the consumer records which ids it has processed (ideally in the same transaction as its own write).
OrderPlaced with event_id: e-81 twice because the relay restarted. What should a correct consumer do?Ordering and partition keys
Brokers do not give you one global order. Kafka guarantees order only within a partition. When you publish with a key, Kafka hashes the key to pick the partition, so every event with the same key lands in the same partition, in the order it was written. Events with different keys spread across partitions and are processed in parallel, with no order between them.
That makes the partition key a design decision:
- Use the id of the thing whose events must stay in order, usually the aggregate id:
order_idfor order events,account_idfor ledger events. - A key with too few values (like
country) creates hot partitions: one partition gets most of the traffic, and one consumer does most of the work. - Adding partitions later changes which partition a key maps to, so for a while new events for a key can be processed before older ones still on the old partition.
- One consumer processing a partition's events in parallel threads throws the order away again. Order is only kept if one partition is processed in sequence.
RabbitMQ and SQS standard queues give even weaker ordering. SQS FIFO queues order messages within a message group id, which plays the same role as a Kafka key. The "Logs, Kafka, and Stream Processing" lesson in System Design covers partitions in depth.
Even with a good key, consumers will see events out of order sometimes: a retry delivers an old event late, two producers race, or a consumer reads from two topics. Design for it. Give each event a version (or sequence number) per aggregate, and have the consumer remember the latest version it applied.
Press Run (⌘ Enter) to see what happens.Skipping older versions works when each event carries the full state that matters (a fat event). Then the newest version wins, and the check also drops duplicates for free. If events are deltas ("add 5 to stock"), you cannot skip one. The consumer must hold back version 3 until version 2 arrives, or park the aggregate and fetch the current state from the source. That is one more reason fat events are easier to consume.
What does this print?
arrivals = [(2, "paid"), (1, "placed"), (4, "refunded"), (3, "shipped")]
latest = (0, None)
for version, status in arrivals:
if version > latest[0]:
latest = (version, status)
print(latest)OrderShipped before OrderPaid for the same order. What is the best fix?Tracing a flow across the broker
In a synchronous system, a stack trace or one log search shows what happened. In an event-driven one, a single checkout becomes a dozen messages handled by six services over several seconds, and when the loyalty points are missing, nobody can say which hop dropped them. Async flows need their own observability, and it has to be designed in from the start.
Every message carries two ids besides its own:
- Correlation id: the same for every message in one business flow. It usually starts as the request id of the HTTP call that kicked things off. Search your logs for it and you see the whole checkout.
- Causation id: the id of the message that directly caused this one. Together these form a tree, so you can see what triggered what.
The request gets an id, req-1, which becomes the correlation id c-77 for everything that follows.
The rule for a handler is mechanical: when you publish because you handled a message, copy its correlation id and set the causation id to its id. Put this in your shared messaging library once, so nobody has to remember it.
Press Run (⌘ Enter) to see what happens.Distributed tracing adds timing on top. The W3C Trace Context standard defines a traceparent header that carries the trace id and the parent span id. HTTP clients propagate it automatically when instrumented with OpenTelemetry. Across a broker you put it in the message headers (CloudEvents has a distributed tracing extension for this). OpenTelemetry's messaging conventions model a publish as a producer span and the handling as a consumer span, and use span links when one handler processes a batch of messages from different traces. The details move quickly, so check the current OpenTelemetry docs for your language.
Finally, watch the signals that only async systems have:
- Consumer lag: how far behind the newest message a consumer group is. Rising lag is the earliest warning that a consumer is failing or too slow.
- Dead-letter queue size: messages that failed every retry. A DLQ nobody watches is where data goes to disappear. Alert on it and have a way to replay.
- Age of the oldest unsent outbox row: if it grows, your relay is stuck, and every downstream system is quietly getting stale.
Match each question to the signal that answers it.
Build an EventEmitter
Build an EventEmitter, the in-process core of pub/sub.
on(event, handler)subscribes a handler and returns a function that unsubscribes itoff(event, handler)unsubscribes a handler (doing nothing if it was never subscribed)emit(event, payload)calls every handler for that event, in the order they subscribed, with the payload, and returns how many handlers it called- a handler that unsubscribes itself while running must not cause the next handler to be skipped
bus = EventEmitter()
stop = bus.on("order.placed", lambda e: print("email", e["id"]))
bus.emit("order.placed", {"id": 42}) # prints "email 42", returns 1
stop()
bus.emit("order.placed", {"id": 43}) # returns 0Idempotent payment consumer
A broker delivers payment events at least once, so duplicates happen. Build a LedgerConsumer that keeps a running total per order and is idempotent.
Events look like {"id": "evt_1", "type": "PaymentCaptured", "order_id": "o1", "cents": 4999} (TypeScript uses orderId).
handle(event)applies the event and returnsTrue/truePaymentCapturedaddscentsto the order's totalPaymentRefundedsubtractscents
- an event whose
idwas already processed changes nothing and returnsFalse/false - an unknown
typechanges nothing and returnsFalse/false total(order_id)returns the order's total, or0for an order never seen
- event
- An immutable fact about something that already happened, named in the past tense, with any number of listeners.
- event sourcing
- Storing every change as an event and computing current state by replaying them.
- CQRS
- Using separate models for writes (rules) and reads (projections shaped for screens).
- transactional outbox
- Saving outgoing events in the same database transaction as the data change, then publishing them from a relay.
- saga
- A multi-service workflow made of local steps, each with a compensating action to undo it on failure.
- idempotent consumer
- A handler that gives the same result no matter how many times it receives the same event.
- event-carried state transfer
- Putting the state consumers need into the event, so they never have to call the source back.
- CloudEvents
- A CNCF specification for a common event envelope with required id, source, specversion and type attributes.
- partition key
- The value a broker hashes to choose a partition. Events with the same key stay in order.
- correlation id
- An id shared by every message in one business flow, used to find the whole flow in logs.
- causation id
- The id of the message that directly caused this one, which turns a flow into a tree.