Course contents

10. Software Architecture Lesson 9 of 10

Event-Driven Architecture

Replace a synchronous call chain with events: shorter request paths, outages become backlogs. Then meet commands vs events, choreography and invisible failures.

17 minIntermediate9 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • An event announces a fact in the past tense; the publisher does not know or care who reacts.
  • A command asks one owner to act and can be rejected; send it to that owner’s queue.
  • Events take work off the request path and turn consumer outages into backlogs.
  • Choreography scatters a process across services; orchestration makes it explicit but central.
  • Failures surface downstream and later: make consumers idempotent, carry correlation ids and trace context, alert on lag.
  • Keep synchronous calls for answers the caller needs before it can continue.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

In an event-driven architecture, services communicate mainly by publishing events (records that something happened, such as OrderPlaced) and reacting to events published by others, instead of calling each other and waiting. A broker (topic, log or bus) sits between producers and consumers, stores the events and delivers them to every interested subscriber.

Why it exists

Synchronous call chains couple services in three ways: in time (the callee must be up now), in latency (the caller waits for the sum of all calls) and in knowledge (the caller must know every callee and its API). Adding a new reaction to an order means changing and redeploying Checkout. Events remove those couplings for work that does not have to happen before the caller can answer: confirmation emails, loyalty points, analytics, search indexing, notifications.

How it works

Events vs commands.

Event Command
Meaning A fact: something happened A request: please do something
Naming Past tense: OrderPlaced Imperative: CapturePayment
Owner of the contract Publisher Receiver
Receivers Zero, one or many; publisher doesn't know Exactly one logical handler
Can be rejected? No, it already happened Yes
Typical channel Topic / log with subscriptions Queue owned by the receiver

Delivery. Brokers deliver at least once: a consumer that does not acknowledge in time (crash, timeout) gets the message again. Consumers must therefore be idempotent, for example by storing processed message ids in the same transaction as their effect (inbox pattern). Producers publish reliably with a transactional outbox so the database change and the event cannot diverge.

Event types. Domain events are internal to a bounded context; integration events are published contracts for other services and must be versioned like public APIs. Event notifications carry an id and invite consumers to call back for details; event-carried state transfer carries the data so consumers need no callback.

Choreography vs orchestration. In choreography, each service reacts to events and publishes its own; the process emerges from the subscriptions. In orchestration, a coordinator (saga orchestrator, workflow engine such as Temporal, Azure Durable Functions or a MassTransit/NServiceBus saga) sends commands step by step and tracks process state, including compensations.

// MassTransit-style consumer: an event handler that is safe to run twice
public sealed class AwardPoints(LoyaltyDb db) : IConsumer<OrderPlaced>
{
    public async Task Consume(ConsumeContext<OrderPlaced> ctx)
    {
        var id = ctx.MessageId!.Value;
        if (await db.Processed.AnyAsync(p => p.MessageId == id)) return;   // duplicate delivery
        db.Points.Add(new PointsEntry(ctx.Message.CustomerId, ctx.Message.Total));
        db.Processed.Add(new ProcessedMessage(id));
        await db.SaveChangesAsync();                                       // effect + marker, one transaction
    }
}

When to use it

  • Work that reacts to something that already happened and need not finish before the user gets an answer.
  • Several independent consumers of the same fact, owned by different teams.
  • Consumers that must survive producer or consumer outages (durable subscriptions absorb them).
  • Integration across bounded contexts where you want to avoid synchronous dependencies.
  • Feeding read models, search indexes, caches and analytics.

When not to

  • The caller needs the result to continue: stock checks, card authorisation, permission checks.
  • Strong, immediate consistency across services is a hard requirement.
  • Simple systems where a function call or one synchronous request is clearer.
  • When the team cannot yet operate a broker, idempotent consumers and distributed tracing.

Trade-offs

Choice You gain You pay
Events instead of sync calls Shorter request path, availability isolation, open for new consumers Eventual consistency, duplicates, harder debugging
Choreography No central coordinator; services stay autonomous Process is implicit; changes span teams; hard to answer "where is X?"
Orchestration Explicit, observable process with compensations A central component that knows every step
Fat events (state transfer) Consumers need no callbacks Larger contracts, more coupling to the publisher's data
Thin events (notifications) Small, stable contracts Callbacks put load and coupling back on the publisher

Alternatives

  • Synchronous request/response (HTTP, gRPC): simplest when the caller needs the answer.
  • Command queues (point-to-point): asynchronous but with one known receiver; good for work distribution.
  • Shared database: tempting, couples schemas; avoid across service boundaries.
  • Batch/ETL: for analytics where minutes or hours of latency are fine.

