The Transactional Outbox Pattern: Reliable Event Publishing in Distributed Systems

2026-11-30来源 dev.toEnglish
The Transactional Outbox Pattern: Reliable Event Publishing in Distributed Systems

In distributed systems, a single business operation often needs to perform two independent actions: persist business data in a database and publish an event to a message broker.

This creates a dual write problem. Since the database and message broker have separate transaction boundaries, one operation can succeed while the other fails, leaving the system in an inconsistent state.

The Transactional Outbox Pattern addresses this problem by storing the business data and its corresponding event in the same database transaction. A separate relay process then publishes the event to the message broker asynchronously.

This approach eliminates the need for a distributed transaction while providing reliable event publication.

Business Problem

Imagine an e-commerce platform during a busy checkout hour.

A customer pays successfully, and the order is marked as PAID in the database. The service then tries to publish an OrderPaid event to the message broker so other services can react, but the broker is briefly unavailable and the publish fails.

The result:

  • The confirmation email is never sent.

  • The warehouse stock is never reduced.

  • analytics services never see the order.

Failed OrderPaid publish causing missed confirmation email, warehouse stock update, and analytics event

The customer complains, and the shop risks overselling items that are no longer in stock.

Understanding the Dual Write Problem

Dual write problem: saving data to a database and publishing an event to a message broker

Dual write problem: saving data to a database and publishing an event to a message broker

The problem comes from writing to two different systems in one flow:

db.commit(order) // write #1: save to database broker.publish(event) // write #2: publish to message broker 

There are two ways this can go wrong:

  • Database commit succeeds, publish fails → the event is lost.

  • Publish succeeds, database commit fails or rolls back → a "phantom" OrderPaid event announces a payment that was never recorded.

Changing the order of the steps doesn't help. It only changes which failure you get.

Why Not Use One Transaction?

The database and the message broker are separate systems, each with its own transaction boundary. A regular database transaction cannot atomically cover both a database write and a message publication.

Distributed transactions, such as Two-Phase Commit (2PC), can coordinate multiple participants to commit or roll back as a single logical transaction. However, they introduce additional complexity:

  • They require all participants to support a compatible transaction protocol, such as XA.
  • They introduce additional coordination overhead, latency, and operational complexity.
  • If the coordinator fails during the protocol, participants can be left in doubt, potentially holding locks until the coordinator recovers, which reduces availability.
  • Many message brokers and managed services do not support XA-based coordination with relational databases in their standard configurations.

For many distributed applications, this trade-off is not desirable.

Instead, we can rely on local database transactions: store the business data and its corresponding event atomically, then publish the event asynchronously through a separate process.

That's where the Transactional Outbox Pattern comes in.

How the Outbox Pattern Works

Instead of publishing the event directly, the service writes the event into an outbox table in the same database transaction as the business data.

Because it is a single local transaction, both writes succeed together or fail together. There is no in-between state.

A separate process, the relay (or poller), then reads the outbox table and publishes the events to the message broker.

How It Works

Transactional outbox pattern flow: service writes order and event in one transaction, relay publishes events to the broker

  1. The service saves the order and the event in one transaction.

  2. The relay claims a batch of pending events in a short transaction.

  3. The relay publishes the events to the broker, outside any transaction, and waits for the broker's confirmation.

  4. The relay marks confirmed events as sent, and schedules failed ones for a retry with backoff.

  5. Consumers (analytics, email, warehouse) process the events.

If the broker is down, events simply wait in the outbox table until it comes back instead of disappearing.

Implementing the Outbox Pattern

The examples below use SQL (MySQL syntax) and language-agnostic pseudo code, so the idea applies to any stack.

1. The Outbox Table

