Event-Driven Architecture & the Transactional Outbox
Distinguish commands from events, avoid the dual-write bug, and guarantee reliable event publishing with the transactional outbox pattern.
TL;DR
Events (OrderPlaced) decouple producers from consumers, unlike Commands (ChargeCard). Never update your database and publish to Kafka/RabbitMQ in two separate calls (dual-write bug)—write the event to an outbox table inside the same DB transaction, and let a relay publish it with at-least-once delivery.
Intent
Guarantee that every committed state change in your database reliably produces its corresponding domain event—with zero lost events and zero phantom events on rollback.
Problem
Consider the naive dual-write:
await db.orders.insert(order)succeeds.await broker.publish('OrderPlaced', ...)times out or the pod crashes.
Now the order exists in Postgres, but Inventory and Billing never hear about it. Wrapping it the other way (publish before COMMIT) is worse: if the transaction rolls back, consumers react to an order that doesn't exist.
Solution
The Transactional Outbox uses your database's own ACID transaction as the bridge:
- Single ACID transaction: inside
BEGIN ... COMMIT, insert intoordersand insert{ event_id, type: 'OrderPlaced', payload }intooutbox. Either both commit or both roll back. - Outbox Relay: a background worker polls
outbox WHERE published_at IS NULL(or tails Postgres WAL via Debezium CDC) and pushes messages to the broker. - Idempotent Consumers: because the relay provides at-least-once delivery, consumers record
processed_event_idso duplicate deliveries are harmless no-ops.
Real-world analogy
▶ Flow: watch it work
Transactional Outbox: DB + Outbox → Relay → Broker → Consumer
Press Start or tap any step dot to trace the path.
▸All steps (5)
Code
Writing business state and the outbox event in one SQL transaction:
// TypeScript 7.0.2 (illustrative SQL transaction)
export interface DbTx {
exec(sql: string, params: unknown[]): Promise<void>;
}
export async function placeOrderWithOutbox(
tx: DbTx,
order: { id: string; customerId: string; totalCents: number },
) {
await tx.exec(
'INSERT INTO orders (id, customer_id, total_cents) VALUES ($1, $2, $3)',
[order.id, order.customerId, order.totalCents],
);
const eventId = crypto.randomUUID();
await tx.exec(
'INSERT INTO outbox (id, event_type, payload) VALUES ($1, $2, $3)',
[eventId, 'OrderPlaced', JSON.stringify(order)],
);
}When to use / when to avoid
- You publish domain events to a message broker (Kafka, RabbitMQ, SQS) and cannot afford lost or phantom events.
- You are decoupling modules or services asynchronously via eventual consistency.
- Simple synchronous in-process calls inside a Modular Monolith where everything shares one DB transaction anyway.
How to implement
Create an outbox table
Include id (UUID), event_type, payload (JSONB), created_at, and published_at.
Write in the same transaction
Insert into outbox inside the same DB transaction as your domain table.
Relay and deduplicate
Publish via polling (FOR UPDATE SKIP LOCKED) or Debezium CDC, and deduplicate by event_id on every consumer.
Pros / Cons
- Eliminates the dual-write race condition without slow two-phase commit (2PC) protocols.
- Works with any relational database (PostgreSQL, MySQL).
- Adds an outbox table, relay worker (or CDC), and periodic cleanup of old published rows.
- Consumers must handle duplicate deliveries (idempotency).
Relations
Check yourself
Check Yourself
1. Why does calling db.insert(order) followed by kafka.send(event) fail in production?
2. Why must consumers of an Outbox-backed event stream be idempotent?
Sources
Related Notes
CQRS: Command Query Responsibility Segregation
Separate write (command) models from read (query) models when read and write shapes diverge—and know when plain CRUD is better.
Event Sourcing: Overview, Projections, and Traps
Store every state change as an append-only sequence of events, rebuild state with projections and snapshots, and recognize when Event Sourcing is a trap.