LeepCast
Subscribe
All posts
Software

The Transactional Outbox Pattern: Reliable Events Without Distributed Transactions

Writing to your database and publishing an event are two separate systems, and one of them will eventually fail between the two. Here is how the transactional outbox closes that gap, how to build the relay, and where duplicates and ordering problems still hide.

LeepCast5 min read

Almost every service that publishes events hits the same bug sooner or later. An order is marked as paid in the database, and an OrderPaid event is supposed to go to a message broker so that shipping, email, and analytics can react. Most of the time both happen. Occasionally only one does, and nobody notices until a customer asks why their package never shipped.

This is the dual-write problem, and the transactional outbox is the standard fix. This guide explains why the naive approaches fail, how the outbox works, the two ways to build the component that drains it, and the guarantees you still have to provide on the consuming side.

Why the obvious approaches fail

The database and the broker are independent systems. There is no single commit that covers both, so any ordering of the two writes leaves a window where a crash produces an inconsistent result.

  • Publish inside the transaction, then commit: if the commit fails or the process dies before it, consumers have already reacted to a change that never happened.
  • Commit, then publish: if the process crashes, is deployed, or loses its network connection between the two steps, the change is saved but the event is lost forever.
  • Use a distributed transaction (two-phase commit): many brokers and managed databases do not support it, and even where they do, it couples the availability of your service to both systems at once.

Retries do not rescue the commit-then-publish version either. A retry loop lives in process memory, and the failure you are worried about is the process disappearing.

How the outbox works

The idea is to stop writing to two systems at once. Instead of sending the event to the broker, the service inserts it as a row into an outbox table in the same database, inside the same transaction that changes the business data. Either both rows commit or neither does, because a single local transaction is something every relational database already guarantees.

A separate process, usually called the message relay, then reads committed rows from the outbox and publishes them to the broker. The relay can crash and restart as often as it likes: the events are durable in the database and will be picked up on the next pass.

Here is a minimal PostgreSQL outbox table, loosely following the column layout that Debezium's outbox event router uses by default (an id, an aggregate type, an aggregate id, an event type, and a JSON payload), plus a timestamp and a published marker for a polling relay:

