Skip to Content
Mengty Learns
Architecture

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.

explanationintermediateTested with typescript 7.0.2Updated Nov 27, 2026

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

TL;DR

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:

  1. await db.orders.insert(order) succeeds.
  2. 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.

Two separate writes (DB + Broker) cannot be atomic; a crash between them loses or fakes events.

Solution

The Transactional Outbox uses your database's own ACID transaction as the bridge:

  1. Single ACID transaction: inside BEGIN ... COMMIT, insert into orders and insert { event_id, type: 'OrderPlaced', payload } into outbox. Either both commit or both roll back.
  2. 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.
  3. Idempotent Consumers: because the relay provides at-least-once delivery, consumers record processed_event_id so duplicate deliveries are harmless no-ops.

Real-world analogy

▶ Flow: watch it work

Transactional Outbox: DB + Outbox → Relay → Broker → Consumer

Overview of Transactional Outbox: DB + Outbox → Relay → Broker → Consumer. 5 steps.
Overview5 steps in this flow

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

When to use
  • 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.
When to avoid
  • 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

Pros
  • Eliminates the dual-write race condition without slow two-phase commit (2PC) protocols.
  • Works with any relational database (PostgreSQL, MySQL).
Cons
  • 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