Event-driven architecture: what it gives you and what it costs

Events let systems change independently and absorb load, and the price is paid in consistency, ordering, duplicates and debugging effort. The architecture pays off when those costs are budgeted up front and events are used only where the decoupling is needed.

By Nabil Ahmed8 minute read

The lunar surface near 43°S, 153°E, lit by a low Sun with night falling across one side.
The Moon near 43°S, 153°E. Rendered by Farside from NASA Lunar Reconnaissance Orbiter elevation data.

Event-driven architecture is usually presented as a diagram with a box for each system and a broker in the middle, where each system publishes what has happened and subscribes to what it cares about, so the tangle of point-to-point calls goes away. The diagram is accurate as far as it goes, but it leaves out what happens when a message arrives twice, late, out of order or not at all.

Those cases are the normal operating conditions of any system that communicates through a broker rather than rare faults, and handling them takes most of the engineering effort. A team that adopts events for the decoupling and learns the rest in production can end up worse off than before, running a distributed system whose failures make no noise.

We think events suit a specific set of problems and are expensive elsewhere, so the decision should be taken one integration at a time, with the costs written down next to the benefits, which this piece sets out.

In brief

  • An event is a record that something happened, published by one system without knowing which other systems will react to it.
  • Event-driven design lets producers and consumers be changed, deployed and scaled separately, and lets new consumers be added without changing the producer.
  • The costs are eventual consistency, duplicate and out-of-order delivery, harder debugging and a broker that has to be run as critical infrastructure.
  • Writing to a database and then publishing to a broker in a separate step will sooner or later lose or invent an event, and the transactional outbox pattern is the standard fix.
  • When the caller needs an answer before it can continue, request and response is still the better choice.

Events, commands and queries

Three kinds of message are often confused, which leads to design mistakes.

A query asks for information and waits for it ("What is the stock level for this item?"), while a command asks a particular system to do something ("Reserve two units."), so in both cases the sender knows the receiver and cares about the outcome. An event states a fact in the past tense, such as "Order placed." Its publisher neither knows nor cares who is listening, since it has finished its own work and is only announcing it.

Both the benefit and the cost of the style come from that last property. A publisher that knows nothing about its consumers lets them be added and removed freely, but because it is not waiting for them, it cannot tell whether anything downstream succeeded.

Events travel through a broker, and two families of broker are in wide use. Queue-based brokers such as RabbitMQ, Amazon SQS or Azure Service Bus deliver each message to a consumer and delete it once it has been acknowledged. Log-based brokers such as Apache Kafka, and services built on the same model, append events to an ordered log that is kept for a configured period, which lets consumers read at their own pace and go back over history. The choice affects replay, ordering and operations, so it belongs in your enterprise integration strategy and should not be made by each project.

What it gives you

Each system changes independently. A new consumer can subscribe to an existing event stream with no release on the producer's side, so the finance team can get order data without involving the order service team.

Tolerance of slow or absent consumers. If the email service is down for an hour, orders carry on, because the events wait in the broker and are processed when the service comes back. With synchronous calls the same failure would have spread back to the customer.

Leveling of peak load. A burst of orders turns into a backlog that consumers work through at a steady rate, which means downstream systems can be sized for sustained load rather than for the peak.

A record of what happened. A retained log is a history that can be replayed to populate a new system, or to reprocess the affected period once a bug in a consumer is fixed.

A feed for analytics. The data platform can take the same events, and whether that feed needs to be continuous is covered in batch or streaming.

What it costs

Cost What it looks like in production The usual answer
Eventual consistency The customer sees "order confirmed" before the stock count has changed Design screens and processes that tolerate a delay; keep atomic operations inside one service
Duplicate delivery Most brokers guarantee at-least-once delivery, so a consumer will sometimes receive the same event twice Idempotent consumers that record processed event IDs
Ordering "Order cancelled" is processed before "order placed" Partition by a key such as order ID, since log-based brokers keep order only within a partition; carry a version number to ignore stale events
Lost events at the source The database commit succeeds but the publish fails Transactional outbox
Schema change A producer renames a field and three consumers break overnight Versioned schemas, compatibility checks in the build and changes that only add fields
Poison messages One malformed event blocks a queue or is retried indefinitely Bounded retries and a dead-letter queue that a named person empties
Debugging One business transaction is spread across the logs of six services A correlation ID on every event, distributed tracing and monitoring of consumer lag
Hidden coupling No one knows who consumes an event, so the producing team is afraid to change it An event catalog with owners and registered consumers
Operations The broker has become the one system everything depends on Run it as critical infrastructure or use a managed service, with capacity and failover tested

Two of these costs need more than a table row.