CREATE TABLE outbox ( id CHAR(36) PRIMARY KEY, -- event ID, e.g. UUIDv7 aggregate_id VARCHAR(64) NOT NULL, -- e.g. order ID event_type VARCHAR(100) NOT NULL, -- e.g. OrderPaid payload JSON NOT NULL, status VARCHAR(16) NOT NULL DEFAULT 'PENDING', -- PENDING | SENT | FAILED attempts INT NOT NULL DEFAULT 0, -- failed publish attempts so far next_attempt_at DATETIME NOT NULL, -- earliest time to try (for backoff) claim_token CHAR(36) NULL, -- which relay run currently owns the row claimed_until DATETIME NULL, -- lease expiry for that claim last_error TEXT NULL, created_at DATETIME NOT NULL, sent_at DATETIME NULL ); 

The extra columns support the relay described below:

  • status and sent_at track whether an event has been successfully published to the message broker.
  • attempts and next_attempt_at drive retries with backoff.
  • claim_token and claimed_until coordinate ownership of events across multiple relays. Duplicate publication is still possible if a lease expires while a relay is processing its batch.

2. Writing Data and Event in One Transaction

BEGIN; -- total is stored in the smallest currency unit (e.g. 150000 = IDR 150,000) INSERT INTO orders (id, customer_id, total, status) VALUES ('ord-123', 'cus-42', 150000, 'PAID'); INSERT INTO outbox (id, aggregate_id, event_type, payload, status, next_attempt_at, created_at) VALUES ('evt-789', 'ord-123', 'OrderPaid', '{"order_id":"ord-123","total":150000,"currency":"IDR"}', 'PENDING', NOW(), NOW()); COMMIT; 

If either insert fails, the whole transaction rolls back. Either both rows exist, or neither does.

3. The Relay: Claim, then Publish and Mark

Outbox relay process: claim a batch with SKIP LOCKED and a lease, then publish events and mark them as sent or retry

A straightforward relay locks a batch with SELECT ... FOR UPDATE, publishes to the broker, and only then commits. That keeps a database transaction and row locks open during a network call: if the broker is slow, transactions grow long, connections are held, and other writers wait.

Instead, split the relay into two steps so that publishing never happens inside a database transaction.

Step 1: Claim a batch

Each relay iteration generates a new claim_token (e.g. a UUID) and claims up to 100 pending events in a short transaction:

BEGIN; SELECT * FROM outbox WHERE status = 'PENDING' AND attempts < :max_attempts AND next_attempt_at <= NOW() AND (claimed_until IS NULL OR claimed_until < NOW()) ORDER BY created_at, id LIMIT 100 FOR UPDATE SKIP LOCKED; UPDATE outbox SET claim_token = :claim_token, claimed_until = NOW() + INTERVAL 30 SECOND -- the lease WHERE id IN (:claimed_ids); COMMIT; 

What each part of the claim does:

  • status = 'PENDING' selects events that are waiting to be published.
  • attempts < :max_attempts ensures that events that have reached the maximum number of failed attempts are no longer eligible for claiming.
  • next_attempt_at <= NOW() ensures that events are only retried when their scheduled retry time has arrived.
  • claimed_until IS NULL OR claimed_until < NOW() ensures that events are not claimed while another relay still holds a valid lease.
  • ORDER BY created_at, id picks the oldest eligible events first, using id as a tie-breaker.
  • LIMIT 100 limits the number of events claimed in one batch.
  • FOR UPDATE SKIP LOCKED prevents multiple relays from claiming the same rows concurrently.

The claimed rows are read in the same transaction, so the relay already has the events it needs for the next step. If the relay crashes after claiming but before publishing, nothing is lost: the events are still PENDING, and once the lease expires, any relay can claim them again.

Step 2: Publish and mark

// events = rows read and claimed in Step 1 for event in events: ok, err = broker.publish( destination = destination_for(event.event_type), payload = event.payload, message_id = event.id, ) if ok: UPDATE outbox SET status = 'SENT', sent_at = NOW(), claim_token = NULL, claimed_until = NULL WHERE id = :id AND claim_token = :claim_token else: if is_permanent(err) || event.attempts + 1 >= max_attempts: // See "Handle Permanent Failures and Replay" mark_as_failed(event, claim_token, err) else: delay = backoff(event.attempts + 1) UPDATE outbox SET attempts = attempts + 1, next_attempt_at = NOW() + INTERVAL :delay SECOND, last_error = :error, claim_token = NULL, claimed_until = NULL WHERE id = :id AND claim_token = :claim_token 

