Sub topic 14
The transactional outbox pattern
This chapter assumes you know acknowledgements, at-least-once delivery, and idempotent consumers from the earlier chapters. You should also be comfortable with basic SQL transactions.
The dual-write problem
A service often has to change its database and also publish a message. For example, it saves an order and then publishes order_placed. These are two systems, and no single transaction covers both.
- If the service commits the row and crashes before publishing, the event is lost.
- If the service publishes first and the commit then fails, consumers see an event for an order that does not exist.
Retrying does not fix this. The process can die between the two steps, and the database and the broker then disagree.
The pattern
Write the message to an outbox table in the same database transaction as the business change. The two writes commit together or not at all. A separate process, the relay, reads unsent rows from the table and publishes them to the broker. Once the broker accepts a message, the relay marks the row as sent.
A runnable example
This uses SQLite to show the shape. The publish function stands in for a real broker client.
import json
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE orders (id INTEGER PRIMARY KEY, item TEXT)")
db.execute(
"CREATE TABLE outbox ("
"id INTEGER PRIMARY KEY AUTOINCREMENT, "
"payload TEXT NOT NULL, "
"sent INTEGER NOT NULL DEFAULT 0)"
)
def place_order(item):
with db: # one transaction: both inserts commit or neither does
cur = db.execute("INSERT INTO orders (item) VALUES (?)", (item,))
payload = json.dumps({"order_id": cur.lastrowid, "item": item})
db.execute("INSERT INTO outbox (payload) VALUES (?)", (payload,))
def relay_once(publish):
rows = db.execute(
"SELECT id, payload FROM outbox WHERE sent = 0 ORDER BY id"
).fetchall()
for row_id, payload in rows:
publish(row_id, payload)
with db:
db.execute("UPDATE outbox SET sent = 1 WHERE id = ?", (row_id,))
place_order("book")
relay_once(lambda message_id, body: print("published", message_id, body))Why consumers must still be idempotent
The relay publishes first and marks the row second. If it crashes between those steps, it publishes the same row again after a restart. The outbox therefore gives at-least-once delivery, not exactly-once.
Pass the outbox row id along as the message ID. Consumers can then use the deduplication approach from the idempotent consumers chapter.
Common errors
- Publishing from the request path. If the service publishes directly and uses the outbox only as a fallback, you have the dual-write problem again.
- Never cleaning up. Sent rows pile up. Delete them or archive them on a schedule.
- Several relays reading the same rows. They publish duplicates and can break ordering. Use one relay, or lock rows, for example with
SELECT ... FOR UPDATE SKIP LOCKEDin PostgreSQL. - Ignoring relay lag. Events appear after a delay. Monitor the count and age of unsent rows.
Polling or log tailing
| Approach | How it works | Trade-off |
|---|---|---|
| Polling relay | Queries the outbox table on an interval | Simple, but adds latency and database load |
| Change data capture | Reads the database's transaction log | Lower latency, but needs extra infrastructure |
Exercise
A service commits an order and its outbox row. The relay publishes the message, then crashes before marking the row as sent. What happens after the relay restarts, and how should the consumer handle it?
Show answer
The relay still sees the row as unsent and publishes it again, so the consumer receives a duplicate. The consumer should record the message ID (the outbox row id) in the same transaction as its side effect, so the second delivery is detected and skipped.