Failure modes

  • Invisible failures. A slow or broken consumer causes no error at the producer; the lesson's Checkout shows zero errors while Loyalty redelivers and double-awards points.
  • Duplicates and reordering. At-least-once delivery and retries produce duplicates; partitions and retries reorder. Idempotent handlers and per-key ordering address them.
  • Poison messages. A message that always fails blocks or loops; cap deliveries and send it to a dead-letter queue.
  • Event chains nobody understands. Deep choreography makes changes risky; document flows and consider orchestration for long processes.
  • Commands disguised as events. SendWelcomeEmail on a topic couples the publisher to one consumer's behaviour.
  • Dual writes. Committing to the database and publishing separately loses events on crashes; use an outbox.

In production

Choose the broker by semantics: queues/topics with subscriptions (Azure Service Bus, Amazon SNS+SQS, RabbitMQ) or a log (Kafka, Azure Event Hubs) when replay and ordering per key matter. In .NET, MassTransit, NServiceBus, Wolverine or Brighter handle retries, outbox and sagas. Carry a correlation id and W3C trace context in message headers so OpenTelemetry traces span producer and consumers. Monitor per subscription: backlog size, age of the oldest message, redelivery and dead-letter rates. Version integration events and keep them backward compatible.

Common misconceptions

  • "Event-driven means real-time." It means asynchronous; consumers may lag by milliseconds or hours.
  • "Events make services fully independent." They still depend on the event contract and its meaning.
  • "The broker guarantees exactly once." End-to-end effects are at least once unless consumers are idempotent.
  • "Event-driven = event sourcing." One is about communication between services, the other about persistence inside one.

Interview angle

Draw the synchronous chain first, point out the latency sum and the availability product, then move non-essential work behind an event. Name the delivery semantics and how you make consumers idempotent, how you publish reliably (outbox), and how you observe the flow (correlation ids, tracing, lag alerts). Contrast choreography and orchestration and say which you would pick for a long, multi-step process with compensations (usually orchestration). Keep the steps the user waits for synchronous.

Model assumptions

The simulation is a simplified model, not a benchmark. Orders arrive as a Poisson stream (40/s, later 60/s in the challenge). Checkout has 64 workers and 15 ms of work; the orders database writes in ~8 ms. Synchronous services have 16 workers each (Email 80 ms, Loyalty 40 ms, Analytics 30 ms, lognormal cv 0.3) and are called in sequence. The topic copies each published event into one subscription per consumer; each subscription delivers to its own workers and redelivers messages not acknowledged within 1 s. The degraded Loyalty worker takes 30 times longer per message. The choreography chain (PaymentCaptured, Shipping, ShipmentDispatched) is a scripted illustration, because simulated workers do not publish further events. Numbers show behaviour and orders of magnitude only.

