Sub topic 12
The transactional outbox pattern
This chapter assumes you know how database transactions work (atomic commit and rollback). It also assumes you know the basics of brokers, at-least-once delivery, and idempotent consumers from earlier chapters.
The dual-write problem
A service often has to do two things when something happens: change its own database, and publish an event about the change. Consider an order service:
def place_order(order):
db.insert_order(order) # step 1: commit to the database
broker.publish("order.placed", order) # step 2: publish the eventThe database and the broker are separate systems, and no single transaction spans both. This is a dual write, and it can fail in two ways:
- The process crashes after step 1 and before step 2. The order exists, but no event is ever published. Stock is never reserved and no receipt is sent.
- You swap the order and publish first. If the database insert then fails, consumers react to an order that does not exist.
Wrapping the publish call in the database transaction does not fix this. The broker call is not part of the transaction, and a commit can still fail after the publish succeeded. Retries do not help either, because the process that would retry is the one that crashed.
The idea
The outbox pattern removes the dual write. The service writes the event into an outbox table in its own database, in the same local transaction as the business change. Both rows commit or neither does. A separate process, the relay, later reads the outbox and publishes to the broker.
-- Assumes tables orders(id, status) and outbox(id, event_type, payload, published_at) already exist.
BEGIN;
INSERT INTO orders (id, status) VALUES ('o-1', 'placed');
INSERT INTO outbox (id, event_type, payload)
VALUES ('evt-1', 'order.placed', '{"orderId": "o-1"}');
COMMIT;The request handler never talks to the broker. The question "did the event get recorded?" now has the same answer as "did the order get saved?", and the database guarantees that answer.
A working relay
The example below uses SQLite so you can run it as is. A production system would use your real database and a real broker client in place of the publish function.
import json
import sqlite3
def setup(conn):
conn.executescript(
"""
CREATE TABLE orders (id TEXT PRIMARY KEY, status TEXT NOT NULL);
CREATE TABLE outbox (
seq INTEGER PRIMARY KEY AUTOINCREMENT,
id TEXT NOT NULL UNIQUE,
event_type TEXT NOT NULL,
payload TEXT NOT NULL,
published_at TEXT
);
"""
)
def place_order(conn, order_id):
# "with conn" opens a transaction: commit on success, rollback on error.
with conn:
conn.execute("INSERT INTO orders (id, status) VALUES (?, 'placed')", (order_id,))
conn.execute(
"INSERT INTO outbox (id, event_type, payload) VALUES (?, ?, ?)",
(f"evt-{order_id}", "order.placed", json.dumps({"orderId": order_id})),
)
def relay_once(conn, publish, batch_size=100):
rows = conn.execute(
"SELECT seq, id, event_type, payload FROM outbox "
"WHERE published_at IS NULL ORDER BY seq LIMIT ?",
(batch_size,),
).fetchall()
for seq, event_id, event_type, payload in rows:
publish(event_id, event_type, payload) # may raise; row stays unpublished
with conn:
conn.execute(
"UPDATE outbox SET published_at = CURRENT_TIMESTAMP WHERE seq = ?",
(seq,),
)
return len(rows)
def publish(event_id, event_type, payload):
print("published", event_id, event_type, payload)
conn = sqlite3.connect(":memory:")
setup(conn)
place_order(conn, "o-1")
place_order(conn, "o-2")
print(relay_once(conn, publish)) # 2
print(relay_once(conn, publish)) # 0: nothing left to publishThe relay calls publish before it marks the row. If the process dies between those two steps, the row is still unpublished after a restart, and the relay publishes it again.
What the pattern guarantees
The outbox gives you at-least-once publication, and it does not give exactly-once. The failure window moves from "between the database and the broker" to "between the broker acknowledgment and the published_at update". An event can be published twice, but it cannot be lost.
Consumers must therefore be idempotent. The outbox row's id becomes the event ID in the envelope. Consumers use it to detect duplicates, as in the idempotent consumer chapter:
{
"id": "evt-o-1",
"type": "order.placed",
"version": 1,
"occurredAt": "2026-11-26T11:00:00Z",
"data": { "orderId": "o-1" }
}Generate the ID when you write the outbox row, and never in the relay. If the relay generated a new ID on each attempt, a redelivered event would look like a different event and the deduplication would fail.
Getting rows out: polling versus log tailing
There are two common ways to move rows from the outbox to the broker.
| Approach | How it works | Strengths | Weaknesses |
|---|---|---|---|
| Polling relay | A loop queries for rows where `published_at IS NULL` | Simple, works on any database, easy to debug | Adds query load, latency equals the polling interval, needs an index on unpublished rows |
| Change data capture (CDC) | A tool such as Debezium reads the database's transaction log and emits each outbox insert | Low latency, no polling queries, preserves commit order | Extra infrastructure, database-specific setup, harder to operate |
With CDC you often do not need the published_at column. The log is the source of truth, and the outbox table only exists so that inserts appear in the log. Start with polling unless you already run a CDC platform.
Edge cases
Several relay instances
Two relays reading the same unpublished rows will publish each event twice. Duplicates are tolerable, but constant duplication wastes work. In PostgreSQL, claim rows with SELECT ... FOR UPDATE SKIP LOCKED inside a transaction, so each relay instance takes a different batch. Alternatively, run one active relay with leader election.
Ordering
The relay publishes in seq order, which gives per-service ordering only in the simple case. With concurrent writers in PostgreSQL, a transaction can take sequence value 11, and another can take 12 and commit first. A relay that has already seen 12 may then skip 11 when it commits. Mitigations are:
- Read the log with CDC, which follows commit order.
- Allow the relay to rescan rows older than a safety window.
- Rely on partition keys and consumer-side version checks, not global order. Most systems only need ordering per entity. Publish with the aggregate ID (for example the order ID) as the partition key.
Growth of the table
Published rows pile up. Delete them or archive them on a schedule, for example rows published more than seven days ago. Keep an index on published_at or a partial index on unpublished rows, so the relay query stays fast as the table grows.
Poison rows
If one row always fails to publish (an oversized payload, say), a strict in-order relay blocks everything behind it. Count attempts per row. After a limit, move the row to a failed state and raise an alert. This is the same dead-letter idea as for consumers.
Payload content
Store the serialized event as it will be published, and do not rebuild it from current table state in the relay. Rebuilding gives you the state at publish time, which may be later than the state when the event occurred. That breaks the meaning of the event as a fact about the past.
The inbox mirror
The outbox protects the producer side. The consumer-side equivalent is an inbox: the consumer writes the event ID and its own state change in one local transaction, as in the idempotent consumer example. Together, the outbox and the inbox give effectively-once results on top of an at-least-once broker.
When to use it
Use an outbox when losing an event would leave systems permanently inconsistent, for example payments, orders, and inventory. You can skip it for events that are lossy by nature, such as click analytics, where a missed event costs little and the extra table and relay are not worth it. The cost is real: an extra table, a relay to operate and monitor, added latency, and cleanup work.
Exercise
A service commits an order and its outbox row, and the relay publishes the event to the broker. The relay then crashes before it sets published_at. What happens after the relay restarts, and what must the consumers do about it?
Show answer
The row is still unpublished, so the relay publishes the same event again, with the same event ID as before. The event is delivered at least once and never lost. Consumers must be idempotent: they record processed event IDs, ideally in the same transaction as their state change, and ignore the second copy.
Exercise
Why is it wrong for the relay to build the event payload from the current state of the orders table at publish time, and not from the payload stored in the outbox row?
Show answer
The relay may run well after the transaction. The order could have changed in between, so the event would describe the state at publish time instead of what happened at the time of the event. Consumers would see changes that have their own events, and the same event could carry different contents on a retry. Storing the payload in the outbox row fixes the content at commit time.