Publishing happens outside any database transaction. After each publish, the relay marks the event with a single, independent UPDATE. The WHERE claim_token = :claim_token condition makes sure it only updates events it still owns: if its lease has expired and another relay has claimed the event, the update simply matches no rows.

Important: mark an event as SENT only after the broker has confirmed the publish. If the confirmation times out, treat the outcome as unknown and retry. The message may have already been accepted by the broker, so retrying can result in duplicates. Retrying helps preserve at-least-once delivery semantics and avoids treating an uncertain outcome as a successful publish.

If the relay crashes after publishing but before marking, the lease expires, another relay claims the event again, and it is published twice. That is a duplicate, which idempotent consumers can handle. Marking first and publishing later would turn the same crash into a lost event, which is exactly what the Outbox Pattern is meant to prevent.

This is the core of the relay. However, implementing a reliable relay requires more than just claiming, publishing, and updating events. Several design considerations and production concerns must also be addressed, as discussed in the following sections.

Important Design Considerations

The Outbox Pattern solves the dual-write problem, but it does not eliminate every challenge in distributed systems. There are several design considerations you should understand before implementing it in production.

1. At-Least-Once Delivery and Idempotent Consumers

The relay uses an at-least-once publication strategy: it retries failed publications until the broker confirms them or the event reaches a terminal FAILED state. Because a publish may succeed even when its confirmation is lost, the same event may be published more than once. Therefore, consumers must be idempotent.

A simple approach is to record every processed event ID in the consumer's own database, in the same transaction as the side effect:

CREATE TABLE processed_events ( event_id CHAR(36) PRIMARY KEY, processed_at DATETIME NOT NULL ); 
on message(msg): tx = db.begin() try: tx.exec("INSERT INTO processed_events (event_id, processed_at) VALUES (?, NOW())", msg.message_id) catch DuplicateKeyError: tx.rollback() // already processed broker.ack(msg) // acknowledge so it isn't redelivered again return reduce_stock(tx, msg.payload) // the actual side effect tx.commit() broker.ack(msg) // acknowledge only AFTER the commit 

Two details matter here:

  • The dedupe record and the side effect share one transaction. If they were separate, a crash between them could skip the event or apply it twice.

  • Acknowledge the message only after committing. If the consumer acknowledges first and then crashes, the message is gone. If it commits first and crashes before acknowledging, the broker redelivers the message, and the primary key on event_id makes that duplicate a no-op.

Catch the duplicate key error explicitly rather than using something like INSERT IGNORE, which can also hide unrelated errors.

2. Event Ordering

Some events only make sense in a specific order. Take a single order in our e-commerce platform: when the customer places it, the service emits OrderCreated; a moment later, when the payment succeeds, it emits OrderPaid. Both events belong to the same order, and consumers expect them in that order. A warehouse service that receives OrderPaid first may try to ship an order it has never seen, and either fail or drop the event.

Events can reach the broker out of order for two reasons: several relays claim batches in parallel, and failed events wait for a retry with backoff. For example, if OrderCreated fails once and waits for its retry, OrderPaid for the same order could be published first.

To preserve ordering, only allow the oldest unfinished event from each aggregate to be claimed. When claiming, skip events whose aggregate still has an earlier PENDING or FAILED event, based on created_at (using id as a tie-breaker).

The basic claim query shown earlier does not enforce this restriction. To support per-aggregate ordering, the claim query needs an additional NOT EXISTS condition that prevents an event from being claimed while an earlier unfinished event exists for the same aggregate.

SELECT o.* FROM outbox o WHERE o.status = 'PENDING' AND o.attempts < :max_attempts AND o.next_attempt_at <= NOW() AND (o.claimed_until IS NULL OR o.claimed_until < NOW()) AND NOT EXISTS ( SELECT 1 FROM outbox older WHERE older.aggregate_id = o.aggregate_id AND older.status IN ('PENDING', 'FAILED') AND ( older.created_at < o.created_at OR ( older.created_at = o.created_at AND older.id < o.id ) ) ) ORDER BY o.created_at, o.id LIMIT 100 FOR UPDATE SKIP LOCKED; 

