Skip to content

Event-Driven Architecture

Intermediate 41 min read Part 8 of 18

Building systems around events: events vs commands, notification vs state transfer, choreography vs orchestration, benefits, costs, and schema versioning.

Summary#

In an event-driven architecture (EDA), services announce facts that already happened ("OrderPlaced") as events, and other services react to them, instead of calling each other directly. An event states a fact, a command asks one receiver to do something, and a message is the envelope that carries either. Events can be thin (event notification: "order 42 changed, ask me for details") or full (event-carried state transfer: the event includes the data, so consumers keep their own copy). Multi-step workflows can be coordinated by choreography (each service reacts to events) or orchestration (a central coordinator sends commands). EDA gives loose coupling and independent scaling, but costs debuggability and forces eventual consistency. Treat event schemas as public APIs: version them and evolve them compatibly.

Why It Exists#

In a request-driven system, the Order Service calls Payment, then Inventory, then Email, then Analytics. Every new feature adds another call. The Order Service must know about every downstream service, its latency adds up across all of them, and if Email is down, placing an order fails. The services are temporally coupled: they must all be up at the same time.

EDA flips the dependency. The Order Service publishes "OrderPlaced" once and is done. Payment, Inventory, Email and a new Fraud service each subscribe. Adding a consumer needs no change to the producer, and a consumer that is down catches up later from the broker. This page builds on Pub/Sub and Event Streaming.

How It Works#

Request-driven vs event-driven, in depth#

Before looking at events in detail, it helps to see in numbers why direct calls between many services hurt.

Availability multiplies. If placing an order synchronously calls five services, and each is available 99.9% of the time, the order path is available about 0.999^5 = 99.5% of the time. That is roughly 44 hours of failed checkouts a year instead of under 9. With 12 downstream calls, it falls to 98.8%. In an event-driven design, only the steps that must finish before the user gets an answer (save the order, perhaps authorise payment) stay on the synchronous path. The rest happen after the event is published, so their downtime delays work but does not fail the request.

Latency adds up. Sequential calls of 30 ms each across five services make 150 ms before the user sees anything, and the tail is worse: the p99 of a chain is dominated by whichever service has a bad moment. Calling in parallel helps, but the request still waits for the slowest. Publishing one event to a broker costs one write, typically 2 to 10 ms with replication.

Change coupling. Every new downstream feature in a request-driven design changes the upstream service's code, tests and deploy. In a company with 30 teams, the Order Service becomes a merge-conflict hotspot owned by everyone and no one. With events, the producer's contract is the event schema. New consumers subscribe without asking.

Load coupling. During a flash sale at 20 times normal traffic, a synchronous design forces every downstream service to scale to 20 times at the same instant. With a broker in between, non-urgent consumers (analytics, recommendations, email) can process the backlog over the next ten minutes at normal capacity, while only the critical path scales.

What request-driven still does better. Direct calls give an immediate answer, simple error handling (the caller sees the failure and can show it to the user), straightforward debugging (one stack trace, one trace), and strong consistency when the callee owns the data. Event-driven designs give all of that up for the steps that move behind the broker. The right design is usually a mix: commands and queries synchronous where the user is waiting, events for everything that can happen afterwards.

A useful way to see the spectrum, following Martin Fowler's 2017 essay "What do you mean by 'Event-Driven'?", is that "event-driven" covers four different patterns: event notification, event-carried state transfer, event sourcing and CQRS. They solve different problems and have different costs. This page covers the first two in depth and the communication style around them; the last two have their own page.

Events vs commands vs messages#

EventCommandMessage
MeaningA fact that happenedA request to do somethingThe transport envelope
NamingPast tense: OrderPlaced, PaymentFailedImperative: ChargeCard, ReserveStockEither
ReceiversZero, one or many; the producer does not know themExactly one intended handlerDepends on content
Can be refused?No, it already happenedYes, the handler may reject itn/a
CouplingProducer does not depend on consumersSender depends on the receiver's contractn/a
Typical channelTopic (pub/sub, stream)Queue or direct callAny broker

Mixing them up causes trouble. A "SendWelcomeEmail" event really is a command sent to the email service, which ties the user service to email behaviour. Publish UserRegistered instead, and let the email service decide.

Events, commands and queries, in depth#

The table above separates events from commands. In practice there is a third kind of message, the query ("what is the status of order 42?"), which expects a reply and changes nothing. Queries almost always belong on a synchronous API, not on a broker. Putting them on a queue adds latency and correlation bookkeeping for no benefit.

Who owns the contract. The direction of ownership is the most useful test:

  • An event's schema is owned by the producer. The producer publishes what happened in its own terms, and consumers adapt.
  • A command's schema is owned by the receiver. The payment service defines what ChargeCard must contain, and every sender must comply.

This tells you which team must approve a schema change, and it also exposes disguised commands. If the producer is designing an event's fields around what one specific consumer needs to do, it is really sending a command, and the coupling is the same as a direct call, just harder to see.

Kinds of events. Events themselves come in several shapes:

KindExampleWhat consumers getGood for
Fact or domain eventOrderPlaced with order detailsA business moment with intentTriggering reactions
Delta eventCartItemAdded {sku, qty}A change to applyFine-grained projections
State or snapshot eventCustomerState with the full recordThe latest full state of an entityReplicating data, compacted topics
SignalNightlyReportReadyA trigger with no dataKicking off batch jobs

Mixing shapes on one topic confuses consumers. A topic of full-state snapshots keyed by entity ID works well with Kafka log compaction (only the latest snapshot per key is kept), while a topic of facts should keep its full history.

