PostgreSQL · Databases

The Transactional Outbox Pattern, Explained Simply

How to save data and publish an event without ever losing one or sending a fake one.

Part 3 of 3: Reliable backends with just your database This is the last part.

Your order service saves a new order and then tells the rest of the company about it by publishing an order_created event to Kafka (or RabbitMQ, or SNS). Billing listens. Shipping listens. Email listens.

That is two writes to two different systems. Sooner or later one of them works and the other doesn’t. This is called the dual write problem, and the transactional outbox is the standard fix. It needs one extra table and one small background process.

Short version:

  • Don’t publish the event directly. Write it to an outbox table in the same database transaction as the order.
  • A separate process reads the outbox and publishes the events.
  • Events are delivered at least once, so consumers must handle duplicates. In return, no event is ever lost, and no event is sent for data that was never saved.

The dual write problem

Here is the code most services start with:

save order to database
publish order_created to Kafka

Look at what can go wrong between those two lines:

Two ways the dual write fails. Failure 1, lost event: the order is saved to the database, then publishing to Kafka fails because Kafka is down, so the order exists and shipping never hears about it. Failure 2, ghost event: the event is published to Kafka, then saving the order to the database fails, so billing charges for an order that does not exist.

Swapping the order of the two lines only swaps which failure you get. The process can also crash between the lines, which has the same effect as Kafka being down.

“Can’t I publish after the transaction commits?”

That is failure 1. The commit worked, then the publish failed or the process was killed during a deploy. The event is gone and nothing will ever retry it.

“Can’t I use a distributed transaction?”

In theory, two-phase commit (2PC, also called XA) makes two systems commit together. In practice most message brokers don’t support it, and the ones that do make every write slower and harder to run. Almost nobody does this for events.

The fix: write the event to your own database

Your database can already save several rows atomically. So save the event as a row, next to the order:

The service runs one database transaction that inserts into the orders table and the outbox table, so both rows or neither are saved. A relay process reads the outbox table, sends each event to Kafka and marks it sent. Kafka delivers the events to consumers.

The order and the event now live or die together. If the transaction rolls back, there is no event. If it commits, the event is safely stored, and the relay will send it, even if Kafka is down for an hour.

The outbox table

CREATE TABLE outbox (
  id             bigserial   PRIMARY KEY,
  aggregate_type text        NOT NULL,   -- 'order'
  aggregate_id   text        NOT NULL,   -- '881', also the Kafka key
  event_type     text        NOT NULL,   -- 'order_created'
  payload        jsonb       NOT NULL,
  created_at     timestamptz NOT NULL DEFAULT now(),
  sent_at        timestamptz
);

CREATE INDEX outbox_unsent_idx ON outbox (id) WHERE sent_at IS NULL;

“Aggregate” is a fancy word for “the thing the event is about”. Here it is the order. aggregate_id will matter when we talk about ordering.

Writing an event is a plain insert inside your existing transaction:

BEGIN;

INSERT INTO orders (id, customer_id, total) VALUES (881, 42, 25.00);

INSERT INTO outbox (aggregate_type, aggregate_id, event_type, payload)
VALUES ('order', '881', 'order_created',
        '{"order_id": 881, "customer_id": 42, "total": "25.00"}');

COMMIT;

The relay: two ways to read the outbox

Option 1: polling

A small loop asks the table for unsent events every second or so:

BEGIN;

SELECT id, aggregate_id, event_type, payload
FROM outbox
WHERE sent_at IS NULL
ORDER BY id
LIMIT 100
FOR UPDATE SKIP LOCKED;

-- publish each row to Kafka and wait for Kafka to confirm

UPDATE outbox SET sent_at = now() WHERE id = ANY($sent_ids);

COMMIT;

FOR UPDATE SKIP LOCKED lets you run more than one relay without two of them grabbing the same rows. It is the same trick used to build a job queue in Postgres, and that post explains how it works.

One detail that catches people out: don’t track progress with “give me rows with id greater than the last one I sent”. A bigserial id is handed out when the row is inserted, not when the transaction commits. A slow transaction can commit id 100 after id 101 is already sent, and a “greater than” relay will skip 100 forever. Querying sent_at IS NULL avoids that.

Option 2: change data capture (CDC)

Every database keeps a log of changes for crash recovery and replication: the WAL in Postgres, the binlog in MySQL and MariaDB. A CDC tool such as Debezium reads that log and publishes each new outbox row as it is committed. Your code doesn’t poll at all.

Which one?

Polling CDC (log reading)
Setup A loop in your service A separate tool to run and watch
Delay Your poll interval (~1 second) Usually under a second
Load on DB One small query per poll Reads the log, no queries
Commit order Needs care (see above) Follows commit order
Best for Starting out, most services High volume, many services

Start with polling. It is boring and easy to debug. Move to CDC when you can measure that polling delay or database load is a problem.

