Transactional Outbox and Inbox

Publish events reliably by saving them in the same transaction as your data, and dedupe them on the consumer side.

What is it?

A service often needs to do two things when something happens: save to its database and tell other services (for example, "order placed" to Kafka). Doing both directly is a dual write, and it breaks when one succeeds and the other fails: an order without an event, or an event for an order that was rolled back.

The transactional outbox fixes this. In the same database transaction that saves the order, you also insert a row into an outbox table describing the event. Either both are saved or neither is. A separate relay then reads the outbox and publishes the events, retrying until the broker accepts them.

Because the relay can retry, a consumer may receive the same event twice. The inbox pattern handles that: the consumer records each processed event id in an inbox table, in the same transaction as its own changes, and skips ids it has already seen.

Explain like I'm 10

Instead of handing a letter to the courier while you're still writing the receipt (and maybe forgetting one), you put the letter in an outbox tray at the same moment you file the receipt. A mail clerk empties the tray and keeps trying until each letter is delivered. The recipient keeps a list of letter numbers already opened, so a duplicate gets thrown away.

Examples

Writing the business row and the outbox row in one transaction

CREATE TABLE outbox (
  id             uuid PRIMARY KEY,
  aggregate_type text        NOT NULL,  -- e.g. 'order'
  aggregate_id   text        NOT NULL,  -- e.g. the order id (used as message key)
  event_type     text        NOT NULL,  -- e.g. 'OrderPlaced'
  payload        jsonb       NOT NULL,
  created_at     timestamptz NOT NULL DEFAULT now()
);

BEGIN;
INSERT INTO orders (id, customer_id, total) VALUES ('o-42', 'c-7', 99.00);
INSERT INTO outbox (id, aggregate_type, aggregate_id, event_type, payload)
VALUES (gen_random_uuid(), 'order', 'o-42', 'OrderPlaced',
        '{"orderId":"o-42","customerId":"c-7","total":99.00}');
COMMIT;

Both inserts commit together or not at all, so there is never an order without its event or an event for an order that doesn't exist. Publishing happens later, outside the transaction.

A polling relay and an inbox-based consumer

// Relay: publish unsent outbox rows, oldest first.
async function relayOnce(): Promise<void> {
  await db.transaction(async (tx) => {
    // SKIP LOCKED lets several relay instances share the work without double-claiming rows
    const rows = await tx.query(
      "SELECT * FROM outbox WHERE published_at IS NULL " +
      "ORDER BY created_at, id LIMIT 100 FOR UPDATE SKIP LOCKED",
    );
    for (const row of rows) {
      await broker.publish("orders", { key: row.aggregate_id, id: row.id, payload: row.payload });
    }
    // If we crash before this commit, the rows are published again: at-least-once
    await tx.query("UPDATE outbox SET published_at = now() WHERE id = ANY($1)", [rows.map((r) => r.id)]);
  });
}

// Consumer: the inbox insert and the side effect share one transaction.
async function handleOrderPlaced(message: { id: string; payload: OrderPlaced }): Promise<void> {
  await db.transaction(async (tx) => {
    const inserted = await tx.query(
      "INSERT INTO inbox (message_id) VALUES ($1) ON CONFLICT DO NOTHING RETURNING message_id",
      [message.id],
    );
    if (inserted.length === 0) return; // already processed: skip the duplicate
    await tx.query("INSERT INTO invoices (order_id, amount) VALUES ($1, $2)", [
      message.payload.orderId,
      message.payload.total,
    ]);
  });
}

The relay may publish a row twice (crash after publish, before marking it sent), so the consumer dedupes by event id. Ordering the outbox by created_at is a best effort in a multi-writer database; per-aggregate ordering is preserved by using the aggregate id as the message key. A CDC-based relay (Debezium reading the outbox table from the WAL) avoids the polling query and publishes in commit order.

How it works

Write side (outbox).

1. In one local transaction, write the business change and an outbox row with a unique event id, the aggregate id, the event type and the payload. 2. A relay moves outbox rows to the broker. Two common ways: - Polling relay: query unpublished rows in order, publish, then mark them published (or delete them). FOR UPDATE SKIP LOCKED lets several relay instances share the work. Simple, but adds load and latency, and ordering by created_at or id can still differ from commit order. - CDC relay: a log-based CDC tool (see change-data-capture) reads inserts into the outbox table from the WAL or binlog, so events come out in commit order with no polling query. Debezium ships an outbox event router transform that routes each row to a topic based on its aggregate type and uses the aggregate id as the message key. 3. The relay retries until the broker acknowledges, so delivery is at-least-once.

Read side (inbox). The consumer stores each processed event id in an inbox table with a unique constraint, in the same transaction as the changes it makes. A duplicate fails the insert (or ON CONFLICT DO NOTHING returns nothing) and is skipped. Together the two give effectively-once processing: at-least-once delivery plus idempotent handling.

Ordering. Use the aggregate id as the message key, so all events for one order land in the same partition, in order. If a consumer must also reject out-of-order events, include a per-aggregate version number in the payload.

Cleanup. Outbox and inbox tables grow forever unless trimmed. Delete outbox rows once published (with CDC you can delete right after insert in the same transaction, since the insert is already in the log), or purge by age in batches. Keep inbox ids at least as long as the broker could redeliver a message, then purge old ones; partitioning by date makes this cheap.