Naming conventions. Name events in the past tense, after what the business would say happened: OrderPlaced, not OrderTableInsert, and PaymentDeclined, not PaymentStatusUpdated. A good test is whether a product manager would recognise the event name. Names that mirror database tables leak the internal schema, so every table change becomes a contract change.

Events cannot be rejected, but they can be ignored. A consumer that receives OrderPlaced for an item it cannot stock does not reject the event (the order was placed). It publishes its own event, StockReservationFailed, and the process reacts to that. This is the core habit of event-driven thinking: failures become new events, not error responses.

Event notification vs event-carried state transfer#

Event notification sends a minimal event: {"type":"CustomerUpdated","customer_id":42}. Consumers that care call back to the Customer Service to get the details.

  • Small events, a single source of truth, no copies to go stale.
  • But consumers depend on the producer's API at read time, and a burst of events causes a burst of callbacks.

Event-carried state transfer puts the state in the event: {"type":"CustomerUpdated","customer_id":42,"name":"Asha","tier":"gold","version":17}. Consumers store what they need locally.

  • Consumers work even when the producer is down, with no callback load.
  • But data is duplicated, events are larger, consumers hold eventually consistent copies, and the event schema becomes a bigger contract.

A common middle ground is to carry the fields most consumers need, plus a version, and let rare consumers call back for the rest. With Event Sourcing and CQRS, events also become the system of record, which is a separate, bigger step.

Notification vs state transfer, in depth#

The choice between thin and fat events looks like a payload-size question, but it is really about where reads happen and who depends on whom at runtime.

The callback storm. Suppose the Customer Service publishes 2,000 CustomerUpdated notifications per second during a bulk import, and 8 consumers each call back for details. That is 16,000 extra reads per second hitting the Customer Service, exactly when it is already busy writing. Worse, the callback reads the current state, not the state at the time of the event. If the customer changed twice in a second, both callbacks see the second version, which may be fine (it is the latest) or wrong (an audit consumer wanted both). Event notification therefore works best when consumers are few, events are rare, or consumers only need the latest state and can afford to coalesce callbacks.

Local replicas with state transfer. With event-carried state transfer, each consumer keeps a local table of the fields it needs. Suppose there are 50 million customers and a consumer keeps 200 bytes per customer: that is about 10 GB, easy for one database. The consumer now answers its own queries in about a millisecond with no network call, and it keeps working when the Customer Service is down. The price is that the copy is eventually consistent, and a bug in the consumer's projection silently corrupts its copy. Keep a way to rebuild: either replay a compacted state topic from the beginning, or bulk-load a snapshot and then apply events from a known offset.

Compacted topics as a replicated table. A Kafka topic keyed by customer_id with cleanup.policy=compact keeps at least the latest record for each key. A new consumer reads it from offset 0 and ends up with the full current state, then keeps up with live changes. This is how Kafka Streams builds a KTable and how many teams distribute reference data (product catalogues, prices, user profiles). Deleting a key is done with a tombstone (a record with a null value).

Full state vs delta. State transfer events can carry either the full new state (CustomerState with every field) or the changed fields plus the version. Full state is self-healing: a consumer that missed one event is correct again after the next one. Deltas are smaller but require every event to be applied in order, which pushes ordering and gap handling onto every consumer. Prefer full state for entity replication, and deltas only when the entity is large and changes are tiny (a 2 MB document where one paragraph changed).

Sensitive data. Copies are hard to delete. If a customer's address is carried in events to 12 consumers, a data-erasure request must be honoured in 12 stores plus the topic's retention. Options: carry only an ID for sensitive fields (notification style for those fields only), encrypt sensitive fields with a per-user key and delete the key on erasure ("crypto-shredding"), or keep retention short on topics that carry personal data.

The hybrid. Most mature systems carry the stable, widely needed fields in the event (IDs, status, amounts, version) and leave large or sensitive data behind an API or a claim check (a pointer to an object in blob storage). That gives most consumers autonomy while keeping events small and safe.

Choreography vs orchestration#

A multi-step business process (place order → charge payment → reserve stock → ship) can be coordinated in two ways.

Choreography: no central controller. Each service listens for events and emits its own. Payment hears OrderPlaced, charges, emits PaymentCaptured; Inventory hears that, and so on.

  • Very loose coupling; easy to add a reaction.
  • But the workflow exists only implicitly, spread across services. Answering "where is order 42 stuck?" means tracing events across many logs. Cyclic dependencies and compensation logic are easy to get wrong.

Orchestration: a coordinator (an orchestrator service, or a workflow engine such as Temporal, AWS Step Functions or Camunda) holds the workflow state and sends commands, then waits for replies.

  • The process is explicit, in one place: easy to see status, add timeouts and run compensations (the saga pattern).
  • But the orchestrator knows all participants and can become a central dependency, or a "god service" if business logic leaks into it.

Rule of thumb: choreography for simple, loosely related reactions (send email, update search, record analytics), and orchestration for business-critical workflows with ordering, timeouts and compensation (payments, bookings). Many systems use both. See Distributed Transactions, Pattern: Multi-Step Processes and Temporal and Workflow Engines.

Choreography, in depth#

Choreography means there is no single place that knows the whole process. Each service subscribes to the events it cares about and publishes events about what it did. The process emerges from these local rules, like dancers who each know their own steps and react to their partners.

A choreographed saga. A saga is a sequence of local transactions, each in one service, where every step has a compensating action that semantically undoes it if a later step fails. The idea comes from "Sagas" by Hector Garcia-Molina and Kenneth Salem (1987), written about long-lived database transactions. In a choreographed saga, the compensation is triggered by failure events.

