What it is
The transactional outbox is a pattern for publishing an event reliably whenever a service changes its data. Instead of writing to its database and then to a message broker, the service writes the change and the event, as a row in an outbox table, in one local database transaction. A separate relay reads new outbox rows and publishes them to the broker, retrying until it succeeds.
Why it exists
Services that own their data still need to tell others what happened: an order was placed, a payment captured. The obvious code saves the order, then publishes OrderPlaced. That is a dual write to two systems that do not share a transaction:
- If the publish fails (broker down, network error) after the commit, the order exists but no one hears about it.
- If the process crashes between the two steps, same result.
- Publishing first is no better: a failed or rolled-back commit leaves an event for an order that does not exist.
Distributed transactions (two-phase commit/XA) across the database and broker could fix this in theory, but most brokers do not support them, and they couple the availability and latency of both systems. The outbox gets the same safety with only a local transaction.
How it works
- Write. In one transaction the service inserts or updates its business rows and inserts an outbox row: an event id, the aggregate type and id (e.g.
order,42), the event type, the payload, and a created timestamp. - Relay. A relay finds unpublished rows and publishes them. A polling publisher runs something like
SELECT … FROM outbox WHERE published_at IS NULL ORDER BY id LIMIT 100every few hundred milliseconds (usingFOR UPDATE SKIP LOCKEDor a single active instance so relays do not fight over rows). A CDC relay such as Debezium tails the database's commit log (WAL, binlog) and publishes outbox inserts as they commit. - Mark or delete. After the broker confirms, the relay marks the row as published or deletes it. A cleanup job removes old published rows.
- Consume idempotently. Because the relay can publish a row, crash before marking it, and publish it again, and because brokers redeliver unacknowledged messages, consumers deduplicate by event id, typically by inserting the id into a
processed_events(inbox) table with a unique key in the same transaction as their side effect.
The result is at-least-once publishing: every committed change produces its event, possibly more than once. Together with idempotent consumers, processing is effectively once.
When to use it
- A service must change its own data and notify other services, and losing or inventing an event would be a bug: orders, payments, inventory, account changes.
- Choreographed sagas, where each step's event triggers the next service.
- Feeding read models, search indexes or caches from a service's changes when a few hundred milliseconds of delay are acceptable.
When not to
- When the event is a best-effort notification whose loss is harmless (analytics pings, cache hints).
- When the database itself is the event log you share (event sourcing, where the appended events already are the source of truth and can be published from the store).
- When the caller needs the downstream effect before it answers: a synchronous call, with its own failure handling, may be the honest design.
Trade-offs
| Choice | You gain | You pay |
|---|---|---|
| Outbox instead of a dual write | Change and event are atomic; broker outages do not fail writes | Extra table and relay; events arrive slightly later |
| Polling relay | Simple, works with any database | Polling load and latency; must avoid concurrent relays publishing the same rows |
| CDC relay (log tailing) | Low latency, no polling queries, no marking writes | More infrastructure (connectors, log retention), tied to database internals |
| One publisher per partition | Per-aggregate ordering | Less publishing parallelism; a stuck row can block later ones |
Alternatives
- Two-phase commit (XA) across database and broker: atomic in theory, rarely supported, slow and fragile in practice.
- Listen to yourself: publish the event first, and have the same service consume it to update its database. Works when the service can tolerate acting on its own event asynchronously.
- Event sourcing: the event store is the database, so there is nothing to keep in sync.
- CDC on the business tables directly (without an outbox table): no extra writes, but your internal schema becomes the public contract.
- Broker transactions (e.g. Kafka transactions) cover writes inside the broker, not your database.
Failure modes
- Relay down or slow: events pile up in the outbox. Nothing is lost, but consumers fall behind. Alert on the age of the oldest unpublished row.
- Broker down: the relay's publishes fail and are retried; writes keep working. When the broker returns, a backlog burst hits consumers.
- Duplicate publishes: crash between publish and mark, concurrent relays, or broker redelivery. Consumers must be idempotent.
- Reordering: parallel relays, retries or multiple partitions can deliver an older event after a newer one. Key by aggregate id, keep one publisher per partition, and carry versions so consumers can ignore stale events.
- Outbox growth: without cleanup the table grows forever and polling slows down.
- Poison rows: a payload the broker rejects can block a strictly ordered relay; move it aside after a few attempts.
In production
Index the outbox on the unpublished predicate, publish in batches, and delete or archive published rows on a schedule. Run one active relay per partition (leader election or row locking) or use a CDC connector. Monitor outbox lag (oldest unpublished row), publish error rate and consumer duplicates. Include an event id, aggregate id and version in every event, and document that delivery is at-least-once so every consumer team builds idempotency in from the start.
Common misconceptions
- "The outbox gives exactly-once delivery." It gives at-least-once publishing; exactly-once effects need idempotent consumers.
- "Just publish after the commit and retry on failure." The retry lives in the memory of a process that can crash; the outbox puts the retry state in the database, in the same transaction as the change.
- "Publish first, then commit, so nothing is lost." Then a failed commit leaves an event about something that never happened.
- "Events will arrive in order." Only per partition, and only if the relay preserves order for each aggregate.
Interview angle
When a design has "save to the database and publish an event", interviewers expect you to spot the dual write and propose the outbox (or CDC) without being asked. Explain the single transaction, the relay, at-least-once publishing and idempotent consumers, then discuss ordering per aggregate, relay failure, outbox cleanup and how you would monitor lag. Mentioning why 2PC is avoided and when CDC beats polling shows depth.
Model assumptions
Parts of this lesson are simulated and parts are scripted. Simulated by the queueing engine: shoppers placing 20 orders per second (random arrivals, all writes), the Orders API (16 workers, 10 ms) writing to the database (8 ms writes), the naive design's publish to the broker and its failure while the broker is down, the relay publishing to the broker and retrying with backoff (up to 12 attempts, 250 ms doubling to 1 s), and Shipping consuming with acknowledgements, a visibility timeout and redelivery (duplicates are counted, not hidden). The relay is modelled as a steady publisher at the order rate; it is not driven by actual outbox rows, and the engine does not model transactions, the outbox table or row marking. A real relay keeps retrying indefinitely. Scripted (hand-placed packets): the API crash between commit and publish, the relay crash that republishes event #42, the idempotent consumer's deduplication (the engine does not model idempotency), the polling queries and the CDC log records. Numbers show behaviour and orders of magnitude, not benchmarks.