ONE LOCAL TRANSACTION
   ┌───────────────────────────────────┐
   │  INSERT orders  (o-42)            │
   │  INSERT outbox  (evt-1, o-42, ..) │
   └───────────────┬───────────────────┘
                   │ COMMIT (both or neither)
                   ▼
           ┌───────────────┐   poll unpublished rows
           │ outbox table  │◀──────────────┐
           └───────┬───────┘               │
                   │ or read inserts       │
                   │ from WAL (CDC)        │
                   ▼                       │
           ┌───────────────┐               │
           │    relay      │───────────────┘
           └───────┬───────┘
                   │ publish, retry until acked (at-least-once)
                   ▼
           ┌───────────────┐   key = aggregate id (per-order ordering)
           │ broker topic  │
           └───────┬───────┘
                   ▼
   ┌───────────────────────────────────┐
   │ consumer: ONE LOCAL TRANSACTION   │
   │  INSERT inbox (evt-1) -- dup? skip│
   │  INSERT invoices ...              │
   └───────────────────────────────────┘

Why does it exist?

A database and a message broker can't share one ordinary transaction, and distributed transactions (two-phase commit) are slow, poorly supported by brokers, and couple the systems' availability. The outbox turns "write to two systems" into "write to one database", which is atomic, and then delivers from there with retries. The inbox makes those retries safe.

When to use it

- A service must update its database and publish an event, and losing or inventing an event is unacceptable (orders, payments, inventory). - Choreographed workflows and sagas, where each step reacts to the previous step's event. - Any consumer whose side effect is not naturally idempotent (sending an email, charging a card, incrementing a counter) needs an inbox or similar dedupe.

When not to use it

- Fire-and-forget notifications where an occasional lost event is fine (a metrics ping, a cache warm-up hint). - When the consumer's operation is already naturally idempotent (an upsert of the full state by key), an inbox table adds little. - When there's no local transaction to join (the write goes to a store without transactions); you need another approach, such as making the event log itself the source of truth.

Common mistakes

  • Writing the outbox row in a separate transaction from the business change, which brings back the dual-write problem.

  • Assuming the relay delivers exactly once. A crash between publishing and marking the row as sent republishes it, so consumers must dedupe.

  • Recording the inbox id in a different transaction from the consumer's side effect, so a crash between them either loses the work or repeats it.

  • Never cleaning up the outbox and inbox tables, letting them grow until the polling query and indexes slow down.

  • Publishing all events without a message key, so events for the same aggregate land on different partitions and are processed out of order.

Practice exercises

  1. Easy:

    Describe two failure scenarios where saving an order and then publishing an event directly to Kafka leaves the systems inconsistent, and how the outbox prevents each.

  2. Medium:

    Design outbox and inbox table schemas, including keys, indexes and a cleanup plan, for a service that writes 1,000 events per second.

  3. Hard:

    Compare a polling relay with a CDC relay (Debezium reading the outbox table) for ordering guarantees, latency, database load and operational risk. Which would you pick for a payments service, and why?

Interview questions

What problem does the transactional outbox solve?

The dual-write problem: a service needs to update its database and publish a message, but the two can't be made atomic directly. Writing the event to an outbox table in the same transaction makes them atomic.

How does the outbox row get to the message broker?

A relay reads unpublished outbox rows and publishes them, either by polling the table or by reading the inserts from the database log with CDC, retrying until the broker acknowledges.

What delivery guarantee does the outbox give, and why?

At-least-once. The relay can crash after publishing but before recording that it did, so it publishes again on restart.

What is the inbox pattern?

The consumer stores each processed message id in a table with a unique constraint, in the same transaction as its side effects. A duplicate message conflicts on insert and is skipped.

Why must the inbox insert be in the same transaction as the consumer's work?

If they're separate, a crash between them either marks the message done without doing the work (lost) or does the work without marking it (repeated on redelivery).

How do you preserve ordering of events for one entity?

Use the aggregate id as the message key so all its events go to one ordered partition. A CDC relay also emits rows in commit order. For extra safety include a per-aggregate version so consumers can detect gaps or stale events.

Why might a polling relay publish events in a different order than they committed?

Ordering by created_at or a sequence id reflects when the value was assigned, not when the transaction committed. A transaction that started earlier can commit later, so its row appears after rows the relay has already published.

Why not use a distributed transaction (two-phase commit) between the database and the broker instead?

Many brokers don't support it, it holds locks across systems, and a stalled coordinator blocks both. It also couples availability: the write fails whenever the broker is down. The outbox needs only a local transaction and tolerates broker outages.

How do you keep outbox and inbox tables from growing forever?

Delete or archive outbox rows after they're published (with CDC they can be deleted right away, since the insert is already captured in the log). Keep inbox ids for longer than the maximum redelivery window, then purge in batches or drop old date partitions.

Senior: when would you choose a CDC relay over a polling relay?

When you need commit-order delivery, low latency or high throughput without polling load on the primary. The cost is running CDC infrastructure (for example Debezium on Kafka Connect) and monitoring replication slots or binlog retention. A polling relay is fine at modest volume and is easier to run.