Event-Driven Architecture
Domain events, pub/sub, event sourcing, CQRS, and the outbox pattern for reliable publishing.
Events, not commands
An event is an immutable fact: 'OrderPlaced', 'PaymentCaptured'. Unlike a command ('ReserveStock!'), an event carries no expectation about who reacts or how. The publisher's job ends when the fact is announced.
This inversion is the heart of loose coupling: the Order service doesn't know Inventory, Payment, Notification, and Analytics all react to OrderPlaced. Adding a new consumer requires zero changes to the publisher.
Designing good events
Name events in past tense as domain facts, include the data consumers commonly need (avoiding a callback query storm), and version them like any public contract.
{
"eventId": "9f2c1a7e-...",
"type": "order.placed",
"version": 1,
"occurredAt": "2026-07-11T09:30:00Z",
"correlationId": "req-8842",
"payload": {
"orderId": "ord_42",
"customerId": "cus_7",
"lines": [{ "sku": "SKU-1", "qty": 2, "priceCents": 1999 }],
"totalCents": 3998
}
}The dual-write problem and the outbox
A subtle trap: the service saves the order to its database AND publishes the event to the broker. If it crashes between the two, the systems disagree forever. Writing to two systems without a shared transaction is the dual-write problem.
The transactional outbox pattern solves it: write the event into an 'outbox' table in the same local transaction as the business data, then a relay (poller or CDC like Debezium) publishes rows from the outbox to the broker. Either both effects happen or neither does.
Event sourcing and CQRS (a taste)
Event sourcing goes further: instead of storing current state, store the full sequence of events and derive state by replaying them. You get a perfect audit log and time travel, at the cost of significant complexity — use it for domains that genuinely need it (ledgers, compliance).
CQRS (Command Query Responsibility Segregation) splits the write model from read models. In event-driven systems it appears naturally: services maintain local read replicas ('materialized views') fed by other services' events, so queries are fast and local.
Key takeaways
- Events are immutable past-tense facts; publishers don't know their consumers.
- Include commonly-needed data in events to avoid query storms; version them.
- Never dual-write DB + broker — use the transactional outbox pattern.
- Event sourcing and CQRS are powerful, specialized tools — not defaults.
Knowledge check
What distinguishes an event from a command?
Orders occasionally save to the DB but never appear in analytics. Logs show crashes right after the DB commit. What is the root cause?
In event sourcing, what is stored as the source of truth?