sql
CREATE TABLE outbox (
  id             uuid PRIMARY KEY,
  aggregate_type text        NOT NULL,
  aggregate_id   text        NOT NULL,
  event_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;

-- The business change and the event commit together, or not at all.
BEGIN;
UPDATE orders SET status = 'paid' WHERE id = 42;
INSERT INTO outbox (id, aggregate_type, aggregate_id, event_type, payload)
VALUES (gen_random_uuid(), 'order', '42', 'OrderPaid',
        '{"orderId": 42, "amount": "19.99"}');
COMMIT;

The aggregate type is a natural routing key, for example one topic per aggregate type. The aggregate id is a natural message key, so that brokers which partition by key keep all events for one order together.

Building the relay: polling or log tailing

There are two common ways to move rows from the outbox to the broker, and they make different trade-offs.

Polling publisher

The relay periodically queries for unpublished rows, publishes them, and marks them as done. It works with any SQL database and needs nothing beyond a database connection and a broker client. In PostgreSQL, the FOR UPDATE SKIP LOCKED clause lets several relay instances poll the same table without blocking each other. The PostgreSQL documentation is explicit that skipping locked rows gives an inconsistent view of the data and is meant for queue-like tables, which is exactly what an outbox is.

python
import json
import time

import psycopg

DSN = "postgresql://app@localhost/shop"

FETCH = """
SELECT id, aggregate_type, aggregate_id, event_type, payload
FROM outbox
WHERE published_at IS NULL
ORDER BY created_at
LIMIT 100
FOR UPDATE SKIP LOCKED
"""


def publish(topic, key, value, headers):
    # Stand-in for a real broker client. It must block until the
    # broker acknowledges the message, and raise if it does not.
    print(topic, key, headers, value)


def relay_once(conn):
    with conn.transaction():
        rows = conn.execute(FETCH).fetchall()
        for event_id, agg_type, agg_id, event_type, payload in rows:
            publish(
                topic=f"outbox.{agg_type}",
                key=agg_id,
                value=json.dumps(payload),
                headers={"id": str(event_id), "type": event_type},
            )
        if rows:
            conn.execute(
                "UPDATE outbox SET published_at = now() WHERE id = ANY(%s)",
                [[row[0] for row in rows]],
            )
    return len(rows)


with psycopg.connect(DSN, autocommit=True) as conn:
    while True:
        if relay_once(conn) == 0:
            time.sleep(0.5)

Notice the failure mode built into this loop. If the relay publishes a batch and then crashes before the UPDATE commits, the row locks are released, the rows are still unpublished, and the next pass sends them again. A polling relay is at-least-once by construction, and so is every other relay design.

Transaction log tailing

Instead of querying the table, the relay reads the database's own change stream: the binlog in MySQL, the write-ahead log in PostgreSQL through logical decoding, or table streams in DynamoDB. Every committed insert into the outbox becomes an event, with no polling delay and no extra query load. Debezium is the best-known implementation, and its outbox event router can route each row to a topic named after its aggregate type.

The costs are operational. Each database needs its own connector, and in PostgreSQL the replication slot that feeds logical decoding prevents the server from removing write-ahead log that the consumer still needs. If the connector stops for a long time, that retained log keeps growing, so the slot needs monitoring and should be dropped when it is no longer used. The PostgreSQL documentation also notes that after a crash a slot can rewind to an earlier position and send recent changes again, so log tailing does not remove duplicates either.

Consumers must be idempotent

Because every relay can deliver the same event more than once, the outbox only works if consumers tolerate duplicates. The usual approach is the idempotent consumer pattern: record the id of each processed message in the same transaction as the side effect it causes, and skip any message whose id is already recorded.

sql
CREATE TABLE processed_messages (
  subscriber_id text NOT NULL,
  message_id    uuid NOT NULL,
  PRIMARY KEY (subscriber_id, message_id)
);

-- Inside the consumer's transaction, before applying the side effect:
INSERT INTO processed_messages (subscriber_id, message_id)
VALUES ('billing', '7c9e6679-7425-40de-944b-e07fc1f90ae7')
ON CONFLICT DO NOTHING;
-- 0 rows inserted means this message was already handled: skip it.

This is why the outbox row carries a stable id and why the relay forwards it as a message header. Debezium does the same, placing the outbox id in an id header so consumers can deduplicate.

Ordering: the subtle part

The outbox preserves the order in which one transaction wrote its events, but ordering across transactions is harder than it looks.

  • Commit order is not insertion order. Two transactions can take timestamps or sequence values in one order and commit in the other, so a poller sorting by created_at can see a later event before an earlier one becomes visible. PostgreSQL sequences are not rolled back and can have gaps, so they cannot be used as a gapless commit counter either.
  • Several pollers break per-key order. With SKIP LOCKED, two relay instances can grab different events for the same order and publish them in either order.

If consumers depend on order, the practical options are a single active relay, a relay sharded by aggregate id so that each key has one owner, or log tailing, which reads changes in commit order. Including a per-aggregate version number in the payload lets consumers detect and discard stale events whichever relay you choose.

A production checklist

  1. Write the business change and the outbox row in one local transaction, and never publish directly from request handlers.
  2. Give every event a unique, stable id and forward it to consumers.
  3. Make every consumer idempotent, keyed on that id.
  4. Decide whether consumers need ordering, then pick the relay topology that provides it.
  5. Clean up published rows on a schedule so the outbox table and its index stay small.
  6. Alert on outbox lag: the age of the oldest unpublished row for a poller, or replication slot lag for log tailing.
  7. Version event payloads, because the outbox is now a public contract between services.

The transactional outbox does not make distributed systems exactly-once. What it does is narrower and more useful: it turns a silent, unrecoverable lost event into a duplicate that a well-built consumer can safely ignore.

Share

Enjoyed this?

Get the next deep dive in your inbox. No spam — just the stories worth reading.

Subscribe to the newsletter

Comments