Sub topic 14
The transactional outbox pattern
This chapter assumes you know how producers, brokers, and acknowledgements work, and that you have read the chapters on at-least-once delivery and idempotent consumers. You should also know basic SQL transactions. The examples use Python with sqlite3, plus pika for RabbitMQ.
The dual-write problem
A service often needs to change its own database and tell other services about the change. An order service saves an order and then publishes order.created. The code looks harmless:
- Insert the order into the database and commit.
- Publish the event to the broker.
The database and the broker are separate systems, and no single transaction covers both. A dual write is a write to two such systems in one operation, and it can fail halfway:
- The commit succeeds and the process crashes before step 2. The order exists, but no event is ever sent.
- You swap the order and publish first. The event goes out, then the commit fails. Consumers react to an order that does not exist.
- The publish times out. You don't know whether the broker received the message, so a retry might send a duplicate.
Retries inside the request don't fix this. A crash can happen between any two lines, and a crashed process cannot retry anything.
The pattern
The transactional outbox stores the event in the same database as the business data, in the same transaction. A separate process, the relay, reads stored events and publishes them to the broker.
The business write and the "intent to publish" now commit or roll back together. The only remaining failure is between the relay's publish and its bookkeeping, and at-least-once delivery with an idempotent consumer already handles that case.
Writing to the outbox
The outbox is an ordinary table in the service's own database. Each row holds the message ID, the destination, and the payload.
import json
import sqlite3
import uuid
db = sqlite3.connect(":memory:")
db.executescript(
"""
CREATE TABLE orders (id TEXT PRIMARY KEY, item TEXT NOT NULL);
CREATE TABLE outbox (
id INTEGER PRIMARY KEY AUTOINCREMENT,
message_id TEXT NOT NULL UNIQUE,
topic TEXT NOT NULL,
payload TEXT NOT NULL,
published_at TEXT
);
"""
)
def place_order(db, item):
order_id = str(uuid.uuid4())
event = {"order_id": order_id, "item": item}
with db: # one transaction: both inserts commit, or neither does
db.execute("INSERT INTO orders (id, item) VALUES (?, ?)", (order_id, item))
db.execute(
"INSERT INTO outbox (message_id, topic, payload) VALUES (?, ?, ?)",
(str(uuid.uuid4()), "order.created", json.dumps(event)),
)
return order_idThe with db: block commits on success and rolls back on an exception. If the order insert fails, no outbox row exists. If the process dies mid-block, the database discards both rows.
Generate the message_id when you write the row, not when you publish. Every retry of the same row then carries the same ID, which gives consumers a stable key for deduplication.
The relay
The simplest relay polls. It selects unpublished rows in order, publishes each, and marks it as published only after the broker confirms.
def relay_once(db, publish, batch_size=100):
rows = db.execute(
"SELECT id, message_id, topic, payload FROM outbox "
"WHERE published_at IS NULL ORDER BY id LIMIT ?",
(batch_size,),
).fetchall()
sent = 0
for row_id, message_id, topic, payload in rows:
publish(topic, message_id, payload) # raises on failure
with db:
db.execute(
"UPDATE outbox SET published_at = datetime('now') WHERE id = ?",
(row_id,),
)
sent += 1
return sent
calls = []
def flaky_publish(topic, message_id, payload):
calls.append(message_id)
if len(calls) == 1:
raise ConnectionError("broker unavailable")
print("published", topic, message_id)
place_order(db, "keyboard")
try:
relay_once(db, flaky_publish)
except ConnectionError:
print("first attempt failed, row stays unpublished")
print("second attempt sent", relay_once(db, flaky_publish))The first attempt fails and leaves the row unmarked. The second attempt picks it up. Nothing is lost, which is the point of the pattern.
A real publish function would use publisher confirms so that it returns only after the broker has accepted the message:
import pika
conn = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
ch = conn.channel()
ch.queue_declare(queue="order.created", durable=True)
ch.confirm_delivery() # basic_publish now raises if the broker rejects the message
def publish(topic, message_id, payload):
ch.basic_publish(
exchange="",
routing_key=topic,
body=payload.encode(),
properties=pika.BasicProperties(
message_id=message_id,
delivery_mode=pika.DeliveryMode.Persistent,
),
mandatory=True,
)What the pattern guarantees
The outbox gives you at-least-once publishing. It does not give you exactly-once.
Suppose the relay publishes a message, the broker confirms, and the relay crashes before the UPDATE. On restart the row still looks unpublished, so the relay publishes it again. The broker now holds two copies with the same message_id.
This is why the outbox pairs with an idempotent consumer. The consumer records each message_id in the same transaction as its side effect, as in the earlier chapter, and ignores repeats. The outbox removes lost events on the producer side. The idempotent consumer removes duplicate effects on the consumer side. You need both.
Ordering and multiple relays
The relay above orders rows by id, so a single relay publishes events in the order they were committed. Two edge cases weaken this.
- Concurrent transactions. With autoincrement IDs, a transaction that took ID 7 can commit after the one with ID 8. A poller can read row 8, publish it, and only later see row 7. If strict order matters, use a database-specific commit order, such as a log sequence number, or accept that order holds only per aggregate (for example, per order ID) and have consumers cope.
- Several relays. Running two relays for availability makes both read the same unpublished rows, which doubles duplicates and can reorder events. Either run one active relay with a standby, or have each relay claim rows with a lock. PostgreSQL, for example, supports
SELECT ... FOR UPDATE SKIP LOCKED. Note that a lock held only during the select doesn't prevent a double publish, so keep the lock until the row is marked.
Partitioning by aggregate ID, so that one relay owns all events for a given key, keeps per-key order while still scaling out.
Polling versus change data capture
Polling is simple and works with any database, but it adds a steady read load and a delay equal to the poll interval. An index on unpublished rows keeps the query cheap:
CREATE INDEX outbox_unpublished ON outbox (id) WHERE published_at IS NULL;The alternative is change data capture (CDC). A tool such as Debezium reads the database's own transaction log and turns inserts into the outbox table into broker messages. CDC has lower latency and no polling load, and it preserves commit order. The costs are another component to run, database-specific configuration, and extra work to monitor replication lag.
| Aspect | Polling relay | CDC on the log |
|---|---|---|
| Setup | A small loop in your code | A separate connector and log access |
| Latency | Up to one poll interval | Typically well under a second |
| Database load | Repeated queries | Reads the log, no queries |
| Commit order | Needs care | Follows the log |
| Delivery | At least once | At least once |
Start with polling unless latency or load forces the move.
Operating the outbox
- Clean up. The table grows forever if you never delete. Remove rows with
published_atolder than a retention window, in small batches, so a long delete doesn't hold locks. Keeping rows briefly helps with debugging and replay. - Watch the backlog. The count of unpublished rows and the age of the oldest one are your key metrics. A growing age means the relay is stuck or the broker is down. Alert on the age.
- Handle poison rows. A row that always fails to publish, such as an oversized payload, blocks all later rows if the relay stops at the first error. Count attempts per row and move rows that exceed a limit aside, like a dead-letter queue for the outbox.
- Keep payloads self-contained. Store the full event, not just a row ID to look up later. Data may change before the relay runs, and the event should describe what happened at commit time.
Common mistakes
- Publishing inside the transaction, before commit. A rollback then leaves a message for a change that never happened.
- Marking a row published before the broker confirms. A crash then loses the event, which brings back the problem the pattern solves.
- Skipping consumer idempotency because "the outbox is reliable". It is reliable about delivery, not about duplicates.
- Writing the outbox row from a second database connection. It then falls outside the business transaction.
Exercise
A relay publishes an outbox row to the broker, receives a confirmation, and crashes before it runs the UPDATE that sets published_at. What happens after the restart, and which part of the system makes this safe?
Show answer
After the restart the row still has publishedat set to NULL, so the relay publishes it again and the broker holds two messages with the same messageid. The outbox guarantees at-least-once publishing, so this duplicate is expected. The idempotent consumer makes it safe: it records message_id in the same transaction as its side effect and ignores the second copy. Marking the row only after the broker confirms is what prevents the opposite failure, a lost event.
Exercise
Why should the message_id be generated when the outbox row is inserted instead of when the relay publishes it?
Show answer
A row can be published several times if the relay retries or crashes after publishing. If the ID is created at publish time, each attempt gets a different ID and consumers cannot recognize the copies as duplicates. An ID stored in the row stays the same on every attempt, so the consumer can deduplicate on it.