The lesson as textEvery step of the simulation, written out.
  1. 1. Checkout tells everyone what to do

    Shoppers place about 40 orders per second. Checkout saves the order and then calls three services, one after another: Email (send confirmation, ~80 ms), Loyalty (award points, ~40 ms) and Analytics (record the sale, ~30 ms).

    The shopper waits for all of it. Median latency is around 240 ms, most of it spent on work the shopper does not need to wait for. And Checkout must know every downstream service, their APIs and their failure modes.

    Scene: Checkout saves each order and then calls Email, Loyalty and Analytics in sequence. Orders take about 240 ms and all succeed.

    Key idea: In a synchronous call chain, the caller’s latency is the sum of everyone it calls, and it must know all of them.

  2. 2. Loyalty goes down, checkout goes down

    One second in, the Loyalty service crashes. Points are a nice-to-have, but Checkout calls Loyalty synchronously, so every order now fails at that step: the shopper sees an error even though the order was saved and the email may already be on its way.

    Availability multiplies along a synchronous chain: if each of four services is up 99.9% of the time, the chain is up at most about 99.6%. The least important dependency decides whether you can take money.

    Scene: Loyalty crashes after one second. From then on every checkout fails at the Loyalty call; the error rate jumps.

    Key idea: Synchronous dependencies couple availability: any callee that fails takes the caller down with it.

  3. 3. Publish an event instead

    Checkout now saves the order and publishes one event, OrderPlaced, to a topic, then answers the shopper. Email, Loyalty and Analytics each subscribe: the topic copies the event into each one’s subscription, and their workers process it in their own time.

    The shopper’s latency drops to roughly a third: only Checkout’s own work is on the request path. Checkout no longer knows who listens; a new consumer subscribes without a Checkout deploy.

    An event states a fact in the past tense, owned by the publisher: *an order was placed*. It is not a request: Checkout does not expect Loyalty to do anything in particular. (Publishing reliably after the database commit needs an outbox; see Transactional Outbox.)

    Scene: Checkout saves the order, publishes OrderPlaced to a topic and answers. The topic copies each event into the Email, Loyalty and Analytics subscriptions, whose workers process them independently. Latency drops to about a third and nothing fails.

    Key idea: Event-driven: the producer announces what happened and moves on; consumers decide what to do about it.

  4. 4. Temporal decoupling: consumers can be down

    Same failure as before: one second in, the Loyalty worker crashes, and it stays down for three seconds.

    This time no shopper notices. Checkout publishes as usual; the topic keeps filling the Loyalty subscription, whose backlog grows. Email and Analytics carry on. When Loyalty comes back it works through the backlog and catches up within moments.

    That is temporal decoupling: producer and consumer do not need to be up at the same time. The cost is that the points arrive late, which here is fine.

    Scene: The Loyalty worker is down from one to four seconds. Checkout keeps succeeding; the Loyalty subscription builds a backlog, which drains quickly once the worker recovers.

    Key idea: With events, a consumer outage becomes a backlog, not a user-facing error.

  5. 5. Events and commands are different messages

    Payment capture is different: Checkout needs it done, by exactly one service, and wants to hear if it fails. That is a command, CapturePayment, sent to a queue owned by Payments. One handler, imperative name, can be rejected.

    Compare the two in the scene. Each OrderPlaced event on the topic becomes three copies, one per subscriber, and the publisher does not care how many there are. Each CapturePayment command is delivered to one Payments worker.

    Mixing them up causes trouble: “events” that are really commands in disguise (SendWelcomeEmail published to a topic) recreate coupling, because the publisher now depends on a specific consumer doing a specific thing.

    Scene: Checkout now also sends a CapturePayment command to a queue owned by Payments. Each OrderPlaced event is copied to three subscriptions, while each CapturePayment command is delivered to one Payments worker.

    Key idea: Events: past tense, owned by the publisher, any number of listeners. Commands: imperative, owned by the receiver, exactly one handler.

  6. 6. Choreography: nobody owns the flow

    Services can react to each other’s events to form a whole business process with no central coordinator. Payments captures the money and publishes PaymentCaptured; Shipping reacts and publishes ShipmentDispatched; Email reacts to that and tells the shopper. This is choreography.

    Each service stays small and independent. But the process now exists only as the sum of subscriptions: to answer “where is order 81?” or “what happens after payment?” you have to read the code of four services. Changing the order of steps touches several teams.

    The alternative is orchestration: one component (a saga or workflow engine) sends commands step by step and tracks state. The flow becomes explicit and observable, at the cost of a central piece that knows everyone. Scripted illustration of the chain.

    Scene: A scripted chain: Payments consumes the command and publishes PaymentCaptured; Shipping reacts and publishes ShipmentDispatched; the Email subscription receives it and the Email worker notifies the shopper. No component coordinates the whole flow.

    Key idea: Choreography decouples services but scatters the process; orchestration makes the process explicit but centralises knowledge.

  7. 7. Failures you cannot see from the front door

    One second in, Loyalty’s points database gets slow: each message now takes over a second, longer than the subscription’s 1 s visibility timeout. The broker assumes the worker died and delivers the same message again. Loyalty awards points twice, and the backlog keeps growing.

    From Checkout everything looks perfect: zero errors, low latency. The problem is visible only in Loyalty’s own metrics: redeliveries, duplicate processing, subscription age. This is the everyday debugging cost of event-driven systems: cause and effect are separated in time and across services.

    Countermeasures: idempotent consumers (remember processed message ids), a correlation id and trace context (W3C traceparent, OpenTelemetry) carried in message headers so one order can be followed through every hop, and alerts per subscription on lag and redelivery rate. Simulated.

    Scene: The Loyalty worker becomes so slow that messages exceed the visibility timeout and are delivered again, so some orders are processed twice and the backlog grows. Checkout shows zero errors and normal latency.

    Key idea: In event-driven systems failures surface downstream and later. Make consumers idempotent and trace messages end to end.

  8. 8. When a synchronous call is the right call

    Loyalty is fixed. Events are not a universal upgrade. Keep a synchronous request when the caller needs the answer to continue: is the item in stock, was the card authorised, is this user allowed to do this. Turning those into events forces the user interface to poll and the process to handle “maybe” states everywhere.

    A good rule: *queries and decisions the user is waiting for* stay synchronous; *reactions to something that already happened* become events. Most systems use both, as this scene now does: a synchronous write to the orders database, a command for payment, events for everything else.

    Scene: The scene labels the three styles in use: a synchronous write to the orders database, a command queue for payment, and an event topic for reactions.

    Key idea: Use events for reactions to facts; use synchronous calls when the caller cannot proceed without the answer.

  9. 9. What to remember about event-driven architecture

    Publish events (facts, past tense) and let consumers react; send commands when you need one specific owner to act. Events give temporal decoupling: shorter request paths, consumer outages become backlogs, new consumers need no producer change.

    The bill: eventual consistency, at-least-once delivery and duplicates, processes scattered across services (choreography) and failures that show up downstream and later. Pay it with idempotent consumers, an outbox, correlation ids and tracing, and per-consumer lag alerts.

    Scene: The final system: Checkout writes orders, sends payment commands and publishes OrderPlaced events consumed by Email, Loyalty and Analytics; Payments and Shipping continue the flow through events.

    Key idea: Events decouple services in time and knowledge; observability and idempotency are what make that safe.