Note: Ordering by created_at and id provides a deterministic ordering based on event creation time, but it does not guarantee strict business ordering when multiple transactions for the same aggregate execute concurrently. If strict business ordering is required, use an explicit per-aggregate sequence number or version assigned transactionally.

The NOT EXISTS condition ensures that only the oldest unfinished event for each aggregate is eligible for claiming. Combined with FOR UPDATE SKIP LOCKED, multiple relays can process different aggregates concurrently without claiming the same event.

For example, if OrderCreated for order #123 is waiting for a retry, OrderPaid for #123 is skipped until OrderCreated is successfully published. Meanwhile, events from orders #124 and #125 can continue to be processed.

However, this only controls the order in which events are published, not necessarily the order in which consumers process them. If strict end-to-end ordering is required, events for the same aggregate should be routed to the same broker partition or ordered queue, and consumers must process them sequentially.

Note: Events marked as FAILED continue to block subsequent events from the same aggregate. They must be explicitly recovered or replayed and successfully published before later events are allowed to proceed.

3. Outbox Table Growth

The outbox table grows with every event.

Solution: regularly delete or archive rows with status = 'SENT' (for example, older than 7 days), so the claim query and its index stay small.

Building a Production-Ready Relay

The basic relay above works, but a few details decide whether it behaves well under slow brokers, crashes, and bad data.

1. Guard every update with the claim token

Always include AND claim_token = :claim_token when marking results. Imagine relay A claims a batch, then pauses (a long GC pause or a network stall) past its lease. Relay B claims the same events with a new token and publishes them. When relay A wakes up, its update matches zero rows, so it can't overwrite relay B's result.

The claim token prevents conflicting updates, but it does not prevent a duplicate publish: relay A may already have sent the messages before its lease expired. That's what the next practice addresses.

2. Manage Lease Duration and Publish Timeouts

If the broker is slow and publishing 100 events plus waiting for confirms takes longer than the 30-second lease, another relay will claim and publish the same events while the first relay is still working. To avoid this, derive a deadline from the lease and make sure the relay finishes, or gives up, before it:

// Step 1 sets claimed_until = NOW() + 30s using the database clock deadline = local_clock() + 25s // relay's own clock, 5s margin for marking for event in events: if local_clock() >= deadline: release_remaining_events() // not enough lease left, give them back break ok = broker.publish(event, timeout = deadline - local_clock()) mark_sent_or_retry(event, ok) 

Measure the deadline on the relay's own clock, starting right after the claim, rather than comparing against claimed_until. The lease is set by the database clock, and if the two clocks drift by a few seconds, the safety margin quietly disappears.

This way a relay never keeps working on events after its lease has expired. If the broker is slow, also consider smaller batches so a normal cycle fits comfortably within the lease. A process that freezes completely can still overrun its lease, so idempotent consumers remain the final safety net.

3. Retry with exponential backoff and jitter

Don't retry failed events immediately. Increase the delay after each attempt and add some randomness so many events don't retry at the same moment:

backoff(attempt): delay = min(BASE_DELAY * 2^(attempt - 1), MAX_DELAY) // 1s, 2s, 4s ... up to 5 min return delay + random_jitter(0, delay * 0.2) 

If the broker is down, backoff stops the relay from hammering it, and events simply wait in the outbox table until it recovers.

It also helps to distinguish transient from permanent errors. Connection failures and timeouts are usually transient, so they should be retried with exponential backoff and jitter. Although these failures still count toward the retry limit, use an appropriate MAX_ATTEMPTS value to avoid exhausting retries too quickly during temporary broker outages.

Errors like an invalid payload or an unknown destination are generally permanent and may be moved directly to FAILED, since retrying them will not resolve the underlying issue.

4. Handle Permanent Failures and Replay

