Nguyen Le Phong

Foundations of Software ArchitecturePart 7 of 15

Event-Driven Architecture, Explained Without the Hype

When to call a service and when to publish an event, what brokers really guarantee, how to survive duplicate messages, and when events only add complexity.

Your POST /checkout usually takes 200 ms. Today it times out, and the trace tells the story: the order service calls payment, payment calls inventory, inventory calls the email service, and the email service is waiting on a third-party provider that's having a slow afternoon. Four services in a row, and the customer stares at a spinner because the last one in line is tired.

Earlier parts of this series were about structure: where to draw boundaries inside a codebase and between services. Once you have more than one service, the next question shows up fast. How should they talk to each other? Event-driven architecture is one answer, and it gets oversold and overfeared in about equal measure. This post sticks to the parts you'll actually use: when to call and when to announce, what a broker really guarantees, how to survive duplicate messages, and when events are the wrong tool.

Nguyen Le Phong at his desk with two monitors, following a trace where one user action waits on a long chain of downstream services.
A lot of architecture changes start in a trace view, the moment someone counts how many services one click is waiting on.

Why long call chains hurt

When one service calls another and waits for the reply, that's a synchronous call. It's the natural first move because it reads like a function call. The trouble starts when you chain them:

  • Latency stacks up. Say each hop costs 80 ms. Four hops and you've spent 320 ms on network and waiting before any real work is done.
  • Failures travel. If the email service is down, checkout fails, even though sending a receipt has nothing to do with whether the customer can buy.
  • Coupling grows. The order service now has to know about payment, inventory and email. Add a fifth step and you're editing the order service again.

Underneath, the caller is doing two jobs at once. It completes the order, and it also coordinates everyone who cares about the order. Splitting those two jobs apart is most of what event-driven design is about.

Two ways for services to talk

Services talk in one of two shapes. Many architecture debates come down to which shape fits which step.

Synchronous (request/response)Asynchronous (messaging)
Feels likeA phone call: both sides on the line at the same timeA letter: sent now, read when the other side gets to it
Who knows whomThe caller knows the callee and waits for itThe sender knows the broker, and nothing about who reads
When the other side is downThe caller fails right awayThe message waits in the queue until the reader is back
LatencyEvery hop adds upThe sender returns right away and the work runs in the background
Good fit"I need the answer to continue": check a balance, validate a token, authorize a card"This happened, react if you care": order placed, file uploaded, user signed up

The last row is the one to remember. Call when you need the answer to keep going. Announce when something already happened and what others do about it is their business. Event-driven architecture means choosing the second shape on purpose, for the steps where it fits.

Here's the checkout from the opening. The synchronous version makes the customer wait for everything:

// Before: checkout waits on every downstream step
async function checkout(cart) {
  const order = await orders.create(cart)
  await payment.authorize(order)
  await inventory.reserve(order)
  await email.sendReceipt(order)      // slow, and the customer doesn't need it to finish
  await analytics.track(order)
  return order
}

The event-driven version keeps only the steps that need an answer, then announces the fact:

// After: keep what needs an answer, announce the rest
async function checkout(cart) {
  const order = await orders.create(cart)
  await payment.authorize(order)      // still sync: the customer must know if the card works
  await broker.publish("orders", { type: "OrderPlaced", id: order.id, order })
  return order                        // shipping, email and analytics react on their own time
}

Notice that payment stayed synchronous. A declined card is something the customer needs to hear now, so that step stays a question with an answer. Some shops go further and accept the order as "pending" while payment confirms later. That's a valid design too, and it brings in the saga problem we'll get to below.

The win is twofold. The customer no longer waits on the email provider. And when someone wants fraud scoring next month, they write a new subscriber without touching checkout.

One honest warning about that snippet: it writes to the database and then to the broker. If the process dies between those two lines, the order exists and nobody hears about it. That's the dual-write problem, and the usual fix is to save the event in the same database transaction and publish it from there. We cover it in The Outbox Pattern.

