Introduction
In any system that must update a local database and notify an external system (a message broker, a cache, a search index), there is a fundamental coordination problem.
You need both operations to succeed or both to fail.
You have no distributed transaction spanning the two systems.
This is the dual write problem: two writes to two different systems without atomicity guarantees.
The outbox pattern is the most widely adopted solution, converting the dual write into a single atomic local write followed by an eventually consistent relay to the external system.
The Dual Write Problem
Consider a service that processes an order.
It must write the order to its database and publish an OrderCreated event to a message broker so that downstream services (inventory, billing, and shipping) can react.
The naive implementation looks like this:
1. BEGIN database transaction
2. INSERT order INTO orders table
3. COMMIT database transaction
4. Publish OrderCreated event to message broker
This sequence has an obvious failure mode: the database commit succeeds at step 3, but the service crashes before step 4 executes.
The order exists in the database, but no event was ever published.
Downstream services never learn about the order.
Reversing the order does not help:
1. Publish OrderCreated event to message broker
2. BEGIN database transaction
3. INSERT order INTO orders table
4. COMMIT database transaction
Now the broker has the event, but a crash between steps 1 and 4 means downstream services process an order that does not exist in the database.
You might consider wrapping both operations in a distributed transaction using two-phase commit (2PC).
This is technically possible, but carries well-documented costs: increased latency, reduced availability (any participant can block the protocol), and the fact that most message brokers do not support XA transactions.
The combination of these factors makes 2PC impractical for the majority of microservice architectures.
The core issue is that a relational database and a message broker are two independent systems with independent durability guarantees.
Without a shared transaction coordinator, you cannot make a write to both systems atomic.
The Outbox Pattern
The outbox pattern eliminates the dual write by reducing the problem to a single write target.
Instead of writing to both the database and the broker, the service writes only to the database, using two tables within the same local transaction: the domain table and an outbox table.
How It Works
The service performs one atomic database transaction containing two inserts:
- Insert or update the domain entity (e.g., the
orderstable). - Insert the corresponding event into an
outboxtable in the same database.
Because both writes target the same database, the local ACID transaction guarantees atomicity.
Either both the order and the outbox record are persisted, or neither is.
A separate process, called the relay or publisher, reads unpublished rows from the outbox table and forwards them to the message broker.
Once the broker acknowledges receipt, the relay marks the outbox row as published (or deletes it).
Outbox Table Schema
A minimal outbox table includes:
| Column | Type | Purpose |
|---|---|---|
| id | UUID | Unique event identifier for deduplication |
| aggregate_type | VARCHAR | Type of entity (e.g., "Order") |
| aggregate_id | VARCHAR | ID of the entity that produced the event |
| event_type | VARCHAR | Event name (e.g., "OrderCreated") |
| payload | JSONB | Serialized event data |
| created_at | TIMESTAMP | When the event was created (not reliable for relay ordering) |
| published | BOOLEAN | Whether the relay has forwarded this event |
| published_at | TIMESTAMP | When the relay successfully forwarded the event (nullable) |
Note on ordering: Do not rely on
created_atalone for relay ordering. Under concurrent transactions, two rows can share the same millisecond timestamp or be inserted in a different wall-clock order than their commit order. Use a database-generated monotonic sequence (e.g., aBIGSERIALcolumn populated at insert time, or the PostgreSQL transaction ID viapg_current_xact_id()) as the relay cursor to guarantee correct causal ordering.
Walkthrough
The following step-by-step walkthrough covers the complete lifecycle of an event through the outbox pattern.
Step 1: Atomic Local Write
BEGIN TRANSACTION;
INSERT INTO orders (id, customer_id, total, status)
VALUES ('ord-123', 'cust-456', 99.00, 'CREATED');
INSERT INTO outbox (id, aggregate_type, aggregate_id, event_type, payload, created_at, published)
VALUES (
'evt-789',
'Order',
'ord-123',
'OrderCreated',
'{"orderId": "ord-123", "customerId": "cust-456", "total": 99.00}',
NOW(),
FALSE
);
COMMIT;
At this point, the event exists durably in the database.
No message has been sent to any broker.
Step 2: Relay Polls the Outbox
When running multiple relay instances (for high availability), use SELECT FOR UPDATE SKIP LOCKED to ensure each row is processed by only one relay instance at a time:
-- Pseudocode for the relay process (concurrent-safe)
LOOP every N milliseconds:
BEGIN TRANSACTION;
rows = SELECT * FROM outbox
WHERE published = FALSE
ORDER BY sequence_number -- monotonic column, not created_at
LIMIT 100
FOR UPDATE SKIP LOCKED;
FOR each row IN rows:
broker.publish(row.event_type, row.payload, headers={idempotency_key: row.id});
UPDATE outbox
SET published = TRUE, published_at = NOW()
WHERE id = row.id;
END FOR;
COMMIT;
END LOOP;
SKIP LOCKED causes competing relay instances to skip rows that another instance has already locked, preventing duplicate in-flight processing within the relay tier (though consumers must still handle duplicates as described below).
Step 3: Consumer Processes Event
Downstream consumers receive the OrderCreated event from the broker and execute their own logic.
Because the relay might republish an event (e.g., after crashing between publishing to the broker and marking the row as published), consumers must be idempotent.
The id field in the outbox row serves as a natural idempotency key.
Step 4: Outbox Cleanup
Published rows accumulate over time.
A background job should periodically delete or archive rows where published = TRUE and published_at is older than some retention threshold.
Ensure the cleanup query does not race with an active relay read: deleting rows that the relay has locked (but not yet committed) is safe with SELECT FOR UPDATE SKIP LOCKED in the cleanup job as well or by filtering on published_at with a conservative lag (e.g., older than 24 hours) to avoid touching recently published rows.
Relay Strategies
There are two primary approaches for the relay component.
Polling Publisher
The relay periodically queries the outbox table, as shown in the walkthrough above.
This is simple to implement and works well at moderate throughput.
The tradeoff is latency (bounded by the polling interval) and load on the database from repeated queries.
Indexing the published column (or using a partial index on published = FALSE) and keeping the outbox table small through cleanup mitigate the query cost.
Transaction Log Tailing (CDC)
Instead of polling the outbox table, the relay reads the database's write-ahead log (WAL in PostgreSQL, binlog in MySQL).
Tools like Debezium connect to the database's replication stream, detect inserts into the outbox table, and forward them to the broker.
This approach has lower latency (events are captured as soon as they are committed), eliminates polling overhead, and scales better.
The cost is operational complexity: you must manage a CDC connector, handle the fact that the WAL exposes the database's internal row format rather than your application-level event schema (requiring a transform step), and ensure the connector itself is highly available.
A dedicated outbox table with an explicit payload column isolates your event schema from internal domain table schema changes, which is one reason a dedicated outbox table is preferred over capturing changes directly from domain tables.
Failure Modes and Guarantees
The outbox pattern provides at-least-once delivery.
The following failure scenarios illustrate why:
Service crashes after database commit. The outbox row is persisted.
The relay will eventually pick it up and publish the event.
No data is lost.
Relay crashes after publishing to broker but before marking the row as published. On restart, the relay will re-read the same row and publish the event again.
The consumer receives a duplicate.
This is why consumer idempotency is essential.
Broker is temporarily unavailable. The relay fails to publish.
It retries on the next polling cycle (or the CDC connector retries).
The event remains in the outbox table until delivery succeeds.
The pattern does not provide exactly-once delivery to consumers.
Exactly-once semantics require end-to-end cooperation: the broker, the consumer, and the consumer's datastore must all participate.
The outbox pattern's responsibility is to guarantee that every committed domain change has a corresponding event that will eventually reach the broker.
Ordering Guarantees
Within a single aggregate (identified by aggregate_id), events are inserted in commit order.
The relay must process them using a reliable monotonic cursor (such as a sequence number assigned at insert time) rather than created_at timestamps, which are not guaranteed to reflect commit order under concurrent load.
If the broker routes events for the same aggregate to the same partition (as Kafka does via a partition key), consumers observe events in causal order for that aggregate.
Cross-aggregate ordering is not guaranteed and typically should not be relied upon.
Comparison with Other Approaches
Event Sourcing avoids the dual write entirely by making the event log the primary source of truth.
There is no separate domain table; the current state is derived by replaying events.
This is a more radical architectural shift, but eliminates the need for an outbox.
Listen to Yourself is a pattern where the service publishes to the broker first and then consumes its own event to update the database, making the broker the authoritative source of truth.
This inverts the typical source-of-truth relationship and introduces consistency challenges, particularly around read-your-writes semantics and what happens if the broker delivery succeeds but the subsequent database write fails.
Change Data Capture on the domain table (without a dedicated outbox table) captures row-level changes directly from the domain table's WAL entries.
This works but conflates the domain table's storage schema with the event schema, making independent evolution of each difficult.
A dedicated outbox table gives you explicit control over the event payload and format.
Key Points
- The dual write problem arises whenever a service must update two independent systems (typically a database and a message broker) without a shared atomic commit protocol.
- The outbox pattern solves this by writing the domain change and the event into the same database transaction, then asynchronously relaying the event to the broker.
- The relay component can be implemented via polling or transaction log tailing (CDC), with CDC offering lower latency at the cost of operational complexity.
- Polling relays should use
SELECT FOR UPDATE SKIP LOCKEDwhen multiple relay instances run concurrently to avoid duplicate in-flight processing. - Relay ordering should be based on a monotonic sequence column, not wall-clock timestamps, to correctly reflect commit order under concurrency.
- The pattern guarantees at-least-once delivery, meaning consumers must implement idempotent processing to handle duplicate events.
- Ordering is preserved per aggregate when the relay uses a monotonic cursor and the broker respects partition assignment.
- Outbox rows require periodic cleanup to prevent unbounded table growth and query degradation; cleanup jobs should avoid racing with active relay reads.
- Two-phase commit is the theoretically correct alternative, but is impractical in most microservice deployments due to availability, latency, and broker compatibility constraints.
References
Kleppmann, Martin. Designing Data-Intensive Applications. O'Reilly Media, 2017.
Hohpe, Gregor and Woolf, Bobby. Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions. Addison-Wesley, 2003.
Richardson, Chris. Microservices Patterns: With Examples in Java. Manning Publications, 2018.
Gray, Jim and Reuter, Andreas. Transaction Processing: Concepts and Techniques. Morgan Kaufmann, 1993.
Debezium Documentation: Outbox Event Router. Red Hat. https://debezium.io/documentation/reference/stable/transformations/outbox-event-router.html