Some events will never succeed on their own (a poison message). Without a retry limit, they may be retried indefinitely, wasting relay capacity and filling logs.

A common approach is to move an event to FAILED after MAX_ATTEMPTS (e.g. 10).

UPDATE outbox SET status = 'FAILED', attempts = attempts + 1, last_error = :error, claim_token = NULL, claimed_until = NULL WHERE id = :id AND claim_token = :claim_token; 

Events marked as FAILED should remain visible and recoverable rather than being silently discarded.

A production relay should provide:

  • Alerting: Notify operators when events enter the FAILED state.
  • Replay: Allow failed events to be retried after the underlying issue has been resolved.

For example, an operator can reset an event:

UPDATE outbox SET status = 'PENDING', attempts = 0, next_attempt_at = NOW(), last_error = NULL WHERE id = :id AND status = 'FAILED'; 

5. Optimize Relay Queries with Indexes

As the outbox table grows, relay queries can become increasingly expensive. Without appropriate indexes, finding eligible events and checking for earlier unfinished events can require scanning a large number of rows.

Consider the following indexes as starting points:

CREATE INDEX idx_outbox_claim ON outbox (status, next_attempt_at, created_at, id); CREATE INDEX idx_outbox_aggregate_order ON outbox (aggregate_id, status, created_at, id); 
  • idx_outbox_claim helps the relay filter eligible pending events based on their status and retry time.
  • idx_outbox_aggregate_order helps the relay check for earlier unfinished events belonging to the same aggregate when per-aggregate ordering is required.

These indexes are starting points rather than universal solutions. Validate their effectiveness using EXPLAIN and actual workload measurements, as the optimal index design depends on the database engine, data distribution, and query patterns.

6. Monitor and Operate the Relay

A reliable relay needs to be monitored continuously to detect publishing issues, retry exhaustion, and growing backlogs. Monitoring should focus on both the relay's operational health and the state of events in the outbox table.

Key metrics to monitor include:

  • Pending events: Track the number of events waiting to be published. A continuously growing backlog may indicate that the relay cannot keep up with incoming events.
  • Oldest pending event age: Measure how long the oldest unpublished event has been waiting. This helps detect delays that a simple event count might not reveal.
  • Failed events: Track the number of events in FAILED status and investigate recurring failure patterns.
  • Publish success and failure rates: Monitor broker publishing outcomes to detect connection issues or changes in broker availability.
  • Retry counts: Track how often events are retried to identify recurring transient failures or problematic event types.

When You Don't Need the Outbox Pattern

The Outbox Pattern adds a table, a relay, idempotent consumers, and monitoring. That cost is not always justified. You can skip it when:

  • Losing an event is acceptable. For non-essential analytics or activity tracking, publishing directly after the commit may be good enough. Know what you are accepting: a crash or broker outage between the commit and the publish drops the event silently. Never publish before the commit, or you will also produce phantom events.

  • There is no second system to update. The dual-write problem exists only when one operation must change two independent systems. If everything the operation affects lives in the same database, including consumers that simply read from it, a single local transaction is enough. Keep in mind that the second system is not always a broker: calling a payment gateway or an email provider after a commit has exactly the same problem.

As a rule of thumb: if a lost or phantom event would cost you money or customer trust, use the pattern. If it would only cost you a slightly incomplete dashboard, a simpler approach is probably enough.

Conclusion

The Transactional Outbox Pattern provides a reliable way to publish events without relying on distributed transactions between a database and a message broker.

By storing business changes and events in the same database transaction, it prevents the dual-write problem. A separate relay then publishes those events asynchronously, using retries and broker confirmations to provide at-least-once publication semantics for events that do not enter a terminal FAILED state.

However, reliability comes with operational responsibilities. Systems must account for duplicate delivery, event ordering, retries, and outbox table growth.

The pattern is particularly useful when consistency between database changes and event publishing is critical, but its complexity should be justified by the system's actual requirements.

原文:https://www.a8q9.cn/en/article/the-transactional-outbox-pattern-reliable-event-publishing-in-distributed-system-6da57c.html

相关文章