Nguyen Le Phong

The Outbox Pattern: Stop Losing Events Between Commit and Publish

Why saving to the database and then publishing to a broker can lose events, how a transactional outbox closes the gap, and what relays and consumers still need.

Say a customer clicks "Place order" on your shop. The order row lands in the database. The payment service is supposed to get an OrderPlaced event and start charging, but that event never shows up. Nothing crashed in a way anyone noticed. A day later support asks why an order has been "pending" since yesterday, and the logs show one short line: the broker timed out right after the commit.

A flow diagram where the database commit succeeds and the event that should follow it gets lost before reaching the broker.
The gap opens when the business data is saved but the intent to publish is not.

That's the dual-write problem, and the transactional outbox is the standard fix. This post covers why the gap exists, how the outbox closes it, the two ways to run the relay, and the parts the pattern leaves to you: duplicates, ordering and keeping an eye on the table.

Two writes for one action

One business action often needs two things to happen. The service writes to its own database, and it tells other services about it through a message broker. The obvious code does them one after the other:

await db.query(
  'INSERT INTO orders (id, customer_id, total_cents) VALUES ($1, $2, $3)',
  [order.id, order.customerId, order.totalCents],
)
await broker.publish('order.placed', { orderId: order.id })  // if this throws, the order exists and nobody hears about it

If the commit succeeds and the publish fails, the database knows something the rest of the system never learns. Flip the order and publish first, and a failed insert means other services react to an order that doesn't exist. Retrying in a catch block doesn't save you either, because the process can die between the two lines.

The textbook answer would be one distributed transaction across both. Chris Richardson's write-up of the pattern rules that out in its first line of forces: "2PC is not an option," since the database or the broker may not support it (Transactional outbox). Kafka, for one, can't join an XA transaction, as Gunnar Morling notes in the Debezium team's post on the pattern (Reliable Microservices Data Exchange With the Outbox Pattern). His way out is short: only modify one of the two resources.

One commit, then a relay

With an outbox, the service never talks to the broker during the request. It writes the business row and a message row into an outbox table, in the same local transaction:

BEGIN;

INSERT INTO orders (id, customer_id, total_cents)
VALUES ('o-1042', 'c-7', 259000);

INSERT INTO outbox (id, aggregate_type, aggregate_id, event_type, payload)
VALUES (gen_random_uuid(), 'order', 'o-1042', 'OrderPlaced',
        '{"orderId": "o-1042", "totalCents": 259000}');

COMMIT;

Commit, and both the order and the intent to announce it exist. Roll back, and neither does. Richardson's summary of the result is the whole point: messages "are guaranteed to be sent if and only if the database transaction commits." A separate process, the message relay, reads the outbox and publishes each row to the broker.

One transaction writes the order row and the outbox row together, then a relay picks up the outbox row and sends it to the broker.
The transaction makes the publish intent durable. The relay takes care of delivery and can retry as often as it needs.

What changed is where the unreliable step sits. The part that must be atomic stays inside one database, where ACID still works. The part that can fail (talking to the broker) becomes asynchronous and retryable. If the relay crashes after reading a row, it reads it again. If the broker is down, the rows wait. Events can arrive late, but they don't vanish.

Getting rows out: polling or log tailing

There are two common ways to build the relay. Richardson calls them Polling publisher and Transaction log tailing.

Polling is the simple one. A worker queries for unpublished rows every second or so, publishes them, then marks them done. On Postgres, a minimal version looks like this:

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,
  attempts       int NOT NULL DEFAULT 0,
  last_error     text
);
CREATE INDEX outbox_unpublished ON outbox (created_at) WHERE published_at IS NULL;

-- the relay, inside one transaction
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;
-- publish each row, then:
UPDATE outbox SET published_at = now() WHERE id = ANY($1);

SKIP LOCKED lets several relay workers share the table without blocking each other. The Postgres docs describe it as a way "to avoid lock contention with multiple consumers accessing a queue-like table" (SELECT). Keep in mind that two workers can then publish rows for the same order in parallel, which matters if consumers care about order. More on that below.

Log tailing reads the database's commit log instead of querying the table. Debezium is the best-known tool here: its outbox event router turns each outbox insert into a Kafka message, uses aggregateid as the message key ("important for maintaining correct order in Kafka partitions") and sends the row id along as a header you can use to drop duplicates (Outbox Event Router). Because it reads the log, the service can even delete the outbox row right after inserting it, and the table stays empty.

Polling publisherLog tailing (e.g. Debezium)
What you runA worker and a SQL query. Works with almost any database.A CDC connector (often Kafka Connect) plus database log settings.
LatencyAt least the polling interval.Close to the commit, without polling queries.
Load on the databaseConstant small queries, plus cleanup of old rows.Reads the log. The outbox table can stay empty.
Good fitMost teams, most volumes. Start here.High volume, a Kafka setup you already run, or tight latency needs.

