Transactional outbox

Also known as: outbox pattern

On this page 7

The transactional outbox, also called the outbox pattern, is a reliability pattern in which a service writes outgoing messages to an outbox table in the same database transaction as its business data, and a separate relay process later publishes those messages to a broker or another system. In automation and distributed workflows, it solves the dual-write problem: the risk that a database update succeeds while the related event is never sent, or the reverse.

The pattern guarantees that state changes and the events describing them are either both recorded or both discarded. It does not provide exactly-once delivery, so consumers must still handle duplicates, but it removes the most common cause of silently lost events in integration pipelines.

Why the dual-write problem needs a transactional outbox

The dual-write problem arises because a database and a message broker cannot share one atomic transaction in most modern architectures. A service that first commits an order and then publishes an OrderCreated event can crash between the two steps, leaving downstream systems unaware of the order.

Distributed transactions using the two-phase commit protocol (XA) can coordinate both resources, but they add latency, reduce availability and are unsupported by many cloud brokers. The transactional outbox replaces this coordination with a local ACID transaction followed by asynchronous delivery.

The following table shows what happens under each naive ordering and with the outbox.

StrategyFailure pointResulting inconsistency
Commit then publishCrash after database commitState changed, event lost
Publish then commitCommit fails after publishingEvent sent for state that does not exist
Two-phase commitCoordinator or participant unavailableBlocked transactions, reduced availability
Transactional outboxCrash at any pointEvent delayed, never lost or invented
Failure outcomes of different write strategies

How the outbox pattern works step by step

The outbox pattern splits message sending into a durable write phase and a delivery phase. Only the first phase runs inside the business transaction.

  1. The service begins a local transaction, updates business tables and inserts an outbox row with the event payload.
  2. The transaction commits, making both changes durable together.
  3. A message relay reads unpublished outbox rows in order and sends them to the broker.
  4. After the broker acknowledges receipt, the relay marks the row as published or deletes it.
  5. Consumers process each message and discard duplicates using the message identifier.

A typical outbox row contains the fields listed below. Keeping the schema generic allows one relay to serve every event type in the service.

ColumnPurposeExample value
Message IDUnique key used for deduplicationUUID
Aggregate type and IDEntity the event belongs to, used for orderingOrder, 48213
Event typeName consumers use for routingOrderCreated
PayloadSerialized event bodyJSON document
Created atInsertion time for ordering and monitoringUTC timestamp
Published atDelivery status, null until sentUTC timestamp or null
Typical columns of an outbox table

Relay strategies: polling versus log tailing

The relay can discover new outbox rows either by polling the table or by reading the database transaction log. The choice affects latency, database load and operational complexity.

StrategyMechanismLatencyTrade-off
Polling publisherPeriodic query for unpublished rowsSeconds, set by poll intervalSimple, but adds query load
Transaction log tailingChange data capture from the write-ahead log or binlogSub-secondLow load, more infrastructure
Database notificationTrigger or listen/notify wakes the relayNear real timeDatabase-specific, needs fallback polling
Comparison of outbox relay strategies

Log tailing is commonly implemented with change data capture tools such as Debezium, which read the PostgreSQL write-ahead log or the MySQL binary log. Polling relays must use row locking or leader election, for example SELECT ... FOR UPDATE SKIP LOCKED, so that several relay instances do not publish the same row concurrently.

The transactional outbox delivers at-least-once semantics: a relay that crashes after publishing but before marking a row will publish it again. Reliable end-to-end processing therefore pairs the outbox with idempotent consumers and message deduplication.

The complementary inbox pattern records processed message identifiers in the consumer database within the same transaction as the consumer’s state change. Together, outbox and inbox approximate effectively-once processing without distributed transactions.

PatternProblem addressedRelationship to the outbox
IdempotencyRepeated execution of the same requestRequired on the consumer side
Message deduplicationDuplicate deliveries from retriesUses the outbox message ID
Saga patternMulti-service business transactionsOutbox reliably emits saga steps
Dead letter queueMessages that repeatedly fail processingHandles consumer-side poison messages
Event sourcingState stored as an event logEvent store can replace the outbox
How the outbox relates to neighboring patterns

Common pitfalls in outbox implementations

Most outbox failures come from ordering, table growth and relay monitoring rather than from the core idea. Teams should address these concerns before the first production release.

  • Unbounded table growth: published rows must be deleted or archived, or queries and log tailing slow down.
  • Lost ordering: parallel relays can reorder events; partition by aggregate ID when order matters.
  • Silent relay failure: monitor the age of the oldest unpublished row and alert on outbox lag.
  • Oversized payloads: very large events bloat the table; store a reference and let consumers fetch details.
  • Leaking internal schemas: publish stable integration events, not raw database rows.

The pattern also introduces eventual consistency. Downstream systems see changes after a delay, so user interfaces and workflow steps must tolerate a short window in which the source system has committed but consumers have not yet received the event.

Understanding it simply

Imagine a shop clerk who records a sale and must also tell the warehouse to ship it. If the clerk records the sale and then forgets the call, the customer never gets the parcel. The transactional outbox fixes this. The clerk writes the shipping note on the same receipt as the sale.

A runner later collects every note and delivers it to the warehouse. If the runner is interrupted, the notes are still there. The sale and the message always exist together, so nothing is forgotten. The warehouse may sometimes get a note twice, so it checks for repeats.

Applied in practice

A logistics company runs an order service on PostgreSQL that must notify billing, warehouse automation and customer notification services through Apache Kafka. Before the change, the service committed orders and then published events directly, and roughly once a week a pod restart left orders without warehouse events, which operators had to find and resend manually.

The team adds an outbox table written in the same transaction as each order and deploys a change data capture connector that streams new rows to Kafka, keyed by order ID to preserve per-order ordering. Consumers store processed message IDs to skip duplicates. A dashboard tracks outbox lag, typically under one second. After rollout, manual event recovery is no longer needed, and restarts only delay delivery briefly instead of losing it.