Each service owns a small state machine: Payment knows that a StockReservationFailed for an order it charged means "refund", and Order knows that refund plus failure means "cancel". No one service holds the overall flow.

What makes choreography hard.

  • No single view of progress. To answer "why is order 42 still pending?", you must search the event logs of four services. Teams solve this with a tracking projection: a read-only consumer that listens to all events for an order and keeps a status table, effectively rebuilding the orchestrator's view without giving it control.
  • Timeouts are nobody's job. If Inventory never replies, no service is waiting. Someone must notice the silence. The usual fix is a deadline: the Order Service schedules a delayed message ("check order 42 in 15 minutes") and cancels the order if it has not reached a final state by then.
  • Cyclic and implicit dependencies. Payment subscribes to Inventory's events and Inventory subscribes to Payment's. Changing one event now affects a loop of services. Over time, the dependency graph can become a tangle no one has drawn.
  • Compensation is spread out. Every service must know which failure events require it to undo something. Adding a new step means updating the failure handling of several existing services.
  • Concurrency anomalies. Sagas lack isolation: other transactions can see intermediate states (a charged order whose stock was not reserved yet). See the deep dive below for countermeasures.

When choreography is the right tool. It shines when steps are independent reactions rather than a strict sequence: when an order is placed, send a confirmation email, update the search index, record analytics, and award loyalty points. None of these needs to know about the others, none needs compensation if another fails, and new reactions can be added freely. A rule of thumb many teams use: if a flow has more than three or four steps that must happen in order, or any step needs compensation, move it to orchestration.

Orchestration, in depth#

In orchestration, one component (the orchestrator or process manager) owns the state of each process instance and tells participants what to do with commands.

Where the orchestrator's state lives. A hand-built orchestrator stores a row per process instance (order_id, current_step, status, deadline) and advances it as replies arrive, which is essentially a state machine persisted in a database. Workflow engines do this for you: Temporal records every step's result in an event history and can rebuild the workflow's state after a crash by replaying that history through deterministic code; AWS Step Functions stores execution state for each step of a state machine defined in JSON; Camunda executes BPMN process models. See Temporal and Workflow Engines.

Orchestration does not mean synchronous. The commands and replies can travel over queues, so participants can be down for minutes without failing the process. The orchestrator simply waits. What orchestration centralises is knowledge of the flow, not runtime coupling.

Avoiding the god service. The orchestrator should decide what happens next, not how each step works. Business rules for pricing belong in the pricing service. If the orchestrator starts computing discounts, it becomes the new monolith. Keep it thin: sequence, timeouts, retries and compensation.

Combining both. A common production shape: an orchestrated workflow handles the critical path (charge, reserve, ship, with compensations), and when it finishes it publishes a fact event (OrderCompleted) that choreographed consumers react to (email, analytics, loyalty). See Pattern: Multi-Step Processes.

Benefits#

  • Decoupling: producers do not know consumers. Teams add features by subscribing, without changing the producer.
  • Independent scaling: each consumer scales on its own lag. Analytics can lag minutes behind while payments keep up in real time.
  • Resilience to downstream failures: if Email is down, orders still succeed; Email catches up from the broker.
  • Absorbing spikes: the broker buffers bursts.
  • Audit and replay: a retained event stream records what happened and can rebuild downstream stores.

Benefits, in depth#

The benefits listed above are real, but each holds only under specific conditions.

Decoupling is about knowledge, not about runtime. Producers do not know their consumers, so teams can add consumers freely. But consumers still depend on the event's fields and meaning. EDA moves coupling from "who calls whom" to "who depends on which fields of which event". It is a better kind of coupling (one-directional, contract-based, visible in a registry), but it is still coupling.

Independent scaling in practice. Each consumer group has its own lag and its own autoscaling signal. For example, a payment consumer may need 40 instances to keep lag under 1 second at peak, while an analytics consumer runs on 4 instances and is allowed to fall 20 minutes behind during peak and catch up at night. In a synchronous design, both would have to be sized for peak. The number of partitions sets the ceiling for a consumer group's parallelism: a topic with 48 partitions allows at most 48 active consumers in one group, so choose partition counts for the most demanding consumer.

Resilience is bounded by retention. A consumer that is down catches up later, but only if the broker still has the events. A queue with a 4-day retention protects you from a weekend outage, not from a two-week bug. Consumer lag alerts, measured in time, are what make this benefit real.

Replay creates new capabilities. With a retained log, a new service can build its state from history. A team launching a new search service can replay 90 days of ProductUpdated events into the index instead of writing a one-off export job. A team that discovers a bug in its projection can fix the code, reset its offsets and rebuild. This is one of the largest practical wins of a log-based backbone such as Kafka over a traditional queue, which deletes messages once consumed.

Team autonomy and Conway's law. Melvin Conway observed in 1968 that systems mirror the communication structure of the organisations that build them. Event-driven integration lets team boundaries line up with service boundaries: each team owns its services and the events they publish, and other teams integrate by subscribing rather than by asking for API changes. See Domain-Driven Design for Services for how to find those boundaries.

Audit trail. A retained stream of business facts (who placed, cancelled or refunded what, and when) is useful for compliance and debugging even if no service uses it as its system of record.

Costs#

  • Debugging and observability: one user action fans out into many asynchronous steps. Without correlation IDs and distributed tracing (OpenTelemetry context propagated in event headers), failures are hard to follow. See Observability.
  • Eventual consistency: right after placing an order, the "My orders" view may not show it yet. The UI must handle that (optimistic display, read-your-writes from the source).
  • Duplicates and ordering: consumers must be idempotent and tolerate reordering. See Delivery Semantics.
  • Hidden coupling through schemas: consumers depend on event fields. Changing a field can break unknown consumers.
  • Harder testing: end-to-end behaviour emerges from many services; contract tests and staging replays help.
  • Operational load: a broker cluster, DLQs, lag monitoring and schema registries to run.