At least once means consumers must dedupe

The outbox gives you at-least-once delivery. If the relay publishes a row and crashes before marking it done, it will publish that row again after restart. Richardson's page names this directly, "The Message relay might publish a message more than once," and the answer is an idempotent consumer.

The usual move is to record each message id in the consumer's own database, in the same transaction as the work it triggers, which is the approach Morling's post describes:

BEGIN;
INSERT INTO processed_messages (message_id) VALUES ($1)
ON CONFLICT DO NOTHING;
-- 0 rows inserted: we've handled this message before, so stop here
-- 1 row inserted: do the business work below, in this same transaction
COMMIT;

If the work fails, the transaction rolls back, the id isn't recorded and the retry gets a clean second chance. The outbox fixes the producer side of a dual write. The consumer side still needs this kind of care, and if a whole business flow spans several services, that's the job of a saga.

Ordering: decide what really needs it

Strict global order across every event in the system is expensive, and you rarely need it. The useful question is smaller: which events must arrive in order for one business object to make sense? OrderPlaced before OrderCancelled for the same order, yes. Two unrelated orders, no.

Per-object order usually comes from the message key. Debezium keys messages by aggregateid, so all events for one order land in the same Kafka partition. With a polling relay, either run one worker, or route rows by aggregate id so one worker owns each order. One subtle catch: created_at is set when the row is inserted, but the row only becomes visible at commit, so a slow transaction can appear after a newer one. If the order of events per object really matters, add a per-aggregate version number and let consumers check it.

Running the outbox day to day

The outbox table is a small queue living in your database, so treat it like one. It needs status fields, timestamps, an attempt counter, the last error and a cleanup policy. Published rows shouldn't pile up forever, and failed rows shouldn't disappear without a trace. A row that keeps failing (a payload the broker rejects, say) should be parked after a set number of attempts so it stops blocking the rows behind it.

Four signals tell you most of what you need: how many rows are pending, how old the oldest unpublished row is, publish latency, and how many rows are retrying or parked. The age of the oldest row is the one to alert on. A growing backlog with a fresh head is load. A backlog whose oldest row is two hours old usually means the relay is stuck.

An operations board tracking outbox backlog, the age of the oldest pending row, retry rate and dead letters.
You're done with the pattern when someone on call can see that delivery has stalled before a customer does.

When to use it, and when to skip it

Reach for an outbox when one action must both change your database and notify another service, and losing that notification would leave the business in a wrong state: an order nobody charges, a refund nobody sends.

You probably don't need it when:

  • Everything lives in one service and one database. A plain transaction already covers you.
  • The message is best-effort, like a page-view analytics ping, where losing one now and then is fine.
  • You use event sourcing. The event store is already the source of truth, and Richardson lists event sourcing as an alternative to an outbox.
Reliable delivery of a vague event is still vague

An outbox won't tell you what to publish. Each event still needs a clear meaning, a stable schema, a versioning plan and an owner. If OrderUpdated could mean ten different things, the outbox will deliver that confusion very reliably.

The outbox isn't flashy, and that's what makes it nice to work with. It accepts that the database and the broker can't share an easy transaction, then builds a small bridge using only what each side does well. For the bigger picture of what happens after delivery, Eventual Consistency in the Real World covers what users notice while services catch up.

Try this week

  • Grep for places that commit to the database and then publish to a broker or call a webhook. Each one is a dual write.
  • Pick the one where a lost message costs the most and move its publish into an outbox insert in the same transaction.
  • Start with a polling relay. Move to log tailing only when latency or volume asks for it.
  • Add a processed_messages check to the consumer before you ship.
  • Put "age of oldest unpublished row" on a dashboard and alert on it.
What did you think?

Frequently asked questions

What problem does the outbox pattern solve?
It solves the dual write: one action must update your database and publish a message, and the two can't share a transaction. The service writes the business row and an outbox row in one local transaction, so the message exists if and only if the data change commits. A separate relay then publishes it to the broker.
Does the outbox pattern give exactly-once delivery?
No. It gives at-least-once delivery, because a relay can publish a row and crash before marking it sent. Consumers need to be idempotent, usually by recording each message id in their own database in the same transaction as the work it triggers.
Should I use polling or change data capture for the relay?
Start with polling: a worker queries unpublished rows, publishes them and marks them done, and it works with almost any database. Move to log tailing with a tool like Debezium when you need lower latency, run high volume, or already operate Kafka Connect.
How do I keep event order with an outbox?
Decide which events need order, usually only those for the same business object. Key messages by aggregate id so they land in the same partition, keep one relay worker per aggregate, and add a per-aggregate version number if consumers must detect out-of-order events.