Duplicates are part of the deal

Look at the relay again. It publishes to Kafka, then marks the rows as sent. What if it crashes between those two steps?

Timeline of a relay crash between three columns: relay, Kafka and outbox row 77. The relay reads row 77 and publishes it, and Kafka stores event 77. The relay crashes before marking the row sent, so sent_at stays NULL. After the restart it reads row 77 again and publishes it again, and Kafka stores a second copy of event 77. Then it marks the row sent and sent_at becomes 10:04. The event went out twice.

The event went out twice. You can’t fully prevent this, so the outbox gives you at-least-once delivery: every event arrives, maybe more than once.

The answer is to make consumers safe to repeat. Include a unique event id in the payload (the outbox id works), and have each consumer remember what it has handled:

-- in the consumer's database
CREATE TABLE processed_events (
  event_id     bigint      PRIMARY KEY,
  processed_at timestamptz NOT NULL DEFAULT now()
);

BEGIN;

INSERT INTO processed_events (event_id) VALUES (77)
ON CONFLICT (event_id) DO NOTHING
RETURNING event_id;

-- no row returned: already handled, COMMIT and stop
-- row returned: do the work in this same transaction

COMMIT;

This is sometimes called an “inbox” table. It is the same idea as an idempotency key: save “I am handling this” in the same transaction as the work.

Ordering: same order, same key

Consumers often care about order. order_shipped arriving before order_created will confuse shipping.

Two rules keep the order right:

  1. Publish with aggregate_id as the message key. Kafka keeps messages with the same key in one partition, in order. Events for order 881 stay in order, while events for different orders can be handled in parallel.
  2. Don’t let two relays send events for the same order at the same time. With several polling relays and SKIP LOCKED, relay A might hold order_created while relay B sends order_shipped for the same order. Either run one relay, or split rows between relays by hash(aggregate_id) so each order always goes through the same relay.
Three orders flow through relays to Kafka partitions, each in order. Order 881 goes through relay 1 to partition p3 as created, paid, shipped. Order 882 goes through relay 2 to partition p0 as created, cancelled. Order 883 goes through relay 1 to partition p3 as created.

Order is only kept per order, not across all orders. That is almost always what you want, and it is what lets you scale.

Keeping the outbox small

The outbox only needs to hold events until they are sent. Delete sent rows on a schedule:

DELETE FROM outbox
WHERE sent_at < now() - interval '3 days';

Keeping a few days helps when you need to check what was sent. In Postgres, a table that gets lots of inserts and deletes also needs autovacuum to keep up. The same tuning tips from the job queue post apply.

The one metric to watch: outbox lag

If the relay stops, nothing errors. Orders save fine. Events just stop flowing, and you find out when a customer asks where their parcel is.

So watch the age of the oldest unsent event:

SELECT now() - min(created_at) AS outbox_lag,
       count(*)                AS unsent
FROM outbox
WHERE sent_at IS NULL;
Outbox lag scale. Under 5 seconds: healthy. 30 seconds to a few minutes: relay slow, or broker struggling. Growing steadily: relay stopped or stuck, page someone. Unsent equals 0: fine, lag shows NULL.

Alert when the lag passes a limit that fits your business, for example two minutes.

When you don’t need an outbox

  • Only one system is involved. If the consumer reads the same database, a job in a jobs table does the same thing with less machinery.
  • Losing an event is fine. Analytics clicks, “user viewed page” counters. Fire and forget is simpler.
  • The event is the source of truth. In event sourcing, you write only the event, so there is no second write to keep in sync.

Questions people ask

Is the outbox the same as event sourcing? No. With an outbox, your normal tables are the truth and events are announcements about changes. With event sourcing, the events themselves are the truth.

Doesn’t this double my database writes? Each event adds one insert, and later one update and one delete. For most services that is small next to the business writes. If it ever matters, CDC removes the update, because it doesn’t need a sent_at column.

Can the relay live inside my service? Yes, and that is the easy way to start. Run it as a background loop. With SKIP LOCKED, every copy of your service can run one safely, as long as you handle the ordering rule above.

What about MySQL? The pattern is the same. MySQL 8.0 supports SKIP LOCKED for polling, and Debezium can read the MySQL binlog for CDC.

Cheat sheet

Transactional outbox in one page. Problem: a database write and a broker publish cannot commit together. Fix: insert the event into the outbox table in the same transaction. Relay: poll WHERE sent_at IS NULL with SKIP LOCKED, or use CDC from the WAL or binlog. Never: track progress with id greater than last sent. Delivery: at least once, so consumers dedupe by event id. Ordering: message key is aggregate_id, one relay per key. Cleanup: delete rows sent more than a few days ago. Watch: outbox lag is now() minus the oldest unsent created_at.

Further reading

Written by Rafi Loom

Backend engineer who builds high-volume systems that move money. More about Rafi