Costs, in depth: eventual consistency#

The deepest cost of EDA is that the system is eventually consistent: after a write, other parts of the system reflect it after some delay. If no new writes happen, every replica and every consumer's copy eventually converges to the same state. The same model runs some of the most reliable systems ever built. DNS changes propagate over minutes to hours as caches expire. Email is store-and-forward and may take seconds or more to arrive. Both stay highly available because no part waits for every other part to agree.

How long is "eventually"? In an event-driven system, the inconsistency window is the sum of several delays:

StageTypical delay
Outbox relay (CDC)10 to 100 ms
Broker replication and consumer fetch5 to 50 ms
Consumer processing and write1 to 50 ms
Consumer lag during normal load0 to a few seconds
Consumer lag during an incident or backlogMinutes to hours

So a typical window is a fraction of a second, but you must design for the worst case: a consumer that is 2 hours behind. Measure the window directly by putting occurred_at in every event and recording now() - occurred_at when each consumer applies it.

What users notice. The classic complaint is "I placed an order and it is not on my orders page". The fixes, from simplest to most involved:

  • Read your own writes from the source. Right after a write, the client reads from the service that accepted it (or the primary database), not from a downstream projection.
  • Optimistic UI. The client shows the new order immediately from its own state, labelled "processing", and reconciles when the projection catches up.
  • Version tokens. The write returns a version or offset. The client passes it on the next read, and the read model waits briefly (or falls back to the source) until it has applied at least that version.
  • Honest UX. Show "your refund is being processed" rather than pretending it is instant.

See Consistency Models and CAP Theorem and PACELC for the theory behind these guarantees.

Costs, in depth: debugging, testing and operations#

Debugging asynchronous flows. In a request-driven system, one trace shows the whole call tree. In an event-driven system, a single click may produce a chain of events consumed minutes apart by different services. Three identifiers make it traceable:

  • Correlation ID: the same for every event that stems from one user action (the original request ID).
  • Causation ID: the event_id of the event that directly caused this one, so you can rebuild the tree.
  • Trace context: W3C traceparent headers carried in message headers, so OpenTelemetry can link consumer spans to producer spans. See Observability.

With these, a log search for one correlation ID shows every event and every consumer action for that order in order.

Testing. End-to-end tests across ten services are slow and flaky. Teams lean on:

  • Schema compatibility checks in CI against the registry, so a producer cannot merge a breaking change.
  • Consumer-driven contract tests (for example Pact, which supports message contracts): each consumer records the fields it relies on, and the producer's build verifies it still provides them.
  • Replay tests: run a consumer against a captured sample of production events (scrubbed of personal data) and compare its output with the previous version's.

Operations. Running an event backbone means owning a broker cluster, partition planning, schema registry, dead-letter queues, lag monitoring per consumer group, and replay tooling. A small team with three services may spend more on this than it gains. That is a reason to start with a managed service or to stay request-driven until the coupling costs are real.

Event schemas and versioning#

An event schema is a public API with unknown clients, so evolve it the way you would a public REST API.

  • Envelope: every event carries event_id (for dedup), event_type, schema_version, occurred_at, producer, correlation_id, and the entity key and version. The CloudEvents specification standardises these fields.
  • Schema format and registry: Avro, Protobuf or JSON Schema, stored in a schema registry (Confluent Schema Registry, AWS Glue Schema Registry, Apicurio) that rejects incompatible changes at publish time.
  • Compatibility rules: backward compatible (new consumers can read old events) and forward compatible (old consumers can read new events). Safe changes: add optional fields with defaults. Unsafe: removing or renaming fields, changing types or meanings.
  • Breaking changes: publish a new event type or version (OrderPlaced.v2) on a new topic, run both in parallel, migrate consumers, then retire the old one.
{
  "event_id": "9b2f7c1e-5a4d-4c1b-9e0a-3f6d2b8a7c10",
  "event_type": "OrderPlaced",
  "schema_version": 2,
  "occurred_at": "2026-12-01T10:15:30Z",
  "correlation_id": "req-71c2",
  "order_id": "ord-42",
  "order_version": 1,
  "customer_id": "cus-7",
  "total": { "amount": 4999, "currency": "INR" },
  "items": [{ "sku": "SKU-1", "qty": 2 }]
}

Schema evolution, in depth#

Events often outlive the code that wrote them: a topic with 30 days of retention, or an event store kept forever, holds events written by many versions of the producer. Every consumer must read all of them. That makes schema evolution a harder problem than REST API versioning, where only current requests matter.

Compatibility modes. Schema registries such as Confluent Schema Registry check each new schema version against earlier ones using a configured mode:

ModeGuaranteeAllowed changes (Avro)Upgrade order
BACKWARD (common default)Consumers on the new schema can read data written with the previous oneDelete fields, add fields with defaultsUpgrade consumers first
FORWARDConsumers on the old schema can read data written with the new oneAdd fields, delete fields that have defaultsUpgrade producers first
FULLBoth directionsAdd or delete only fields with defaultsAny order
Transitive variants (for example BACKWARD_TRANSITIVE)Checked against all earlier versions, not just the lastSame as aboveNeeded when consumers replay old data

For event streams that are replayed, the transitive modes matter: a consumer reading from the beginning of a compacted topic may meet version 1 and version 7 of the same event type in one pass.

