CodeOrigin All articles
Distributed Systems

Write the Event Where You Write the Row: Anatomy of a Transactional Outbox

CodeOrigin
Write the Event Where You Write the Row: Anatomy of a Transactional Outbox

Photo: database administrator monitoring queue dashboards on dual monitors at night, via drawsql-media.s3-us-east-2.amazonaws.com

The incident report was two sentences long. An order was created; the confirmation email never went out. The application code had done exactly what it was told:

await db.insert(orders, order);
await broker.publish('order.created', { id: order.id });

Between those two lines sits an entire class of failure. The database commits and the broker is unreachable, and the event is gone forever. Invert the order and the broker is fine while the transaction rolls back, and now downstream systems believe in an order that never existed. Neither ordering is correct, because the two writes are not one write.

The Two-Step That Cannot Become One

There is no reliable distributed transaction between a relational database and a message broker that is worth the operational cost for most teams. Two-phase commit exists, and it is a hard sell in a system that already has a broker, a database, and a deploy pipeline.

The outbox pattern takes the opposite approach: do not try to make the two writes atomic. Instead, make the database the only place you write, and derive the event from what you already committed. The message becomes a row inside the same transaction as the business change. Either both land or neither does, because they are literally the same commit.

The Table

CREATE TABLE outbox (
  id             bigserial PRIMARY KEY,
  aggregate_type text        NOT NULL,
  aggregate_id   text        NOT NULL,
  event_type     text        NOT NULL,
  payload        jsonb       NOT NULL,
  headers        jsonb       NOT NULL DEFAULT '{}',
  created_at     timestamptz NOT NULL DEFAULT now(),
  available_at   timestamptz NOT NULL DEFAULT now(),
  attempts       int         NOT NULL DEFAULT 0,
  claimed_by     text,
  claimed_until  timestamptz,
  published_at   timestamptz
);

A few details earn their keep. headers carries the trace identifier and the schema version so consumers can route and version-check without parsing the body. available_at supports scheduled retries without a separate table. aggregate_type and aggregate_id give you a cheap partition key and an audit trail. The unique constraint worth adding is a deduplication key — usually (aggregate_type, aggregate_id, event_type, sequence) — so a retried application transaction cannot enqueue the same event twice.

The application code becomes one transaction with two statements:

BEGIN;
INSERT INTO orders (id, ...) VALUES (...);
INSERT INTO outbox (aggregate_type, aggregate_id, event_type, payload)
  VALUES ('order', '10428', 'order.created', '{"id":10428}');
COMMIT;

That is the whole idea. Everything after this point is delivery mechanics.

The Relay Worker

The relay reads unpublished rows, sends them to the broker, and marks them. The critical property is that it must be safe to run many of them concurrently. In PostgreSQL, FOR UPDATE SKIP LOCKED gives that almost for free:

SELECT id, event_type, payload, headers, attempts
FROM outbox
WHERE published_at IS NULL
  AND available_at <= now()
ORDER BY id
LIMIT 100
FOR UPDATE SKIP LOCKED;

Each worker claims its own batch and no worker waits behind another. Two decisions follow immediately. First, marking published should happen after the broker acknowledges, which means a crash between send and update produces a duplicate. That is unavoidable and correct: the system chooses at-least-once and pushes the deduplication burden to the consumer. Second, retries need exponential backoff written into available_at, plus a dead-letter threshold, because a row that fails forever at the front of the queue will starve everything behind it once you stop using SKIP LOCKED naively.

Ordering deserves a note. Ordering per aggregate is achievable if one worker at a time handles a given aggregate_id; global ordering is not, and pretending otherwise produces the worst kind of bug — one that appears under load and vanishes during reproduction.

At-Least-Once Meets Idempotence

A duplicate delivery is not an error; it is the contract. Consumers therefore need a deduplication strategy that survives a restart:

The trap is deduplicating in memory. A cache of seen identifiers handles the easy case and fails precisely when it matters: after a deploy, a restart, or a scale-out that starts a fresh process with an empty cache.

Lag, Retention, and Invisible Debt

An outbox table that is not monitored is a queue that fills up in silence. Four numbers tell you whether it is healthy:

Retention also needs a decision. Published rows should be archived or deleted on a schedule, but keep enough history to answer the question that always arrives during an incident: what did we actually publish, and when?

What the Outbox Does Not Buy You

It does not provide exactly-once delivery. It does not order events globally. It does not validate that the payload describes the row correctly ten minutes later — the event is a snapshot, not a live view. And it does not remove the need to version the schema, because consumers will be reading older payloads after a deploy whether you planned for it or not.

What it does provide is narrower and far more valuable: the message exists if and only if the database change exists, and there is a durable record of every event the system intended to send. The queued message stops being invisible debt and becomes a row you can query, count, and age.

All Articles

Related Articles

One Request, Many Rooms: A Correlation Contract for Code That Leaves Home

One Request, Many Rooms: A Correlation Contract for Code That Leaves Home

The Stampede You Wrote: Containing Retry Amplification with a Shared Budget

The Stampede You Wrote: Containing Retry Amplification with a Shared Budget

Three Verdicts for a Failed Event: Building a Quarantine That Explains Itself

Three Verdicts for a Failed Event: Building a Quarantine That Explains Itself