Three engineers at a whiteboard redraw a tangled call chain as one queue with several independent subscribers.
The useful whiteboard session picks one real flow and sorts each step into "needs an answer now" or "can happen after".

The vocabulary in plain words

The jargon is smaller than it looks. Most of it comes from Gregor Hohpe and Bobby Woolf's Enterprise Integration Patterns, which still has the clearest definitions:

  • Message: any piece of data one service hands to another through a middleman.
  • Command: a message that asks another service to do something, like ChargeCard (Command Message). It normally goes to one handler, and that handler can say no.
  • Event: a message that says something already happened, like OrderPlaced. It's a fact in the past tense, sent to whoever is interested (Event Message).
  • Broker: the middleman that stores and delivers messages. RabbitMQ, Kafka, NATS, Amazon SNS/SQS and Google Pub/Sub are common ones.
  • Topic or queue: the named mailbox a message lands in. Producers write to it, consumers read from it.
  • Producer and consumer: the side that publishes, and the side that subscribes and reacts.

The distinction that matters most is command versus event, because it decides who's in charge. A command says "you, do this." An event says "this happened, do what makes sense for you." Martin Fowler points out a common trap here: an event that's really a command in disguise, where the sender actually expects one specific reaction (What do you mean by "Event-Driven"?). If OrderPlaced only exists so the email service sends a receipt, and the order service breaks when it doesn't, you've built a remote control with extra steps.

The order service publishes one OrderPlaced event to a broker. Shipping, email and loyalty or analytics each subscribe and react on their own time. PUBLISH ONCE · REACT MANY TIMES Order Service emits OrderPlaced Message Broker topic: orders Shipping Email receipt Loyalty / Analytics subscribe
The order service has no idea who's listening. A new reaction (fraud scoring, a partner webhook) is a new subscriber, and the order service stays as it is.

Three things people mean by "we use events"

Fowler's article sorts the term into several patterns that often get mixed up. Three of them come up in almost every design review:

  1. Event notification. A thin message: "order 1234 was placed." If a consumer needs details, it calls back to the source. Coupling stays low and it's easy to set up. Fowler's caveat: the overall flow gets hard to see, because it isn't written down in any one piece of code.
  2. Event-carried state transfer. The event carries the data consumers need (the whole order, say), so they never call back. Consumers keep working when the source is down, and you skip a round trip. The cost is extra copies of data and more work on the receiving side to keep those copies straight.
  3. Event sourcing. The stored events are the source of truth, and current state is rebuilt by replaying them. You get a full audit trail. You also get replay headaches when handlers talk to outside systems, and event schemas that are hard to change later. It's a big decision with its own post: Event Sourcing: A Beginner's Guide.

Fowler's fourth pattern, CQRS, is about separate read and write models and doesn't require events at all, even though the two often show up together (CQRS has its own post too).

A sensible default

Use event-carried state transfer for the few facts other teams actually care about, and plain synchronous calls for anything that needs an immediate answer. Plenty of systems run happily on those two for years before event sourcing becomes worth its cost.

What a broker actually promises

Brokers don't give you the tidy world of "every message exactly once, in perfect order." What they give you is more modest, and you design around it.

  • At-least-once is the normal case. Kafka guarantees at-least-once delivery by default (Kafka delivery semantics). Amazon SQS standard queues may hand you the same message twice, and the docs say plainly: design your applications to be idempotent (SQS at-least-once delivery).
  • Exactly-once has a boundary. Kafka does offer exactly-once processing for read-process-write flows between Kafka topics, using transactions. Once your consumer charges a card, sends an email or writes to another database, that guarantee no longer covers the side effect. Duplicates are still your problem there.
  • Ordering is per partition. Kafka sends events with the same key (an order id, a customer id) to the same partition, and consumers read each partition in the order it was written (Kafka introduction). Across partitions there's no ordering. Pick your key so that events that must stay in order share one.
  • Poison messages need somewhere to go. A message that fails every time shouldn't block the queue forever. Hohpe and Woolf call the parking spot a Dead Letter Channel, and most brokers support some form of dead-letter queue.