In general, duplicates cannot be configured away. A consumer can crash after doing its work but before acknowledging the message, and the broker then has to deliver it again. Some platforms offer exactly-once processing inside their own boundaries, but once a consumer calls an external system, for example to charge a card or send an email, the guarantee ends at that boundary, which means every consumer has to be safe to run twice. The techniques for doing that are covered in idempotency: the property that stops integrations doing things twice.

Hidden coupling tends to show up last and to do the most damage. Producers were supposed to be free of their consumers, yet three years later an event may have eleven consumers, some of them reading fields that were never meant to be public, and the producing team can no longer change its own data model. An event schema is a public contract in the same way an API is, so it needs the same design, ownership and versioning discipline. Giving events the rigor of data contracts keeps the freedom the architecture was meant to provide.

The order that never shipped

Consider a mid-size retailer whose order service saves each order to its database and then publishes an "order placed" event, which the warehouse system, the email service and the loyalty system all subscribe to. The code looks like the obvious code:

def place_order(order):
    db.save(order)                       # step 1: commit to the database
    broker.publish("OrderPlaced", order) # step 2: tell everyone else

This runs for months, until a deployment stops the service between step one and step two while a handful of orders are in flight. Those orders are in the database, and their customers have been charged and have seen a confirmation, but since no event was published the warehouse never learns about them. Nothing errors or alerts, and the first sign is customers calling a week later.

Swapping the two steps does not help, because if you publish first, a failed database commit produces events for orders that do not exist. This is known as the dual-write problem: the database and the broker are two systems, and writing to one and then the other cannot update both atomically.

The transactional outbox pattern takes the second write out of the request. The service writes the order and the event to the same database in a single transaction, so that either both are stored or neither is:

BEGIN;

INSERT INTO orders (id, customer_id, status, total)
VALUES (:order_id, :customer_id, 'PLACED', :total);

INSERT INTO outbox (event_id, aggregate_id, event_type, payload, created_at)
VALUES (:event_id, :order_id, 'OrderPlaced', :payload_json, now());

COMMIT;

A separate relay process then reads the unpublished rows from the outbox table in order, publishes each one to the broker and marks it as sent when the broker confirms receipt. Some teams poll the table, while others read the database's change log with a change data capture tool such as Debezium. Either way, a relay that crashes after publishing but before marking the row will publish the same event again when it restarts, so the outbox guarantees at-least-once publication and consumers have to deduplicate on event_id. The pattern turns a silent loss into a harmless duplicate, which is the right trade.

The retailer adds two safeguards. Every hour a reconciliation job compares the orders placed with the orders the warehouse has received and raises an alert on any gap older than fifteen minutes, and consumer lag on each subscription is monitored against a threshold. In retail, where the customer has already paid, that hourly check counts for more than confidence in the design.

When events are the wrong tool

The caller needs the answer now. Validating a payment, checking a credit limit and fetching a price are examples. When the user is waiting and the next step depends on the result, make a direct call, since splitting a request and its reply into two events adds delay and failure modes for no benefit.

The steps must succeed or fail together. Inside a single service and database, use a transaction, because events are meant for communication between consistency boundaries and do not belong inside one.

The process has a defined sequence and an owner. When events trigger services that emit further events, the overall process is not written down anywhere. This style, called choreography, works for two or three steps, but beyond that it becomes impossible to say what state an order is in or what happens if step four fails. A multi-step business process with timeouts and compensation is better run by an explicit orchestrator, as we explain in long-running workflows and build in our workflow orchestration work.

The team and the system are small. A single application with one database and one team gains little from a broker while taking on its full operating cost. A modular application with in-process calls can be split later if a real need appears.

Most estates end up mixing events and direct calls, which we think is correct.

Before you commit

The design review for any new event-based integration should work through this checklist.

  • State in one sentence why this interaction should be an event rather than a call. "The producer must not depend on the consumer being available" is a good reason, whereas "It is our standard" is not one.
  • Name the owner of the event schema, and decide how it will be versioned and how compatibility will be checked before each release.
  • Show how the event is published atomically with the change of state. If the answer is "we save, then publish", the design has the dual-write flaw.
  • For each consumer, show how a duplicate is detected and what happens when events arrive out of order.
  • Define the retry limit and the dead-letter destination, along with the alert on that destination and the person who acts on it.
  • Confirm that a correlation ID passes from the first request through every event and that consumer lag is being monitored.
  • Describe the reconciliation, meaning how you would discover a lost event and how quickly.
  • Decide who runs the broker, what happens when it is unavailable and when failover was last tested.

When most of these have answers, the architecture should serve you well. When only a few do, the engineering that makes events safe has not yet been budgeted, and that is cheaper to find in a review than in production. This work makes up most of what systems integration involves from day to day, and none of it appears on the diagram.

Related services

Start a conversation.

A short paragraph is enough. A principal reads every message and replies within one working day.

Or email hello@farside.works. We use what you send only to reply. Privacy