In an event-driven architecture, services announce facts (OrderPlaced, PaymentFailed) instead of calling each other, and anyone interested reacts. Producers and consumers are decoupled in time, location and knowledge, which makes systems easier to extend and more resilient to partial outages. Two powerful patterns build on events: CQRS separates the model that handles writes from the models that serve reads, and event sourcing stores the events themselves as the source of truth.
Think of it like
A newspaper, not a phone tree
In a phone tree you must know whom to call, and you wait for each person to pick up. A newspaper just prints what happened: "New bakery opens on Main Street on Monday." Suppliers, competitors and hungry customers each react in their own way, at their own pace, and the paper never needs to know who reads it. Keep every past edition and you can reconstruct the town's entire history, which is exactly what event sourcing does.
Events, commands and queries
Messages between services come in three flavors, and naming them correctly clarifies who owns what. The key distinction: a command asks for something to happen and can be refused; an event states that something already happened and cannot be undone.
| Message | Intent | Naming | Handlers | Example |
|---|---|---|---|---|
| Command | "Please do this" | Imperative verb | Exactly one; may reject it | PlaceOrder, ChargeCard |
| Event | "This happened" | Past tense | Zero or more subscribers; immutable fact | OrderPlaced, CardCharged |
| Query | "Tell me" | Question | Exactly one; no side effects | GetOrder, ListOrdersForUser |
Publish/subscribe
Producers publish events to a topic on a broker (Kafka, Pulsar, SNS, RabbitMQ exchanges, Google Pub/Sub), and every subscribing consumer receives a copy. The broker absorbs bursts, buffers messages while consumers are down and lets consumers replay history. See Message Queues & Pub/Sub for broker internals.
Point-to-point queue
- Each message is processed by exactly one consumer
- Used to distribute work across a pool of workers
- Message is deleted once acknowledged
- Example: a job queue of thumbnails to render
Publish/subscribe topic
- Every subscriber (or consumer group) gets every event
- Used to fan out facts to many independent reactions
- Log-based brokers retain events for replay
- Kafka combines both: fan-out across groups, work sharing within a group
- Space decoupling: producer and consumers don't know each other's addresses or even existence.
- Time decoupling: a consumer can be offline and catch up later; the broker holds the events.
- Synchronization decoupling: the producer doesn't block waiting for consumers to finish.
Choreography vs orchestration
A business process that spans services (place order, charge card, reserve stock, ship) can be coordinated in two ways. In choreography, each service listens for events and decides on its own what to do next; there is no conductor. In orchestration, a central coordinator tells each participant what to do and tracks progress.
| Choreography | Orchestration | |
|---|---|---|
| Coupling | Loose: services only know event types | Orchestrator knows every participant's API |
| Visibility | Flow is implicit, spread across subscriptions | Flow is explicit in one place |
| Changing the flow | Touches several services; risk of cyclic event chains | Change one workflow definition |
| Failure handling | Each service must know which events to compensate | Centralized compensations and timeouts |
| Risk | "Pinball" architecture nobody fully understands | Orchestrator becomes a god service if it absorbs business logic |
| Best for | Simple fan-out reactions across bounded contexts | Long, multi-step business transactions with compensations |
What goes in an event
Event notification (thin)
- Carries just an ID and the type: "order 81f2 changed"
- Consumers call back to the owner for details
- Small, and never leaks too much data
- Callbacks reintroduce runtime coupling and load on the owner
Event-carried state transfer (fat)
- Carries the relevant state: items, totals, address
- Consumers keep a local copy and never call back
- Owner can be down; consumers keep working
- Larger payloads and a schema contract to evolve carefully
{
"specversion": "1.0",
"id": "evt_5c3e9a",
"source": "/orders-service",
"type": "com.shop.order.placed.v1",
"time": "2026-10-29T14:03:11Z",
"subject": "ord_81f2",
"datacontenttype": "application/json",
"data": {
"orderId": "ord_81f2",
"customerId": "cus_19a7",
"items": [{ "sku": "BOOK-042", "qty": 2, "priceCents": 1999 }],
"totalCents": 3998,
"currency": "USD"
}
}CQRS: separate models for writes and reads
Command Query Responsibility Segregation (popularized by Greg Young, building on Bertrand Meyer's command-query separation) splits one model into two. The write model is normalized and enforces business rules. One or more read models (projections) are denormalized and shaped for specific queries, kept up to date by consuming change events.
Event sourcing
Most systems store current state and overwrite it. Event sourcing stores the full sequence of state changes in an append-only event store, and derives current state by replaying them. Your bank works this way: the ledger of transactions is the truth, and the balance is computed from it.
| Version | Event | Balance after replay |
|---|---|---|
| 1 | AccountOpened { owner: "Ada" } | 0 |
| 2 | MoneyDeposited { amount: 100 } | 100 |
| 3 | MoneyWithdrawn { amount: 30 } | 70 |
| 4 | MoneyDeposited { amount: 50 } | 120 |
- 1
Load
Read the aggregate's events from the event store (starting from the latest snapshot, if any).
- 2
Rehydrate
Fold them into the current state in memory.
- 3
Decide
Validate the command against that state (
balance ≥ amount). Reject it or produce new events. Never mutate state directly. - 4
Append with expected version
Append the new events only if the stream is still at the version you read (optimistic concurrency). If someone else wrote first, reload and retry.
- 5
Publish
Subscribers and projections consume the new events to update read models and trigger side effects.
- Event store
- An append-only database of event streams, one per aggregate, with optimistic concurrency on append (EventStoreDB, or a table keyed by stream ID and version).
- Snapshot
- A cached copy of an aggregate's state at version N, so rehydration replays only the events after N. An optimization, never the source of truth.
- Projection
- A read model built by consuming events. It can be dropped and rebuilt from scratch at any time.
- Replay
- Re-running events through new code: fix a bug in a projection, or build a brand-new report over all history.
- Upcasting
- Transforming old event versions into the current shape as they are read, so the code only handles the latest schema.
Why event sourcing
- Complete audit log for free (finance, healthcare, compliance)
- Time travel: reconstruct state as of any moment
- New read models can be built from history later
- Appends are fast and conflict detection is natural
What it costs
- Steep learning curve and unfamiliar tooling
- Events are forever: schema evolution needs care
- Querying current state requires projections (so CQRS)
- Deleting personal data (GDPR) needs crypto-shredding or similar
Living with eventual consistency
Once state flows through events, different parts of the system see changes at different times. That is fine for most business processes (a shipping label can appear a second after payment), but you must design for it explicitly.
- Idempotent consumers: brokers deliver at least once, so processing the same event twice must be harmless. Track processed event IDs or use upserts. See Idempotency & Delivery Guarantees.
- Ordering per key: Kafka orders events only within a partition, so key events by aggregate ID (
orderId) to keep each order's history in order. - Out-of-order and duplicate tolerance: include a version or sequence number and ignore events older than what you already applied.
- Dead-letter queues: park poison events that keep failing, alert on them, and keep the rest of the stream moving.
- Reliable publishing: use the transactional outbox or CDC so a committed state change always produces its event.
Schema evolution
Events are a public contract, often read by teams you have never met, and with event sourcing they live forever. Evolve them like an API.
| Compatibility mode | Guarantee | Safe changes | Upgrade order |
|---|---|---|---|
| Backward | New consumers can read old events | Delete fields; add optional fields with defaults | Consumers first |
| Forward | Old consumers can read new events | Add fields; delete optional fields | Producers first |
| Full | Both directions | Add or remove optional fields with defaults only | Any order |
- Never repurpose a field or change its type; add a new field instead.
- Put a version in the event type (
order.placed.v2) for breaking changes, and publish both versions during the migration. - Validate schemas in CI against a registry so incompatible changes fail the build, not production.
- With event sourcing, upcast old events on read rather than rewriting history.
Implementation
State is a fold over events; commands validate against rehydrated state and append new events with optimistic concurrency.
from dataclasses import dataclass, replace
from functools import reduce
@dataclass(frozen=True)
class AccountOpened:
account_id: str
owner: str
@dataclass(frozen=True)
class MoneyDeposited:
amount: int
@dataclass(frozen=True)
class MoneyWithdrawn:
amount: int
Event = AccountOpened | MoneyDeposited | MoneyWithdrawn
@dataclass(frozen=True)
class Account:
id: str | None = None
balance: int = 0
version: int = 0 # number of events applied
def apply(s: Account, e: Event) -> Account:
match e:
case AccountOpened(account_id=aid):
return replace(s, id=aid, version=s.version + 1)
case MoneyDeposited(amount=a):
return replace(s, balance=s.balance + a, version=s.version + 1)
case MoneyWithdrawn(amount=a):
return replace(s, balance=s.balance - a, version=s.version + 1)
raise TypeError(f"unknown event {e!r}")
def rehydrate(events: list[Event], start: Account = Account()) -> Account:
return reduce(apply, events, start) # state is a fold over history
def withdraw(s: Account, amount: int) -> list[Event]:
if s.id is None:
raise ValueError("account does not exist")
if amount <= 0:
raise ValueError("amount must be positive")
if s.balance < amount:
raise ValueError("insufficient funds")
return [MoneyWithdrawn(amount)]
class ConcurrencyError(Exception):
pass
class InMemoryEventStore:
def __init__(self) -> None:
self._streams: dict[str, list[Event]] = {}
def read(self, stream_id: str) -> list[Event]:
return list(self._streams.get(stream_id, []))
def append(self, stream_id: str, expected_version: int, events: list[Event]) -> None:
stream = self._streams.setdefault(stream_id, [])
if len(stream) != expected_version: # optimistic concurrency check
raise ConcurrencyError(f"expected v{expected_version}, found v{len(stream)}")
stream.extend(events)
store = InMemoryEventStore()
store.append("acc-42", 0, [AccountOpened("acc-42", "Ada")])
store.append("acc-42", 1, [MoneyDeposited(100)])
state = rehydrate(store.read("acc-42"))
store.append("acc-42", state.version, withdraw(state, 30))
print(rehydrate(store.read("acc-42")).balance) # 70Key takeaways
- Commands ask (one handler, may be rejected); events state facts in the past tense (any number of subscribers, immutable).
- Pub/sub decouples producers from consumers in space, time and synchronization, so new reactions can be added without touching the producer.
- Choreography keeps services loosely coupled but hides the flow; orchestration makes the flow and its compensations explicit in one place.
- CQRS splits a normalized write model from denormalized read models fed by events, so reads and writes scale and evolve independently.
- Event sourcing stores the event log as the source of truth; state is a fold over events, with snapshots for speed and projections for queries.
- Design for eventual consistency: idempotent consumers, per-key ordering, outbox publishing and compatible schema evolution.
Common pitfalls
- Naming commands as events (
SendEmailon a topic) and creating hidden point-to-point coupling. - Assuming exactly-once delivery and writing consumers that break on duplicates.
- Publishing events with a dual write instead of an outbox, losing events when a process crashes.
- Long choreographed chains nobody can follow, with compensations forgotten in one of the services.
- Adopting event sourcing for simple CRUD domains, paying its complexity without needing its audit or replay benefits.
Interview tips
- Use the vocabulary precisely: command vs event, choreography vs orchestration, notification vs event-carried state transfer.
- Whenever you draw an event bus, say how you publish reliably (outbox), how consumers handle duplicates, and what the partition key is.
- If you propose CQRS, address the read-your-writes gap before the interviewer does.
Real-world applications
- E-commerce order pipelines where payment, inventory, shipping and email react to
OrderPlaced. - Banking ledgers and trading systems using event sourcing for a complete audit trail.
- Search indexes, caches and analytics stores kept in sync with a primary database via change events.
Test yourself
Which of these is best modeled as an event?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.