Look at a typical order service. When a customer places an order, it saves the order, then calls payment, then calls inventory, then calls email, then calls the warehouse, then calls analytics.
That one service knows about five others, and it causes four problems:
- One failure breaks everything. Email is down, so the order fails.
- It’s slow. The customer waits for every call to finish.
- It’s hard to change. Want an SMS as well? Change the order service, test it, and redeploy it, even though ordering didn’t change.
- It can’t scale in parts. A flood of emails slows down order taking.
Event-driven architecture (EDA) flips this around. The order service saves the order and announces a fact: “order 42 was placed”. It doesn’t call anyone. Payment, inventory, email and the warehouse each listen for that event and do their own part. Adding SMS means adding a new listener. The order service never changes.
In the last article we looked at the tools that carry messages: queues, pub/sub and Kafka. This one is about designing a whole system around events.
Events vs commands
There are two kinds of messages, and mixing them up causes a lot of confusion.
| Command | Event | |
|---|---|---|
| Says | “Please do this” | “This happened” |
| Name | imperative: ChargeCard, SendEmail |
past tense: OrderPlaced, PaymentFailed |
| Receiver | exactly one, and the sender knows who | anyone who’s interested; the sender doesn’t know |
| Can it be refused? | yes (“card declined”) | no; it’s a fact about the past |
Both are useful. EDA simply means that between services, you mostly share events rather than give orders.
What makes a good event
An event is a fact, so it should never change once published. A good one looks like this:
// Java · an immutable event as a record
public record OrderPlaced(
UUID eventId, // unique: lets consumers spot duplicates
String orderId, // which order this is about (also the Kafka key)
String customerId,
BigDecimal total,
Instant occurredAt, // when it happened
String correlationId, // ties together every event from one user action
int schemaVersion // so the shape can change safely later
) {}
How much data should it carry? There are two styles:
- Thin events carry just IDs: “order 42 was placed”. Small and stable, but every listener must call back to the order service to get the details. That brings back the coupling and load you were trying to remove.
- Fat events carry the data listeners need: amount, items, customer. Listeners can work on their own, even if the order service is down. Events are bigger, and changing their shape needs care.
A good middle ground: include the fields most listeners need, not the whole internal Order object with 50 fields.
The transactional outbox pattern
Here’s the bug almost every team writes first:
@Transactional
public void placeOrder(Order order) {
orderRepository.save(order);
kafka.send("orders", new OrderPlaced(...)); // ⚠ two systems, no shared transaction
}
This writes to two systems: the database and Kafka. They can’t share one transaction, so they can disagree:
- The database commit fails after Kafka sent the event. Everyone hears about an order that doesn’t exist.
- The app crashes after the commit, before the send. The order exists, but nobody ever hears about it: no payment, no email.
This is the dual-write problem. The fix is the transactional outbox:
- In one database transaction, save the order and a row in an
outboxtable describing the event. Both are saved, or neither is. - A separate relay reads new outbox rows. It can poll every second, or follow the database’s change log with a change data capture (CDC) tool like Debezium.
- The relay publishes each event and marks it as sent.
// Java · step 1: the order and its event, in one transaction
@Transactional
public void placeOrder(Order order) {
orderRepository.save(order);
outboxRepository.save(OutboxEvent.of("OrderPlaced", order.getId(), toJson(order)));
} // commit: both rows, or neither
If the relay crashes between publishing and marking a row as sent, it will publish that event again. That’s fine, as long as consumers are idempotent, which they must be anyway.
Choreography vs orchestration
When one event sets off a chain of steps, who’s in charge of the chain? There are two styles.
- Choreography: each service reacts to the previous event and publishes its own. There’s no boss. It’s simple and very loosely coupled, but the full flow isn’t written down anywhere. With many steps, it gets hard to answer “where is order 42 stuck?”
- Orchestration: one orchestrator (often called a saga) sends commands to each service in turn and tracks progress. If a step fails, it runs compensating actions, like refunding a payment. The flow is in one place and easy to follow, but the orchestrator is one more service to build and run. Tools like Temporal and Camunda help here.
Rule of thumb: choreography for short, simple flows (2–3 steps). Orchestration once a business process has many steps, or needs careful undo logic when something fails.
The hard parts, and how to handle them
Duplicates. Brokers deliver at least once, and the outbox can resend. Every consumer must be idempotent: store the eventId of each processed event (with a unique constraint) and skip ones you’ve seen. More in message delivery semantics.
Ordering. Use the entity’s ID as the Kafka key so its events stay in order. Even so, events from different services can arrive in any order: “shipped” before “payment succeeded”. Two defences:
- Store a version per entity and ignore events older than what you’ve already applied.
- Use a state machine that accepts events in any order and only moves forward when it has what it needs.
Changing event shapes. Dozens of consumers may read an event, and you can’t update them all at once. So:
- Only add optional fields; never rename or remove one that’s in use.
- Consumers should ignore fields they don’t know.
- For a breaking change, publish a new version (
OrderPlaced.v2) alongside the old one until every consumer has moved. - A schema registry (with Avro or Protobuf) can reject incompatible changes before they’re published.
Debugging. A request now hops across services with no call stack. Give every event a correlation ID from the original request, log it everywhere, and use distributed tracing (OpenTelemetry, viewed in Jaeger or Zipkin) to see the whole journey.
When not to use events
Events are not a better kind of API. Use a plain request/response call when:
- the caller needs the answer now (“is this username free?”, “what’s in my cart?”);
- you need strong consistency right away, like checking a balance before a transfer;
- it’s a simple read, like “get user profile”.
A common, healthy mix: commands and queries over HTTP or gRPC for things that need an answer, events for telling the rest of the system what happened.
What breaks, and how to fix it
| What breaks | What you see | The fix |
|---|---|---|
| The dual write | Orders with no events, or events for orders that don’t exist | The transactional outbox |
| Duplicate events | A customer is charged twice, or stock drops twice | Idempotent consumers: record processed eventIds with a unique constraint |
| Out-of-order events | “Shipped” is processed before “paid” | Key by entity ID, store versions, and use state machines that tolerate any order |
| A breaking schema change | One team renames a field, and five other services start failing | Additive-only changes, versioned events, and a schema registry |
| Nobody can follow a request | “Where is order 42?” takes hours to answer | Correlation IDs and distributed tracing |
Puzzle 1: the double charge
Two layers of protection:
- Idempotent consumer. Before charging, check whether a payment already exists for this order (or this
eventId), backed by a unique constraint in the database. - Idempotency key at the payment provider. Here the crash happened after the provider charged the card but before our database recorded it, so our own check finds nothing. Send the order ID as the idempotency key with the charge. Payment providers like Stripe return the original result for a repeated key instead of charging again.
The second one matters most: when an action leaves your system, your own database can’t protect you. The receiver has to deduplicate too.
Puzzle 2: the missing confirmation emails
Redis Pub/Sub keeps nothing. It only delivers to subscribers that are connected right now, so every event published while the email service was down is gone.
For events that matter, use a durable broker: Kafka (the email service’s consumer group just resumes from its last offset) or RabbitMQ with durable queues. Combine it with the outbox, so the event is safely stored before it’s even published. Keep Redis Pub/Sub for signals you can afford to lose.
Puzzle 3: the new field that broke checkout
An event is a public contract. The orders team owns the publisher, but other teams depend on its shape, and their code still reads total. Renaming a field is a breaking change, and nothing checked it.
The fix: treat events like a public API. Make additive changes only: add totalAmount, keep total until every consumer has switched, then remove it. For bigger changes, publish a new version of the event alongside the old one. And put a schema registry with compatibility checks in front of the topic, so a breaking change is rejected at publish time instead of in production.
Key takeaways
- Event-driven architecture means services announce facts (“order placed”) instead of calling each other. New features become new listeners.
- Commands ask one service to do something and can be refused. Events state what happened, to anyone who cares.
- Design events as public contracts: immutable, past-tense names, an
eventId, a correlation ID and a version. - Use the transactional outbox to save data and its event together. Never write to the database and the broker separately.
- Choreography suits short flows; orchestration (sagas) suits long ones with undo steps.
- Plan for duplicates, ordering, schema changes and tracing from day one. And keep plain request/response for anything that needs an answer now.
Next in the Asynchronous systems thread: event sourcing and CQRS, where the events don’t just describe changes to your data, they are your data.
Comments