So the rule for the whole team is short: every consumer must be safe to run twice. That property is idempotency, and Chris Richardson's write-up of the Idempotent Consumer pattern is a good reference. Here's what it looks like in code:

// Not idempotent: a redelivered event adds the points twice
async function onOrderPlacedNaive(evt) {
  await loyalty.addPoints(evt.order.customerId, evt.order.total)
}

// Idempotent: record the event id and the change in one transaction
async function onOrderPlaced(evt) {
  await db.transaction(async (tx) => {
    const isNew = await tx.processedEvents.insertIfAbsent(evt.id)  // unique key on id
    if (!isNew) return                                            // seen it already
    await tx.loyalty.addPoints(evt.order.customerId, evt.order.total)
  })
}

The important part is the single transaction. If you check "have I seen this id?", do the work, and save the id in three separate steps, a crash in the middle brings the duplicate right back. When the side effect lives outside your database, like a payment API, pass the event id along as an idempotency key if the provider supports one. Stripe, for example, uses the key to recognize retries and returns the saved result of the first request instead of running it again (Stripe idempotent requests).

Who runs the flow: choreography or orchestration

When one business process spans several services, something has to coordinate it. Richardson describes two ways to do that in his saga pattern write-up, and the choice decides what debugging looks like at 2 a.m.

  • Choreography. No central coordinator. Each service listens for events and publishes its own in turn: order emits OrderPlaced, payment hears it and emits PaymentTaken, shipping reacts to that. Services stay loosely coupled. The flow, though, lives in nobody's code, so you understand it by tracing a live system.
  • Orchestration. A coordinator, often called an order saga, tells each service what to do next and tracks where the process is. The flow is in one place and easy to read. The price is that the coordinator is now a component someone owns and has to keep small.
A rule of thumb

Choreography fits loose fan-out where nobody needs the full story: analytics, notifications, search indexing. Orchestration fits a real business transaction whose steps must all succeed or be undone together. That second case is the saga problem, covered in The Saga Pattern for Distributed Transactions.

Where events pay off

  • Fan-out. One thing happens and several unrelated reactions follow. Adding the seventh reaction shouldn't mean editing the code that recorded the first fact.
  • Slow or bursty work. Encoding video, rendering PDFs, sending a large email campaign: put it on a queue and let workers get through it while the user moves on.
  • Absorbing spikes. A queue soaks up a burst of traffic that would otherwise overload a synchronous downstream service. Workers drain it at the speed they can handle.
  • Team independence. The team that owns orders publishes facts without having to track every team that reads them.

When to skip events

Events have a real cost: a broker to run, failures you can't see by default, and flows spread across services. Adding them too early is a reliable way to build complexity you didn't need.

  • You need the answer right now. "Is this coupon valid?" is a question. Call the service.
  • You have two services. A broker, a schema registry and a dead-letter queue are a lot of machinery to replace one direct call.
  • Nobody on the team has run a broker in production. Async failures don't show up on their own. Without tracing and alerts, a stuck queue is an outage you hear about from customers.
  • The business needs strong consistency. If "correct within a second or two" isn't acceptable for this data, eventual consistency will hurt. Eventual Consistency in the Real World goes into how teams handle that gap.
The "everything is an event" trap

The failure mode looks like this: every function call becomes an event, and the logic for one feature ends up spread over twenty subscribers that nobody can trace end to end. Async messaging is for decoupling things that really are independent. If explaining one flow takes a whiteboard and four marker colors, you've gone too far.

