A service saved an order to the database and crashed before it could send the event to the broker: the payment never started, and the neighbouring service never learned about the order. The reverse is no better — the message went out, but the transaction rolled back. The transactional outbox pattern solves this dual-write problem between the database and the broker.
How it works
The service does not send the message to the broker directly. Instead, in the same transaction as the business data changes, it inserts an event into the outbox table: the transaction either commits the order and the event together or rolls both back. A separate process — the relay — then reads the table and publishes the events to the broker, marking them as sent.
| Participant | Role |
|---|---|
| Sender | the service: writes business data and the event in one transaction |
| Outbox table | holds unsent events; in NoSQL, a field on the record instead of a table |
| Relay | a separate process: reads the table and publishes events to the broker |
| Broker | delivers events to subscribers |
BEGIN; INSERT INTO orders (id, customer_id, total) VALUES (100500, 42, 1990); INSERT INTO outbox (id, aggregate_id, type, payload) VALUES ('7c9e6679-742f', 100500, 'OrderCreated', '{"total": 1990}'); COMMIT; What it guarantees and what it costs
If the transaction commits, the message is guaranteed to reach the broker; if it rolls back, the message is never sent. A two-phase commit between the database and the broker will not do: the database or the broker may not support it, and coupling a service to two stores at once is undesirable. Order is preserved: events reach the broker in the order in which the service committed its transactions.
- The relay may publish an event twice — if it crashes after sending but before marking the table — so the consumer must be idempotent, for example by storing the IDs of processed messages.
- The event reaches the broker with a delay: the relay polls the table or reads the database log.
- Publishing is no longer automatic: a developer can forget to insert a row into the outbox.
How the relay picks up events
| Approach | How it works |
|---|---|
| Polling publisher | the relay polls the outbox table at intervals; works with any SQL database, but preserving the order of events is harder |
| Transaction log tailing | the relay reads the database transaction log (CDC), for example via Debezium; requires database-specific solutions |
Sagas and domain events are what most often call for the pattern; its alternative is event sourcing, where the event history is itself the data store. Chris Richardson described the pattern in the microservices.io catalogue; Debezium, a change data capture (CDC) platform, supports the same approach under the name outbox pattern.
Sources
the term is written from these pagesVerified 8 Nov