Skip to content

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.

34 min read0/9 questions

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.

CommandEvent
GrammarImperative: ChargeCard, SendEmailPast tense: OrderPlaced, PaymentFailed
Meaning"Please do this""This already happened"
ReceiversExactly one handlerZero, one or many listeners
Can be refused?YesNo, it is a fact
Sender knows the receiver?YesNo

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.

Match the pairs0/4 matched

Is each message an event or a command?

Choose an item, then its match on the other side.

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:

Python
from collections import defaultdictfrom typing import Callable Handler = Callable[[dict], None] class EventBus: def __init__(self): self._subs: dict[str, list[Handler]] = defaultdict(list) def subscribe(self, topic: str, handler: Handler) -> None: self._subs[topic].append(handler) def publish(self, topic: str, event: dict) -> None: for handler in self._subs[topic]: try: handler(event) except Exception as e: # one broken subscriber must not stop the others print(f" ! {handler.__name__} failed: {e}") bus = EventBus() def send_receipt(e): print(f"email: receipt for order {e['order_id']}")def update_analytics(e): print(f"analytics: +{e['cents']} revenue")def award_points(e): raise RuntimeError("loyalty db down") bus.subscribe("OrderPlaced", send_receipt)bus.subscribe("OrderPlaced", update_analytics)bus.subscribe("OrderPlaced", award_points) bus.publish("OrderPlaced", {"order_id": 42, "cents": 4999})
Output
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)
PayloadIds onlyThe relevant state
Consumers call back?Yes, to fetch detailsNo
Runtime couplingHigh: the source must be up when consumers reactLow: consumers work even if the source is down
Schema couplingLow: few fields to keep stableHigh: every field is part of the contract
RiskA callback storm on the source under loadStale 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_id instead of name, email and address.
Quick check
The shipping service consumes 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?
Need a nudge? A hint rules out a wrong answer.

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.

an OrderPlaced event as a CloudEvent
{
  "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:

  1. Only add, and make additions optional. A new optional field is safe. Renaming, removing, or changing a field's type is a breaking change.
  2. Consumers are tolerant readers. Ignore fields you do not know. Only read the fields you need. Never fail on extra data.
  3. Breaking change means a new event type. Publish order.placed.v2 alongside v1, move consumers over, then stop publishing v1 once nobody reads it.
  4. 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.

Python
def upcast(event: dict) -> dict: # v1 stored a single "amount" in pounds as a float. v2 uses integer cents + currency. if event.get("v", 1) == 1: event = { "v": 2, "type": event["type"], "cents": round(event["amount"] * 100), "currency": "GBP", } return event stored = [ {"type": "Deposited", "amount": 100.0}, # written in 2023 {"v": 2, "type": "Withdrew", "cents": 2500, "currency": "GBP"}, {"type": "Deposited", "amount": 4.99}, # also v1] balance = 0for raw in stored: e = upcast(raw) balance += e["cents"] if e["type"] == "Deposited" else -e["cents"]print(balance)
Output
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.

Python
events = [ {"type": "Deposited", "cents": 10000}, {"type": "Withdrew", "cents": 2500}, {"type": "Deposited", "cents": 500}, {"type": "Withdrew", "cents": 1000},] def apply(balance: int, event: dict) -> int: if event["type"] == "Deposited": return balance + event["cents"] if event["type"] == "Withdrew": return balance - event["cents"] return balance balance = 0for e in events: balance = apply(balance, e)print("now:", balance) # Time travel: replay only the first two eventsprint("after 2 events:", apply(apply(0, events[0]), events[1]))
Output
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.

Predict the outputPython

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)
Need a nudge? Hints walk you through it.

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.

Transactional outbox
Order servicePostgresRelayBrokerEmail serviceBEGIN; INSERT order; INSERT outbox; COMMITSELECT unsent FROM outboxpublish OrderPlacedackUPDATE outbox SET sent_at = now()deliver OrderPlaced

Both rows commit together or not at all. There is no moment where one exists without the other.

1/6
Quick check
Why does the outbox row have to be written in the same transaction as the order?
Need a nudge? A hint rules out a wrong answer.

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.