How each format handles change.

  • Avro resolves the writer's schema against the reader's schema by field name. Defaults fill missing fields. The registry stores the writer's schema, and each message carries a small schema ID (5 bytes in the Confluent wire format: a magic byte and a 4-byte ID), so payloads stay compact.
  • Protobuf identifies fields by number, not name. Never reuse a field number. Mark removed numbers as reserved. New fields are ignored by old readers. In proto3, unset scalar fields read as zero values, so "missing" and "zero" look the same unless you use optional or wrapper types.
  • JSON Schema is the most flexible and the easiest to get wrong. JSON has no binary schema ID by default, and "additional properties allowed" decides whether adding a field is compatible. Many teams with JSON payloads use the CloudEvents envelope with a dataschema URI and validate in CI.

Expand and contract. To rename a field safely: (1) add the new field alongside the old one and write both, (2) migrate consumers to read the new field, (3) once no consumer reads the old field (check the registry's consumer list or contract tests), stop writing it, and (4) remove it in a later version. The same sequence works for changing a field's type: add a new field of the new type, never change the type in place. See Online Data Migrations and Schema Evolution.

Semantic changes are the dangerous ones. A registry checks structure, not meaning. Changing amount from "rupees" to "paise" while keeping it an integer passes every compatibility check and silently corrupts every consumer. Treat a change of meaning as a breaking change: new field name (amount_minor) or new event version.

Upcasting. Consumers (or a shared library) can convert old event versions to the latest shape when reading, so business code handles only one version. This is common in event-sourced systems where old events cannot be rewritten. The upcaster chain (v1 to v2 to v3) must be kept as long as old events exist.

Topologies and topic design#

Beyond choreography and orchestration, there are a few structural choices that decide how an event-driven system feels to operate.

Broker topology vs mediator topology. Mark Richards describes two event-driven topologies in "Software Architecture Patterns" (O'Reilly). In the broker topology, events flow through a lightweight broker and every processor reacts and publishes, which is choreography. In the mediator topology, an initial event goes to a mediator that splits it into steps and dispatches them to processors, which is orchestration. The vocabulary differs, but the trade-off is the same: flexibility and loose coupling against central control and visibility.

Topic granularity. Three common layouts:

LayoutExampleProsCons
Topic per event typeorders.placed, orders.cancelledConsumers subscribe to exactly what they needNo ordering between event types for one order
Topic per entity (aggregate)orders with many event types, key = order_idAll events for one order are orderedConsumers filter out types they ignore
One bus with routing rulesEventBridge bus with rule filtersCentral routing, easy cross-account deliveryLess control over ordering and replay

If consumers must see OrderPlaced before OrderCancelled for the same order, both must be on the same partition of the same topic. That makes topic per entity, keyed by entity ID the usual default for business events, with schema registries configured to allow several event types per topic (Confluent's TopicRecordNameStrategy and RecordNameStrategy exist for this).

Partition count. Partitions cap consumer parallelism and are hard to change for keyed topics, because adding partitions changes which partition a key hashes to and breaks per-key ordering across the change. Size for two to three years of growth. For example, if the slowest important consumer processes 500 events per second per instance and peak is 20,000 events per second, you need at least 40 partitions; choose 64 or 96 to leave room.

Event routing and filtering. Content-based routing (EventBridge rules, RabbitMQ topic exchanges, Google Pub/Sub subscription filters) lets each consumer receive only matching events, which saves consumer CPU but moves logic into infrastructure configuration. Keep filters simple and versioned with the consumer's code.

Internal vs public topics. Separate topics a service uses for its own internal processing from topics that are part of its public contract. Only public topics get strict compatibility rules and documentation, so teams can refactor internals freely.

Worked example: an e-commerce event backbone#

Consider a retailer with 30 services and 25 teams. Peak traffic is 3,000 orders per second during a sale, with an average of 300.

Event volume. Each order produces about 8 business events over its life (placed, payment authorised, captured, stock reserved, shipment created, shipped, delivered, and sometimes refunded). Add 15 product and price updates per second at normal times, bursting to 5,000 per second during catalogue imports, and about 40,000 click-stream events per second from the website. The click stream belongs on a separate analytics cluster. The business events peak at about 24,000 per second (3,000 x 8, an upper bound since events are spread over days), and the average is far lower.

Sizing. At 1 KB per business event, 24,000 per second is 24 MB/s inbound. With replication factor 3, the brokers write 72 MB/s in total, and each of, say, 10 consumer groups reads 24 MB/s, so 240 MB/s outbound. A six-broker Kafka cluster handles this comfortably. Thirty days of retention of the average rate (about 3,000 events per second, or 3 MB/s) is about 7.8 TB before replication and 23 TB after, which argues for tiered storage or a shorter retention on high-volume topics.

Topic layout. orders (key order_id, 96 partitions), payments (key order_id, so payment events line up with order events by key), inventory (key sku), catalog (compacted, key product_id), customers (compacted, key customer_id). Each topic belongs to the team that owns the producing service.

Coordination. Checkout is an orchestrated workflow in Temporal: authorise payment, reserve stock, confirm the order, with compensations (void authorisation, release stock). When it completes, the order service publishes OrderConfirmed. Email, loyalty points, search ranking signals, the data warehouse and fraud scoring consume it by choreography.

Consistency choices. The checkout path reads stock from the inventory service synchronously, because overselling is expensive. The product page reads stock from a cached projection that may be a few seconds stale, labelled "only 3 left" rather than an exact live number. The "My orders" page reads from a projection with a version-token fallback.

Failure scenario. The email provider is down for 40 minutes. The email consumer's lag grows to 40 minutes x 300 orders per second x 60 = about 720,000 events. Nothing else is affected. When the provider returns, the consumer scales from 4 to 20 instances and drains the backlog in roughly 10 minutes, while dedup keys stop a retry from sending duplicate confirmations. In a request-driven design, the same outage would either fail checkout or require ad-hoc retry code in the order service.

Managed and serverless event routing#

Not every event-driven system needs its own Kafka cluster. Cloud providers offer building blocks that cover most needs for small and medium systems.

SNS plus SQS fan-out on AWS. A producer publishes to one SNS topic. Each consuming service owns an SQS queue subscribed to that topic, optionally with a filter policy on message attributes. Each queue gives its consumer its own retry, visibility timeout, dead-letter queue and scaling, and a slow consumer cannot affect the others. This pattern trades replay (SQS deletes messages once processed) for very low operational effort.

EventBridge. An event bus receives JSON events, and rules match on event content (source, detail-type, any field in the body) and route matches to targets such as Lambda functions, SQS queues, Step Functions or HTTP endpoints. It also receives events from many SaaS providers and AWS services directly. It offers an archive with replay and a schema registry that can infer schemas from events. It suits integration-style events at moderate volume, with per-event pricing rather than per-broker pricing.

Google Cloud Pub/Sub and Eventarc; Azure Event Grid and Service Bus. On Google Cloud, Pub/Sub gives topics with subscriptions, filtering, ordering keys and seek-based replay within retention, and Eventarc routes events from Google services to Cloud Run and other targets. On Azure, Event Grid routes discrete events with push delivery and filters, while Service Bus provides queues and topics with sessions and duplicate detection, and Event Hubs provides a Kafka-compatible streaming endpoint.

Serverless consumers. Functions triggered by events (Lambda, Cloud Run functions, Azure Functions) scale automatically with event volume and cost nothing when idle. The usual cautions apply with more force: functions are retried on failure, so they must be idempotent; concurrency can spike to hundreds of instances and overwhelm a database behind them, so cap concurrency; and cold starts add latency to the first events after a quiet period.

Choosing. A rough guide: use the cloud's managed fan-out (SNS plus SQS, Pub/Sub, Event Grid) when you need per-consumer queues and do not need long replay; use a managed Kafka (Amazon MSK, Confluent Cloud, Event Hubs for Kafka) or Pulsar when you need ordered, replayable logs at high volume; and self-host only when cost at scale or control justifies a dedicated platform team. See Pub/Sub and Event Streaming for the broker-level comparison.

Governing events at scale#

With 5 services and 20 event types, everyone knows what exists. With 200 services and 2,000 event types, nobody does, and the system drifts into duplicated, half-documented events with unknown consumers. Governance keeps the decoupling benefit from turning into chaos.

An event catalogue. Every public event type gets an entry with: the owning team, a one-paragraph business meaning, the schema and its versions, the topic and partition key, the retention, whether it carries personal data, and its known consumers. AsyncAPI documents can describe topics, messages and schemas in a machine-readable format, similar to what OpenAPI does for REST, and catalogue tools can be generated from them.

Knowing who consumes what. Consumer groups in Kafka, subscriptions in Pub/Sub and rules in EventBridge are all discoverable. A periodic job that maps each topic to its consumer groups and their owning teams is cheap, and it answers the question every producer asks before a change: "who will I break?". Combine it with consumer-driven contract tests so the answer is checked in CI, not only looked up.

Ownership rules. Three rules prevent most governance problems:

  1. Each event type has exactly one producing service.
  2. Public event types change only through the registry with compatibility checks, and breaking changes require a new version with a published retirement date for the old one.
  3. Personal data in events is tagged in the schema (for example with a field-level pii annotation), so retention and erasure tooling can find it.

Metrics per event flow. For each important flow (for example "order placed to confirmation email sent"), track the end-to-end delay from occurred_at to the final effect, the error and DLQ rate per consumer, and the volume per event type. Sudden volume changes are often the first sign of a producer bug, such as a loop that republishes the same state on every save.

Cost visibility. Event backbones become shared infrastructure, and shared infrastructure grows without owners. Attribute broker storage and throughput to topics and teams. A single team's debug topic with 30 days of retention at 50 MB/s holds about 130 TB, a cost that should be visible to someone.

Moving from request-driven to event-driven#

Few teams start event-driven. Most migrate a working system, and the migration has its own failure modes.

  1. Start with one high-value, low-risk flow. Good first candidates are side effects that are already slow or unreliable: confirmation emails, search indexing, analytics exports. Their consumers can tolerate delay, and mistakes do not lose money.
  2. Publish events without changing the existing calls. The producer starts writing OrderPlaced through an outbox while still making its old synchronous calls. New consumers run in shadow mode: they process events and write results to a side table or log, and you compare their output with what the synchronous path produced.
  3. Switch one consumer at a time. When the shadow output matches for a week or so, remove that synchronous call and let the consumer take over. Keep a feature flag so the call can be restored quickly.
  4. Use CDC for legacy systems you cannot change. If the legacy monolith's code is too risky to touch, read its database log with Debezium and publish change events. These are low-level (orders row changed), so put a small translation service in front that turns them into business events (OrderPlaced). See Change Data Capture and the Outbox Pattern.
  5. Retire the old paths deliberately. A half-migrated system with both a synchronous call and an event for the same effect is the worst state: double emails, double updates, and confusion over which path is authoritative.

This is a version of the strangler fig approach: grow the new event-driven pieces around the old system until the old paths can be removed. See Monolith vs Microservices.

Anti-patterns that make event-driven systems fail#

  • The event-driven monolith. Services that cannot be deployed independently because a change to one event requires coordinated releases of five consumers. Usually caused by events that mirror internal tables, or by consumers that depend on fields they should not.
  • Request-reply over a broker for everything. Sending a command on a queue and blocking until a reply arrives on another queue gives you all the costs of async (correlation, timeouts, extra hops) and none of the benefits. If the caller must wait, use a synchronous API.
  • Events as remote procedure calls. RecalculateCustomerScore published "as an event" for one consumer. It is a command, so send it on a command queue owned by the receiver.
  • Unbounded fan-out chains. Event A triggers B, which triggers C, D and E, each of which triggers more. One user action ends up producing hundreds of events, and a bug in one step causes an event storm. Limit chain depth, and watch for loops (a service consuming its own events indirectly).
  • Shared mutable topics. Several services publishing the same event type to the same topic, with slightly different meanings. Each event type should have exactly one owning producer.
  • No dead-letter handling. One malformed event blocks a Kafka partition for hours because the consumer retries it forever.
  • Ignoring time. Consumers that assume events arrive in real time break when they replay a backlog: a "send a reminder if not paid within 15 minutes" rule fires for thousands of orders during replay. Base time-based rules on the event's occurred_at, and skip side effects during replays.

When to Use It#

  • Many independent consumers react to the same business facts.
  • Teams need to add features without coordinating changes to a central service.
  • Workloads where parts can lag (notifications, search indexing, analytics, recommendations).
  • Integrating services or data stores, with the event stream as the shared backbone.

When NOT to Use It#

  • The caller needs an immediate, consistent answer (checking a balance before a withdrawal).
  • Small systems or a single team, where direct calls or a modular monolith are simpler. See Monolith vs Microservices.
  • Strongly consistent multi-step operations where eventual consistency is not acceptable to the business.
  • Teams without tracing, schema governance or on-call for the broker.

How to Implement It#

  1. Identify domain events from the business process (event storming helps); name them in past tense.
  2. Decide notification vs state transfer per event, based on consumer needs.
  3. Define schemas with an envelope and register them with compatibility checks.
  4. Publish reliably with the outbox pattern. See Change Data Capture.
  5. Make consumers idempotent and order-tolerant using entity versions.
  6. Choose coordination: choreography for reactions, orchestration for critical workflows with compensations.
  7. Propagate correlation IDs and trace context in headers; monitor lag and DLQs per consumer.
  8. Design the UI for eventual consistency.
TechnologyFits when
Kafka, Pulsar, KinesisEvent backbone with retention and replay
SNS + SQS, Google Pub/Sub, Azure Service BusManaged fan-out with per-consumer queues
Amazon EventBridgeEvent routing by rules between AWS services and SaaS
Temporal, AWS Step Functions, CamundaOrchestrated workflows
Schema registries, CloudEventsSchema governance and a common envelope

Trade-offs#

ChoiceGainCostPick when
Event-drivenDecoupling, independent scaling, resilienceEventual consistency, harder debuggingMany consumers, evolving features
Request-drivenSimple, immediate answersTemporal coupling, cascading failuresQueries and strongly consistent steps
Event notificationSmall events, one source of truthCallback load and runtime couplingFew consumers, large or sensitive data
Event-carried stateConsumers autonomousData copies, bigger contractsMany consumers needing the same fields
ChoreographyLoose couplingImplicit workflow, hard to traceSimple reactions
OrchestrationExplicit flow, timeouts, compensationCentral coordinatorBusiness-critical multi-step flows
Topic per entity, keyed by IDPer-entity ordering across event typesConsumers filter types they ignoreBusiness events for aggregates
Compacted state topicsNew consumers bootstrap full stateOnly the latest value per keyReference data, entity replication
Full-state events vs deltasSelf-healing consumersLarger eventsEntity replication
Transitive schema compatibilitySafe replay of old eventsStricter evolution rulesLong retention or event stores
Tracking projection for choreographyVisibility without central controlOne more consumer to runChoreographed flows that need status

Common Pitfalls#

  • Publishing commands disguised as events (SendInvoiceEmail).
  • Dual writes (database then publish) that lose events on crashes.
  • Long choreography chains no one can explain or debug.
  • Breaking schema changes deployed without a registry or versioning.
  • No correlation IDs, so a failed order cannot be traced.
  • Expecting the read side to be instantly up to date.
  • Callback storms when thin notifications trigger many consumers to call the producer at once.
  • Changing a field's meaning (units, currency) while keeping its type, which passes every compatibility check.
  • Adding partitions to a keyed topic and breaking per-key ordering.
  • Time-based rules that fire during replays because they use processing time instead of occurred_at.
  • Half-migrated flows that run both a synchronous call and an event consumer for the same effect.
  • Choreographed sagas with no deadline, so stuck orders stay pending forever.

Real-World Examples#

Amazon EventBridge is AWS's managed event bus for routing events between AWS services, SaaS applications and your own services, based on rules.

Netflix has written about using Kafka-based event pipelines to move data between its services and its data platform.

Martin Fowler's 2017 essay "What do you mean by 'Event-Driven'?" separated event notification, event-carried state transfer, event sourcing and CQRS, which is now the common vocabulary for these patterns.

Confluent Schema Registry, the Apicurio registry and AWS Glue Schema Registry all enforce compatibility rules at publish time, and Kafka Streams uses compacted topics to build tables from event streams.

In the Interview#

Event-driven design in interview problems#

Most system design prompts have at least one place where events are the right tool and at least one where they are the wrong one. Interviewers look for whether you can tell the two apart.

  • E-commerce or food delivery. Keep "place order" synchronous up to the point where the order is durably recorded. Publish OrderPlaced through an outbox. Orchestrate payment and stock with compensations. Let notifications, analytics and search react by choreography.
  • Ticket booking. Seat reservation must be synchronous and strongly consistent (a hold with a TTL in the database or Redis). Confirmation emails, analytics and waitlist updates can be events. See Design a Ticket Booking System.
  • Social feeds. PostCreated fans out to feed builders, notification services and search indexers. Discuss fan-out on write versus fan-out on read for celebrity accounts. See Design a News Feed.
  • Ride sharing. Location updates are a high-volume stream (at-most-once is fine for intermediate positions). Trip state transitions (TripRequested, DriverAssigned, TripCompleted) are business events that drive billing and notifications.

When you introduce events, say four things: the event name and owner, what it carries (thin or fat), how it is published reliably (outbox), and how consumers handle duplicates and ordering. Then name the user-visible consistency effect and how you hide it.

Deep Dive: Event granularity, domain events vs integration eventsShow

Domain events vs integration events. Inside a service, fine-grained domain events (ShippingAddressChanged, ItemAddedToCart) model the business closely. Publishing all of them exposes internals and makes every refactor a breaking change. Many teams publish a smaller, stable set of integration events for other services (OrderPlaced, OrderCancelled), mapped from internal events, as an explicit public contract. This is the same idea as an anti-corruption layer in domain-driven design.

Granularity. Very fine events (FieldXChanged) force consumers to rebuild state from many events; very coarse ones (EverythingAboutOrderChanged with the full aggregate) are easy to consume but hide intent. Prefer business-meaningful events, with enough state for most consumers.

Event-driven does not mean event sourcing. EDA is about communication between services. Event sourcing is about storing a service's own state as an event log. You can do either without the other.

The "event soup" failure. As event types multiply without ownership, nobody knows who consumes what. Mitigate with an event catalogue (owner, schema, consumers), tooling such as AsyncAPI documents, and lineage from the schema registry.

Deep Dive: Saga isolation anomalies and countermeasuresShow

A database transaction is ACID: atomic, consistent, isolated and durable. A saga keeps atomicity in a weaker form (every step either completes or is compensated) and durability, but it gives up isolation. Each local transaction commits on its own, so other requests can see and act on the saga's intermediate states. Garcia-Molina and Salem's 1987 paper accepted this explicitly: sagas trade isolation for the ability to run long processes without holding locks.

Three anomalies appear.

  • Lost update. Saga A reads an order, saga B updates it, and A then overwrites B's change without seeing it.
  • Dirty read. Saga A has charged a card and reserved stock, then fails and starts compensating. Meanwhile, a loyalty service reads "order charged" and awards points for an order that is about to be refunded.
  • Fuzzy (non-repeatable) read. Two steps of one saga read the same data and see different values because another saga changed it in between.

Countermeasures. Chris Richardson's book Microservices Patterns (Manning, 2018) collects a set of standard countermeasures, most of which come from older work on long-running transactions:

  • Semantic lock. A step sets a flag such as status = 'PENDING_APPROVAL' on the records it touches. Other sagas that see the flag either wait, fail, or treat the record carefully. The lock is released when the saga completes or compensates. This is an application-level lock and needs timeouts to avoid locking forever.
  • Commutative updates. Design operations so the order of application does not matter: debit and credit on a ledger commute, while "set balance to X" does not.
  • Pessimistic view. Reorder the saga's steps to reduce harm from dirty reads. For example, do the step that can fail (stock reservation) before the step whose effect is visible to other services (awarding loyalty points), so a compensation never has to undo something already seen.
  • Reread value. Before overwriting a record, reread it and check it has not changed (optimistic concurrency with a version number). If it changed, abort and restart the saga.
  • Version file. Record the operations applied to a record so that operations arriving out of order can be reordered. For example, a "cancel" that arrives before its "authorise" is held until the authorise arrives, and then both are applied as a no-op.
  • By value. Choose the mechanism per request based on business risk. Low-value orders run as plain sagas, while high-value ones use a distributed transaction or a manual approval step.

Pivot transactions. In a well-structured saga, steps fall into three groups: compensatable steps before the pivot (can be undone), the pivot step itself (the point of no return, for example capturing a payment or shipping a parcel), and retriable steps after the pivot (must eventually succeed, so they are retried until they do, for example sending a confirmation). Designing a saga means finding the pivot and making sure everything after it can be retried safely and idempotently.

Choreography makes these harder to see. With orchestration, the semantic lock, the pivot and the compensation order are all visible in one workflow definition. With choreography, they are spread across services, and reviewing whether a dirty read can happen means tracing event subscriptions across teams. This is the deeper reason why business-critical sagas usually move to orchestration as they grow.

Key Takeaways#

  • Events are past-tense facts with unknown consumers; commands ask one receiver to act.
  • Event notification keeps events thin; event-carried state transfer lets consumers work independently with local copies.
  • Use choreography for simple reactions and orchestration for critical workflows with timeouts and compensation.
  • EDA buys decoupling, independent scaling and resilience at the cost of eventual consistency and harder debugging.
  • Treat event schemas as public APIs: envelope fields, a registry, compatible changes and versioned breaking changes.
  • Keep queries and user-facing commands synchronous; move everything that can happen afterwards behind events.
  • Thin events cause callback load and runtime coupling; fat events cause copies to manage. A hybrid with IDs, status and version is the common middle.
  • Sagas give up isolation: use semantic locks, commutative updates, reordered steps and a clear pivot step.
  • Measure the consistency window with occurred_at, and hide it with read-your-writes, optimistic UI or version tokens.
  • Evolve schemas with expand-and-contract, transitive compatibility for replayed topics, and new versions for any change of meaning.