What fits at each stage

  • Solo or early startup. You probably don't need a broker yet. A jobs table in the database you already run can cover "do this later": workers pick rows, process them, mark them done. In PostgreSQL, SELECT ... FOR UPDATE SKIP LOCKED lets several workers pull from the same table without blocking each other, and the docs mention queue-like tables as the intended use (PostgreSQL SELECT, locking clause).
  • Growing team. Bring in a managed broker (SQS, Pub/Sub, hosted Kafka) for the two or three real fan-out points: order events, file processing, notifications. Keep synchronous calls for anything that needs an answer. Set up tracing before you add more topics.
  • Large organization. Events become the backbone between teams, with schema rules, dead-letter handling, replay tools and a named owner for each topic. The hard part shifts from technology to contracts: agreeing what an event means and not changing that meaning casually.

How to start this week

  1. Find one spot where a request waits on work the user doesn't need to wait for: sending email, building a report, syncing to a partner. That's your first event.
  2. Publish a past-tense fact like OrderPlaced instead of a command. Let the email service subscribe instead of being called.
  3. Make the consumer idempotent from day one, keyed on the event id. Assume every message arrives twice.
  4. Save the event in the same transaction as the data change (an outbox table), so a crash can't lose it.
  5. Add a dead-letter queue with an alert before going live. A dead-letter queue that keeps growing is your earliest warning.
  6. Add tracing so one request can be followed across the hop. Debugging async flows without it is mostly guessing.
A small engineering team around a table in the evening, going through an event fan-out plan and deciding which services should react to one event.
Fan-out stays healthy when someone still owns the whole flow: what gets published, who reacts and which steps are allowed to wait.

Key takeaways

  • Call when you need the answer to continue. Publish an event when something happened and others can react in their own time.
  • Commands ask one handler to act. Events state a fact for anyone who cares. Getting this right decides who's in charge.
  • Expect at-least-once delivery. Exactly-once inside Kafka doesn't cover your emails or payments, so every consumer must be safe to run twice.
  • Choreography keeps services loose. Orchestration keeps the flow readable. Use the first for fan-out and the second for multi-step business transactions.
  • A broker for two services, or an event for every call, adds the very complexity you wanted to avoid.

Splitting the work is the easier half. Once services stop sharing a database, a harder question comes up: who owns the data, and what counts as true when it's spread across five services? That's the next part of the series, Who Owns the Data?

What did you think?

Frequently asked questions

What is event-driven architecture?
It's a way of connecting services where one service publishes a fact that already happened, like OrderPlaced, and other services subscribe and react on their own time. The publisher doesn't know or wait for its readers. You still use direct synchronous calls for steps that need an immediate answer.
What is the difference between a command and an event?
A command asks one specific handler to do something, like ChargeCard, and that handler can refuse. An event states that something already happened, like OrderPlaced, and any number of subscribers can react. If the sender expects one particular reaction to its event, it's really a command in disguise.
Does Kafka guarantee exactly-once delivery?
By default Kafka guarantees at-least-once delivery. It offers exactly-once processing for read-process-write flows between Kafka topics using transactions, but that doesn't cover side effects outside Kafka, such as charging a card or sending an email. Consumers that touch external systems still need to be idempotent.
How do I make a message consumer idempotent?
Store the id of each processed event in a table with a unique key, in the same database transaction as the change the event causes, and skip events whose id is already there. For calls to outside APIs, pass the event id as an idempotency key when the provider supports one, as Stripe does.
Choreography or orchestration: which should I use?
Choreography, where services react to each other's events with no coordinator, fits loose fan-out like notifications, analytics and search indexing. Orchestration, where a coordinator tells each service what to do next, fits multi-step business transactions that must succeed or be undone together, which is the saga pattern.
When should I avoid event-driven architecture?
Skip it when you need an immediate answer, when you only have two services, when nobody on the team has run a broker in production, or when the data must be correct immediately. For simple background work, a jobs table in your existing database is often enough to start.