How-To Guide

How to Implement the Outbox Pattern

Publish events reliably with the outbox: write the event and the change in one transaction, relay the outbox, and dedupe on the consumer.

On this page

  1. Introduction
  2. Write the event in the same transaction as the change
  3. Relay the outbox to the broker
  4. Dedupe on the consumer
  5. Handle ordering and the outbox growth
  6. Test the crash and the duplicate
  7. Common pitfalls
  8. Conclusion

Introduction

A service that changes its database and publishes an event has two writes that must both succeed, and a database transaction cannot include a message broker. Publishing the event inside the transaction is a dual write: the commit can succeed and the publish fail, or the publish succeed and the commit fail, leaving the data and the event inconsistent. The outbox pattern removes the dual write by writing the event as a row in the same transaction, so the data change and the event commit together.

This tutorial implements the outbox: write the event in the same transaction, relay the outbox, dedupe on the consumer, and test the failure and the duplicate. The examples use a relational outbox table, and the pattern applies to any service that must publish an event reliably.

Write the event in the same transaction as the change

The outbox is a table in the service’s own database. When the service changes its data, it inserts the outgoing event into the outbox table in the same transaction, so the data change and the event row commit atomically. Either both are in the database or neither is. There is no window where the data changed and the event is missing, because they share the transaction.

The outbox row holds the event: an id, the type, the payload, the target topic, and a status. Give each event a unique id, because the consumer dedupes on it. The status tracks whether the event has been published, so the relay knows which to send. The row is written with the data, and the relay reads it after the commit.

BEGIN;
UPDATE orders SET status = 'confirmed' WHERE id = $1;

INSERT INTO outbox (id, type, payload, topic, created_at)
VALUES ($2, 'order.confirmed', $3, 'orders', now());   -- same transaction

COMMIT;   -- the change and the event commit together, or neither

Relay the outbox to the broker

A relay process reads the unsent rows from the outbox and publishes each to the broker, then marks it sent. The relay runs periodically or tails the table for new rows, and it publishes the events in order so the consumer sees them in the order they were written. The relay may publish an event and crash before marking it sent, so it re-publishes on restart, which is why the delivery is at least once and the consumer must dedupe.

The relay can be a separate process or a library in the service. A separate process decouples the relay from the request path and can be scaled and restarted independently. A change-data-capture tail of the outbox table streams the rows as they commit, which avoids polling and delivers with low latency, and it is a clean way to relay without a custom process.

async function relayOnce() {
  const rows = await db.query(
    "SELECT id, type, payload, topic FROM outbox WHERE sent_at IS NULL ORDER BY created_at LIMIT 100",
  );
  for (const row of rows.rows) {
    await broker.publish(row.topic, { id: row.id, type: row.type, payload: row.payload });
    await db.query("UPDATE outbox SET sent_at = now() WHERE id = $1", [row.id]);
    // if this update fails after the publish, the next run re-publishes -> at-least-once
  }
}

Dedupe on the consumer

Because the relay delivers at least once, the consumer may receive an event twice. Give each event a unique id, and have the consumer record the ids it has processed, ignoring a duplicate. This makes the consumer idempotent, so a redelivered event has no effect the second time, and the at-least-once delivery becomes effectively once for the data.

The dedupe store is a table of processed event ids, written in the same transaction as the consumer’s effect, so the effect and the id commit together and a redelivery is caught. If the id is recorded without the effect, a crash between them loses the effect; if the effect is applied without the id, a redelivery double-applies. Both go in one transaction, which is the consumer-side counterpart of the outbox.

BEGIN;
-- dedupe: skip if this event id was already processed
INSERT INTO processed_events (event_id) VALUES ($1) ON CONFLICT DO NOTHING;
-- only apply the effect if the insert was new (row_count = 1)
UPDATE accounts SET balance = balance + $2 WHERE id = $3;
COMMIT;

Handle ordering and the outbox growth

The relay publishes the events in the order they were written, and the consumer processes them in order per key, so the sequence of changes for one entity is preserved. If several consumers process the same entity in parallel, the ordering must be per key, not global, so the events for one entity are in order while different entities can be parallel.

The outbox table grows, so archive or delete the sent rows after a retention period. Keep the unsent rows and the recently sent ones for the relay and for a debugging window, and delete the older ones, or move them to an archive. The outbox is a queue, and like any queue it needs a retention policy so it does not grow without bound.

Test the crash and the duplicate

Test that a crash between the data change and the relay still delivers the event, by committing the change and the outbox row and then restarting the relay, and asserting the event is published. Test that a duplicate delivery is deduped, by publishing the same event id twice and asserting the consumer applies the effect once. Test that the order for one entity is preserved.

# commit the change and the outbox row, crash the relay, restart it
# assert the event is published exactly once from the consumer's perspective
node scripts/crash-relay.mjs
node scripts/start-relay.mjs
# assert the consumer applied the effect once (the duplicate was deduped)

Common pitfalls

Publishing directly inside the transaction as a dual write, no event id so the consumer cannot dedupe, the relay marking sent before publishing so a crash loses the event, the consumer’s dedupe id and effect not in one transaction, and an outbox that grows without a retention policy are the recurring mistakes. The outbox row in the same transaction, an event id, publish-then-mark, a transactional consumer dedupe, and a retention policy address them.

Conclusion

The outbox pattern makes the data change and the event commit together. Write the event in the same transaction, relay it to the broker and mark it sent, dedupe on the consumer with a transactional id, and keep the order per entity. Self-check by crashing between the commit and the publish and asserting the event is delivered, and by publishing a duplicate and asserting the consumer applies it once. Then a service never changes its data without the event going out.

Sources: Microservices.io: Transactional outbox, Debezium: Outbox event router, Chris Richardson: Reliable messaging.

FAQ

Why not publish the event directly in the transaction?
A database transaction cannot include a message broker, so publishing inside it is a dual write: the write can commit and the publish fail, or the reverse. The outbox makes the event a row in the same transaction, so the write and the event commit together.
Does the outbox deliver exactly once?
No; it delivers at least once, because the relay may publish an event and crash before marking it sent. The consumer must dedupe on the event id. At-least-once delivery plus idempotent consumption is the standard reliable messaging guarantee.

Related Examples