Python
def reserve_stock(o): print("reserved stock")def release_stock(o): print(" undo: released stock")def charge_card(o): if o["cents"] > 10_000: raise RuntimeError("card declined") print("charged card")def refund_card(o): print(" undo: refunded card")def create_shipment(o): print("shipment created") STEPS = [(reserve_stock, release_stock), (charge_card, refund_card), (create_shipment, None)] def run_saga(order: dict) -> str: done = [] for action, compensate in STEPS: try: action(order) done.append(compensate) except Exception as e: print(f"failed: {e}") for undo in reversed(done): if undo: undo(order) return "cancelled" return "completed" print(run_saga({"cents": 4999}))print(run_saga({"cents": 25000}))
Output
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.

Put it in order4 steps

A saga runs reserve stock → charge card → book courier. Booking the courier fails. Order what happens next.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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).

Quick check
The email service receives OrderPlaced with event_id: e-81 twice because the relay restarted. What should a correct consumer do?
Need a nudge? A hint rules out a wrong answer.

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_id for order events, account_id for 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.

Python
# Arrival order at the consumer, not the order they were published inarrivals = [ {"order_id": 42, "version": 1, "status": "placed"}, {"order_id": 42, "version": 3, "status": "shipped"}, {"order_id": 42, "version": 2, "status": "paid"}, # late: a retry delivered it after v3 {"order_id": 42, "version": 3, "status": "shipped"}, # duplicate {"order_id": 7, "version": 1, "status": "placed"},] view = {} # read model: order_id -> (version, status) def apply(e): current = view.get(e["order_id"]) if current and e["version"] <= current[0]: print(f"skip order {e['order_id']} v{e['version']} (already at v{current[0]})") return view[e["order_id"]] = (e["version"], e["status"]) print(f"apply order {e['order_id']} v{e['version']} -> {e['status']}") for e in arrivals: apply(e)print(view)
Output
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.

Predict the outputPython

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)
Need a nudge? Hints walk you through it.
Quick check
Order events are published to a 12-partition Kafka topic with no key. A consumer sometimes sees OrderShipped before OrderPaid for the same order. What is the best fix?
Need a nudge? A hint rules out a wrong answer.

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.
One checkout, correlation id c-77
POST /checkoutid req-1ShipmentRequestedid e-4, caused by e-2PaymentCapturedid e-2, caused by e-1ReceiptEmailedid e-3, caused by e-1PointsAwardedid e-5, caused by e-1OrderPlacedid e-1, caused by req-1root

The request gets an id, req-1, which becomes the correlation id c-77 for everything that follows.

1/4

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.

Python
import itertools ids = (f"e-{n}" for n in itertools.count(1)) def new_event(type_, data, caused_by=None): event_id = next(ids) return { "id": event_id, "type": type_, "correlation_id": caused_by["correlation_id"] if caused_by else event_id, "causation_id": caused_by["id"] if caused_by else None, "data": data, } placed = new_event("OrderPlaced", {"order_id": 42})paid = new_event("PaymentCaptured", {"order_id": 42}, caused_by=placed)shipped = new_event("ShipmentRequested", {"order_id": 42}, caused_by=paid) for e in (placed, paid, shipped): print(e["id"], e["type"], "corr:", e["correlation_id"], "cause:", e["causation_id"])
Output
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 the pairs0/4 matched

Match each question to the signal that answers it.

Choose an item, then its match on the other side.
ChallengeMedium

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 it
  • off(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 0
from typing import Any, Callable Handler = Callable[[Any], None] class EventEmitter: def __init__(self): pass def on(self, event: str, handler: Handler) -> Callable[[], None]: pass def off(self, event: str, handler: Handler) -> None: pass def emit(self, event: str, payload: Any = None) -> int: pass
ChallengeMedium

Idempotent 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 returns True / true
    • PaymentCaptured adds cents to the order's total
    • PaymentRefunded subtracts cents
  • an event whose id was already processed changes nothing and returns False / false
  • an unknown type changes nothing and returns False / false
  • total(order_id) returns the order's total, or 0 for an order never seen
class LedgerConsumer: def __init__(self): pass def handle(self, event: dict) -> bool: pass def total(self, order_id: str) -> int: pass
Key terms
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.