SD·131
Event-Driven Architecture
Building systems around events: events versus commands versus queries, notification versus event-carried state transfer, designing event schemas and envelopes, event ownership and domain boundaries, consumers and their responsibilities, replay, versioning and evolution of events, the dual-write problem and the transactional outbox, CDC-based publishing, sagas with choreography and orchestration (and durable workflow engines), event sourcing with aggregates, snapshots and projections, plus the trade-offs and failure modes of event-driven systems.
Start here: announcing what happened, reliably
In an event-driven design, services don't tell each other what to do; they announce what has happened ("OrderPlaced", "PaymentCaptured", "OrderReady"), and anyone interested reacts. The orders service doesn't need to know that the kitchen, the notifications service and the analytics pipeline all care about new orders. New consumers can be added without touching the producer. The hard part is making sure that the announcement matches reality: every committed order produces exactly one event that is eventually seen, and no event is produced for an order that wasn't committed.
The dual-write trap
The obvious code saves the order, then publishes the event:
db.execute("insert into orders …") # committed
publish("ev.order_placed", {...}) # what if the process dies right here?
1,000 orders, with the process crashing between the two steps 5% of the time (a deploy, an out-of-memory kill, a broker hiccup):
orders 1000, kitchen saw 946 → 54 orders never reached the kitchen
Fifty-four customers paid for meals the kitchen never heard about. Swapping the order (publish first, then commit) produces the opposite bug: events for orders that were never saved. Two separate systems can't be updated atomically by writing to each in turn.
The transactional outbox
Instead, the order and its event are written in one database transaction, the event going into an outbox table. A separate relay reads unsent outbox rows, publishes them, and marks them sent:
with db.transaction():
db.execute("insert into orders …")
db.execute("insert into outbox(order_id, payload) values (…)") # same transaction
# relay, running separately:
for row in unsent_outbox_rows():
publish(row.payload); mark_sent(row.seq)
Same 1,000 orders; this time the relay crashed between publishing and marking sent, 53 times:
published 1053 messages for 1000 orders
kitchen received 1053, skipped 53 duplicates, saw 1000 distinct orders → 0 missing
Either both the order and its outbox row commit, or neither does, so no event is lost and none is invented. A relay crash means a row gets published again, so the consumer sees duplicates, which it handles by remembering which order IDs it has already processed (insert … on conflict do nothing). At-least-once publishing plus an idempotent consumer gives exactly-once effect.
What an event should carry
{ "type": "OrderPlaced", "version": 2, "event_id": "01J…", "occurred_at": "2026-10-30T12:31:07Z",
"order_id": 42, "kitchen_id": 7, "items": [{"dish": "Dal Tadka", "qty": 2}], "total_paise": 25200 }
A type and version (so it can evolve), a unique ID (for deduplication), when it happened, the ID of the thing it's about, and enough data that consumers rarely need to call back to the producer (event-carried state transfer). Events are named in the past tense because they are facts that have already happened.
How deep to go in event-driven architecture
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Explain events vs commands, publish/subscribe and why EDA decouples services |
| L2 | Publish events reliably with an outbox and consume them idempotently |
| L3 | Explain event design (envelopes, versioning, state transfer), sagas, CDC and event sourcing trade-offs |
| L4 | Diagnose lost, duplicated, out-of-order and poison events in a running system |
| L5 | Design event flows and ownership across domains, including choreography vs orchestration |
| L6 | Govern event catalogues, schemas and platforms across an organisation |
What event-driven architecture is
In an event-driven architecture (EDA), components communicate by producing and reacting to events: records of facts that happened ("OrderPlaced", "PaymentCaptured", "ParcelDelivered"). Producers don't know or care who consumes their events; consumers react independently.
Benefits:
- Loose coupling: add a new consumer (fraud scoring, analytics, loyalty points) without changing the producer.
- Resilience and autonomy: consumers can be down or slow without blocking producers (temporal decoupling).
- Scalability: consumers scale independently; work is naturally parallel by partition.
- Auditability and replay: an event log is a history of what happened, useful for debugging, analytics and rebuilding state.
- Responsiveness: react in near real time (notifications, fraud, inventory updates).
Costs:
- Eventual consistency everywhere; users and developers must reason about intermediate states.
- Harder to understand the whole flow: behaviour emerges from many consumers ("what happens when an order is placed?" requires tracing subscriptions). Needs good documentation (event catalogues), tracing and ownership.
- Duplicate, out-of-order and missing events must be handled by design.
- Schema evolution of events consumed by many teams.
Events, commands and queries
| Message kind | Meaning | Naming | Addressing | Can be rejected? |
|---|---|---|---|---|
| Command | A request to do something | Imperative: PlaceOrder, ChargeCard |
To one specific handler | Yes (validation, business rules) |
| Event | A fact that already happened | Past tense: OrderPlaced, CardCharged |
Broadcast to any interested subscribers | No: it's history (consumers may ignore it) |
| Query | A request for information | GetOrder, ListOrders |
To one handler | Returns data, no state change |
Mixing these up causes coupling: a so-called "event" like SendWelcomeEmail is really a command to a specific service, and the producer now depends on that consumer existing. Name events for what happened in the producer's domain (CustomerRegistered), and let the email service decide to send a welcome email.
Types of event messages
Martin Fowler distinguished several patterns that are all called "event-driven":
Event notification
A thin event says that something happened, with identifiers: {"type": "OrderPlaced", "orderId": "9817"}. Consumers who need details call back to the producer's API.
- Pros: small events, producer's data model not exposed, consumers always fetch current state.
- Cons: callbacks add load and runtime coupling (if the order service is down, consumers can't process); the state fetched may be newer than the event (fine for many uses, confusing for some).
Event-carried state transfer
The event carries the data consumers need: the order's items, totals, customer ID, shipping address. Consumers keep their own local copy (a read model) and never call back.
- Pros: consumers are autonomous (work when the producer is down), fewer calls, natural fit for building read models and caches.
- Cons: larger events, data duplication across services, schema coupling to the payload, personal data spreading across systems (privacy obligations follow it).
Domain events vs integration events
- Domain events: meaningful inside a bounded context (fine-grained, may reflect internal model details).
- Integration events (public events): a curated, stable contract published for other contexts, often coarser, versioned carefully, decoupled from internal tables. Publish integration events deliberately rather than leaking every internal change (raw CDC of internal tables is the extreme form of leaking).
Event sourcing
Events are the source of truth for state itself (below). Distinct from simply publishing events.
Event schemas
A well-designed event has an envelope (metadata) and a payload:
{
"id": "0193f2b0-7c1e-7a2b-9d10-5f4c2e8a91b7",
"type": "orders.order-placed",
"version": 2,
"occurredAt": "2026-10-24T10:15:30.123Z",
"producer": "orders-service",
"subject": "order/9817",
"correlationId": "c-55a1",
"causationId": "cmd-77b2",
"tenantId": "acme",
"traceparent": "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
"data": {
"orderId": "9817",
"customerId": "c-42",
"items": [{ "sku": "book-1", "qty": 1, "unitPriceMinor": 49900 }],
"currency": "INR",
"totalMinor": 49900,
"orderVersion": 1
}
}
Guidelines:
- Unique event ID (UUIDv7 is time-ordered and convenient) for deduplication.
- Type and version explicitly; occurredAt (business time) distinct from broker timestamps.
- Correlation ID (the whole business transaction) and causation ID (the message that caused this one) for tracing flows; W3C trace context in headers.
- Aggregate/entity version so consumers can ignore stale or duplicate updates.
- Money as integer minor units with currency; timestamps in UTC ISO-8601; enums as strings.
- Prefer past-tense, domain-language names and include enough context for common consumers without dumping whole internal models.
- Define schemas formally (Avro, Protobuf, JSON Schema) in a schema registry, documented in an event catalogue (AsyncAPI, EventCatalog, Backstage) with owner, purpose and consumers. CloudEvents standardises the envelope attributes across platforms.
Event ownership
Each event type should have one owning service (the system of record for the fact):
- Only the owner publishes
OrderPlaced; others never "fake" it. - The owner is responsible for the schema, its documentation, compatibility, and the quality of the data.
- Topic naming reflects ownership:
orders.order-events,payments.payment-events. - Consumers own their subscriptions and reactions; they must not require producers to change for them (beyond reasonable contract evolution).
- Align events with bounded contexts (domain-driven design): the order context owns order lifecycle events; the payment context owns payment events. When two services both "own" parts of an entity, the boundary is probably wrong.
Consumers
A consumer's responsibilities:
- Idempotency: handle duplicates safely (inbox table, version checks, natural idempotency; chapter 128).
- Ordering assumptions: rely only on what the producer guarantees (per-key order within a partition); handle out-of-order arrival using versions.
- Error handling: retries with backoff, dead-lettering poison events, alerts (chapter 128).
- Tolerant reading: ignore unknown fields; handle new enum values; don't break on additive changes.
- Own state: build local read models from events rather than calling other services synchronously during event handling (which reintroduces coupling and failure propagation).
- Observability: lag, processing time, error rates, DLQ depth; trace context propagated.
- Replays: be able to reprocess from a point in time (idempotent, possibly side-effect-suppressed mode for things like emails).
// TypeScript consumer (KafkaJS-style): idempotent, version-aware projection of order events
await consumer.run({
eachMessage: async ({ message }) => {
const evt = OrderEventSchema.parse(JSON.parse(message.value!.toString())); // tolerant schema (zod passthrough)
await db.transaction(async (tx) => {
const seen = await tx.insertInto("inbox").values({ consumer: "loyalty", eventId: evt.id })
.onConflict((oc) => oc.doNothing()).executeTakeFirst();
if (Number(seen.numInsertedOrUpdatedRows) === 0) return; // duplicate
if (evt.type === "orders.order-placed") {
await tx.insertInto("points_ledger").values({
customerId: evt.data.customerId, orderId: evt.data.orderId,
points: Math.floor(evt.data.totalMinor / 10000),
}).execute();
}
});
},
});
Replay
Durable event logs make replay possible: reset a consumer group's offsets and reprocess history. Uses: rebuild a corrupted or redesigned read model, backfill a new service, reproduce bugs, compute new analytics over history.
Design for it:
- Retain events long enough (tiered storage, compaction, or archives in object storage) for the replays you need.
- Consumers must be idempotent and deterministic given events (avoid depending on "now" or on external calls whose answers change, or record those answers in events).
- Separate state-building from side effects: during a replay you want to rebuild a projection, not resend 2 million emails. Use a replay flag, a separate consumer group, or check whether side effects were already performed.
- Measure replay duration (a projection that takes 3 days to rebuild limits your options); parallelise by partition; snapshot projections.
Event versioning and evolution
Events are contracts with possibly many consumers you don't know about, and they persist in logs for a long time. Evolution rules (Vol. 11 ch. 117):
- Additive changes (new optional fields with defaults) are backward and forward compatible; most evolution should be additive.
- Never change the meaning of an existing field, its type, or units silently.
- Breaking changes need a new version: publish
order-placed.v2alongside v1 (dual publishing) for a migration period, or a new topic; track consumers; retire v1 after all have migrated. - Upcasting: consumers (or a library) convert old event versions to the current shape when reading, so business logic handles only the latest version (common in event-sourced systems where old events live forever).
- Weak schema / tolerant reader consumers make most changes non-breaking.
- Enforce compatibility in CI with a schema registry (
BACKWARD_TRANSITIVEfor event streams that are replayed from the beginning).
// Upcaster: convert OrderPlaced v1 (single "amount" in rupees, double) to v2 (minor units + currency)
public final class OrderPlacedUpcaster {
public static OrderPlacedV2 upcast(JsonNode e) {
int version = e.path("version").asInt(1);
JsonNode d = e.get("data");
return switch (version) {
case 1 -> new OrderPlacedV2(d.get("orderId").asText(), d.get("customerId").asText(),
BigDecimal.valueOf(d.get("amount").asDouble()).movePointRight(2).longValueExact(), "INR");
case 2 -> new OrderPlacedV2(d.get("orderId").asText(), d.get("customerId").asText(),
d.get("totalMinor").asLong(), d.get("currency").asText());
default -> throw new UnsupportedEventVersion(version);
};
}
}
The dual-write problem
A service that updates its database and publishes an event faces the dual-write problem: the two operations aren't atomic.
- Write DB, then publish: if the process crashes (or the broker is down) after the commit, the event is lost; other services never learn about the order.
- Publish, then write DB: if the DB transaction fails, consumers act on an order that doesn't exist.
- Distributed transactions (XA/2PC) between database and broker are rarely available or desirable.
Two standard solutions: the transactional outbox and CDC.
Transactional outbox
Write the event into an outbox table in the same database transaction as the business change. A separate relay reads the outbox and publishes to the broker, marking entries as sent (or deleting them). Delivery is at-least-once (the relay may publish then crash before marking), so consumers must be idempotent.
CREATE TABLE outbox (
id uuid PRIMARY KEY,
aggregate_type text NOT NULL, -- e.g. 'order' (used for topic routing)
aggregate_id text NOT NULL, -- used as the message key → per-order ordering
type text NOT NULL,
payload jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
published_at timestamptz
);
CREATE INDEX outbox_unpublished ON outbox (created_at) WHERE published_at IS NULL;
// Java/Spring: business write + outbox insert in one transaction
@Transactional
public OrderId placeOrder(PlaceOrder cmd) {
Order order = Order.place(cmd); // domain logic, invariants
orders.save(order);
outbox.save(OutboxEntry.of("order", order.id().value(), "orders.order-placed",
json.valueToTree(OrderPlacedV2.from(order))));
return order.id();
}
// Polling relay (simple): publish in order, mark as published; run as a single active instance
@Scheduled(fixedDelay = 200)
@Transactional
public void relay() {
List<OutboxEntry> batch = outbox.lockNextBatch(500); // SELECT ... FOR UPDATE SKIP LOCKED
for (OutboxEntry e : batch) {
kafka.send(new ProducerRecord<>(topicFor(e), e.aggregateId(), e.payloadBytes())).get();
e.markPublished();
}
}
// Go: write order and outbox row atomically
func (s *Service) PlaceOrder(ctx context.Context, cmd PlaceOrder) (string, error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil { return "", err }
defer tx.Rollback()
id := uuid.Must(uuid.NewV7()).String()
if _, err := tx.ExecContext(ctx,
`INSERT INTO orders (id, customer_id, total_minor, currency, status) VALUES ($1,$2,$3,$4,'PLACED')`,
id, cmd.CustomerID, cmd.TotalMinor, cmd.Currency); err != nil {
return "", err
}
payload, _ := json.Marshal(OrderPlaced{OrderID: id, CustomerID: cmd.CustomerID, TotalMinor: cmd.TotalMinor})
if _, err := tx.ExecContext(ctx,
`INSERT INTO outbox (id, aggregate_type, aggregate_id, type, payload) VALUES ($1,'order',$2,'orders.order-placed',$3)`,
uuid.Must(uuid.NewV7()), id, payload); err != nil {
return "", err
}
return id, tx.Commit()
}
Relay options: a polling publisher (simple; adds DB load and some latency; ensure ordering per aggregate and a single active relay or partitioned relays), or CDC on the outbox table (Debezium's outbox event router reads the WAL and routes each outbox row to a topic by aggregate_type, using aggregate_id as the key: low latency, no polling). Clean up published rows periodically (or delete immediately with CDC, since the WAL captured the insert).
Libraries and frameworks: Spring Modulith event publication registry, Axon, Eventuate Tram, MassTransit/NServiceBus (.NET) outboxes, Watermill (Go) forwarder, Temporal/durable execution as an alternative for orchestrated flows.
CDC as the event source
Instead of an outbox, publish events from CDC of the business tables themselves. Simpler for the application (no outbox writes), but events mirror table rows (internal schema leaks to consumers; multi-row changes become several events; intent is lost: did the status change because of a cancellation or a refund?). Common compromise: CDC of an outbox table, which combines transactional safety with curated, intentful events.
The listen-to-yourself pattern is another option: publish the event first (to a durable log), and have the service itself consume it to update its own database. Atomicity comes from the log; the service's own state is eventually consistent with its own events, which complicates read-your-writes.
Sagas
A business process spanning several services (place order → reserve inventory → charge payment → arrange shipping) can't use one ACID transaction. A saga is a sequence of local transactions, each publishing an event or command that triggers the next; if a step fails, compensating transactions semantically undo earlier steps (release inventory, refund payment) (Vol. 5 ch. 73).
Choreography
Each service reacts to events and emits its own; no central coordinator.
OrderPlaced→ inventory reserves →InventoryReserved→ payments charges →PaymentCaptured→ shipping schedules →ShipmentScheduled→ orders marks confirmed.- On
PaymentFailed, inventory listens and releases the reservation; orders marks the order failed.
Pros: loose coupling, no single point of control, simple for short flows. Cons: the overall flow is implicit (spread across services), hard to see, change and monitor; cyclic dependencies between services' events; adding steps touches several services.
Orchestration
A central orchestrator (a saga/process manager) tells each participant what to do (commands) and reacts to their replies, tracking the saga's state:
Pros: the flow is explicit in one place (easy to read, change, monitor, test); clearer error handling and timeouts. Cons: the orchestrator is a central component (must be highly available and not accumulate business logic of participants); some coupling to participants' commands.
Durable execution engines (Temporal, AWS Step Functions, Azure Durable Functions, Restate, Camunda/Zeebe for BPMN, DBOS) implement orchestration robustly: workflow state, timers, retries and compensation handled by the platform, with code that reads like a sequential program:
// Temporal workflow (Go SDK): saga with compensations; activities retried by the platform
func OrderWorkflow(ctx workflow.Context, order Order) (err error) {
ao := workflow.ActivityOptions{
StartToCloseTimeout: 30 * time.Second,
RetryPolicy: &temporal.RetryPolicy{InitialInterval: time.Second, BackoffCoefficient: 2, MaximumAttempts: 5},
}
ctx = workflow.WithActivityOptions(ctx, ao)
var compensations []func(workflow.Context) error
defer func() {
if err != nil { // run compensations in reverse order
dctx, _ := workflow.NewDisconnectedContext(ctx)
for i := len(compensations) - 1; i >= 0; i-- { _ = compensations[i](dctx) }
}
}()
if err = workflow.ExecuteActivity(ctx, ReserveInventory, order).Get(ctx, nil); err != nil { return err }
compensations = append(compensations, func(c workflow.Context) error {
return workflow.ExecuteActivity(c, ReleaseInventory, order).Get(c, nil)
})
if err = workflow.ExecuteActivity(ctx, ChargePayment, order).Get(ctx, nil); err != nil { return err }
compensations = append(compensations, func(c workflow.Context) error {
return workflow.ExecuteActivity(c, RefundPayment, order).Get(c, nil)
})
return workflow.ExecuteActivity(ctx, ScheduleShipment, order).Get(ctx, nil)
}
Saga design points (both styles):
- Every step and compensation must be idempotent (retries happen) and compensations must be able to run after partial progress.
- Some steps can't be compensated (an email was sent; goods shipped): order steps so irreversible ones come last ("pivot transaction"), and use reservations/semantic locks (pending states) before committing.
- Sagas lack isolation: other transactions can see intermediate states (inventory reserved but order not confirmed); design for it (pending statuses, commutative updates, rereading values).
- Handle timeouts (a participant never replies) as failures with compensation or escalation.
Event sourcing
The idea
In event sourcing, an entity's state is not stored as a current-state row; instead, the system stores the sequence of events that happened to it, and current state is derived by replaying them:
Account 42 event stream:
1 AccountOpened { owner: "Ana", currency: "INR" }
2 MoneyDeposited { amount: 10000 }
3 MoneyWithdrawn { amount: 2500 }
4 MoneyDeposited { amount: 500 }
→ current balance = 10000 − 2500 + 500 = 8000
- Aggregates (DDD) are the consistency boundary: a command loads the aggregate's events, rebuilds its state, validates the command against invariants, and appends new events with optimistic concurrency (expected stream version).
- Projections (read models) subscribe to events and build query-optimised views (CQRS, chapter 127).
- Snapshots store the aggregate state at version N to avoid replaying thousands of events on every load.
// Kotlin: an event-sourced aggregate as a pure fold over events (functional style)
sealed interface AccountEvent { val accountId: String }
data class Opened(override val accountId: String, val owner: String) : AccountEvent
data class Deposited(override val accountId: String, val amount: Long) : AccountEvent
data class Withdrawn(override val accountId: String, val amount: Long) : AccountEvent
data class Account(val id: String = "", val balance: Long = 0, val open: Boolean = false)
fun evolve(state: Account, e: AccountEvent): Account = when (e) {
is Opened -> Account(e.accountId, 0, open = true)
is Deposited -> state.copy(balance = state.balance + e.amount)
is Withdrawn -> state.copy(balance = state.balance - e.amount)
}
fun decideWithdraw(state: Account, amount: Long): List<AccountEvent> {
require(state.open) { "account closed" }
require(amount > 0 && state.balance >= amount) { "insufficient funds" }
return listOf(Withdrawn(state.id, amount))
}
// handler: val state = events.fold(Account(), ::evolve)
// val new = decideWithdraw(state, 2500)
// store.append("account-42", new, expectedVersion = events.size) // optimistic concurrency
The decide/evolve split (sometimes called the "functional event sourcing" or "decider" pattern) keeps domain logic pure and easily testable: given past events and a command, assert the new events.
Benefits and costs
| Benefits | Costs |
|---|---|
| Complete audit trail: every change with intent | Steeper learning curve; unfamiliar to many teams |
| Temporal queries: state at any past time; debugging by replay | Event schema evolution forever (old events never go away): upcasting |
| New read models by replaying history | Eventual consistency of projections |
| Natural fit for event-driven integration | Querying current state requires projections |
Captures business intent (AddressCorrected vs CustomerMoved) |
Deleting personal data (GDPR) needs crypto-shredding or stream rewriting |
| Concurrency via optimistic append | Long streams need snapshots; replay performance |
Use event sourcing where the history is the domain (ledgers, accounting, inventory movements, trading, logistics tracking, compliance-heavy workflows) or where audit and temporal queries are core requirements. For typical CRUD-heavy domains, it's usually more cost than benefit; publishing events via an outbox gives most integration benefits without it.
Tooling: EventStoreDB/KurrentDB, Axon Framework/Server, Marten (PostgreSQL, .NET), Eventuous, Equinox, Akka/Pekko Persistence, PostgreSQL tables with careful indexing and optimistic version checks; Kafka is a good transport and integration log but a poor primary event store for per-aggregate streams (no efficient per-entity stream reads or conditional appends).
Trade-offs and failure modes
| Problem | Symptom | Mitigation |
|---|---|---|
| Lost events (dual writes) | Downstream never updated | Outbox or CDC |
| Duplicates | Double emails, double points | Idempotent consumers, dedupe by event ID |
| Out-of-order events | Stale state overwrites newer | Per-key partitioning, version checks |
| Poison events | Consumer stuck or DLQ growing | Bounded retries, DLQ, alerting |
| Event spaghetti | Nobody knows the full flow | Event catalogue, ownership, tracing, orchestration for complex flows |
| Breaking schema change | Consumers crash | Registry with compatibility checks; versioned events |
| Hidden synchronous coupling | Consumers call producers per event | Event-carried state transfer, local read models |
| Slow consumers | Growing lag, stale views | Autoscaling, partitions, batching, monitoring lag |
| Personal data everywhere | Privacy and erasure obligations | Minimal PII in events, references, crypto-shredding |
Lab: dual writes versus the transactional outbox
PostgreSQL 16, NATS Server 2.11.9 with JetStream, and Python (psycopg 3, nats-py) on the lab machine. Crashes are injected with a seeded random generator at a 5% rate at the most dangerous point of each design, so the two runs are comparable.
Experiment 1: dual write
db.execute("insert into orders values (%s, 'thali')", (i,)) # autocommit
if random.random() < 0.05: continue # "crash" after commit
await js.publish("ev.order_placed", json.dumps({"order_id": i}).encode())
orders 1000, kitchen saw 946 → 54 orders never reached the kitchen
Nothing in the system knows those 54 events are missing; only a reconciliation job comparing orders with kitchen tickets would find them. Wrapping both in a "try, and on failure roll back" doesn't help: the crash is the failure, and there's nothing left running to roll back.
Experiment 2: outbox and relay
with db.transaction():
db.execute("insert into orders values (%s, 'thali')", (i,))
db.execute("insert into outbox(order_id, payload) values (%s, %s)", (i, payload))
# relay
rows = db.execute("select seq, payload from outbox where not sent order by seq limit 100").fetchall()
for seq, payload in rows:
await js.publish("ev.order_placed", payload.encode())
if random.random() < 0.05: break # "crash" before marking sent
db.execute("update outbox set sent = true where seq = %s", (seq,))
# consumer
if db.execute("insert into kitchen_seen values (%s) on conflict do nothing", (oid,)).rowcount == 0: duplicate
relay crashed 53 times
published 1053 messages for 1000 orders; kitchen received 1053, skipped 53 duplicates,
saw 1000 distinct orders → 0 missing
Production details the lab leaves out: run the relay with SELECT … FOR UPDATE SKIP LOCKED so several relay instances can share the work without publishing the same row twice concurrently; delete or archive sent rows so the outbox stays small; publish with the outbox seq (or the event ID) as the broker's deduplication ID, which removes most duplicates at the broker too; and keep per-aggregate ordering by publishing in seq order per order ID (or partition by it). Instead of polling, change data capture (Debezium reading PostgreSQL's logical replication stream, with its outbox event router) relays outbox inserts with lower latency and no polling load.
Experiment 3: the consumer side of the bargain
The kitchen's dedup table is itself the inbox pattern's minimal form: record each processed event ID in the same transaction as the consumer's own state change. If the consumer's effect is outside its database (sending an SMS), deduplicate on the provider side with an idempotency key derived from the event ID, because "record, then send" and "send, then record" are another dual write.
Experiment 4: choreography or orchestration
The order flow (placed → paid → cooking → ready → delivered) can run two ways:
| Style | How | Good for | Risk |
|---|---|---|---|
| choreography | each service reacts to events and emits its own | few steps, independent teams | nobody sees the whole flow; cycles |
| orchestration | a saga orchestrator sends commands and tracks state (Temporal, Step Functions, or a state table) | many steps, compensations, timeouts | the orchestrator becomes a central dependency |
Either way, a failed step after earlier steps succeeded needs a compensation (refund the payment if the kitchen rejects the order), because there's no cross-service rollback.
Try it yourself
- Run two relay processes with
FOR UPDATE SKIP LOCKEDand verify each outbox row is published once (apart from crash-induced repeats). - Use the outbox
seqasNats-Msg-Idand measure how many duplicates still reach the consumer. - Add an
OrderCancelledevent and a compensation in a payments consumer; test cancellation arriving before the payment event. - Write a reconciliation query that finds orders with no kitchen ticket after 5 minutes, and run it against the dual-write result.
Revision sheet: event-driven architecture
Key ideas
- Events (facts, past tense) vs commands (requests to act) vs queries.
- Notification events (ID only, consumers call back) vs event-carried state transfer (enough data to act).
- Envelope: type, version, event ID, time, subject/aggregate ID, producer, trace context; payload.
- Reliable publishing: transactional outbox + relay (polling or CDC); never dual write.
- Reliable consuming: idempotency (inbox/dedup table), ordering per aggregate, retries, DLQ.
- Schema evolution: additive changes, versioned types, registries, upcasting.
- Sagas: choreography or orchestration, with compensations and timeouts.
- Event sourcing: state as a fold over an event log; powerful audit and replay, costly migrations and queries (pair with CQRS read models).
- Ownership: each event type owned by one domain/service.
Numbers to remember
- Lab: 5% crashes between commit and publish lost 54 of 1,000 events.
- Lab: outbox with 53 relay crashes → 1,053 messages, 53 duplicates skipped, 0 missing.
Pitfalls
- Dual writes to a database and a broker.
- Consumers that can't handle duplicates or reordering.
- Events that leak internal table structure (consumers coupled to producer schemas).
- Fat events with sensitive data broadcast to everyone.
- Choreography so complex nobody can trace a flow; no reconciliation.
- Event sourcing adopted for CRUD domains.
Glossary
- Outbox / inbox: tables making publish / consume atomic with local state.
- CDC: change data capture from the database log.
- Saga: a sequence of local transactions with compensations.
- CQRS: separate write model and read models.
- Upcasting: converting old event versions to the current shape on read.