Sub topic 10
Keeping state consistent: outbox and sagas
This chapter assumes you know relational transactions, the payment state machine and idempotency keys from earlier chapters, and basic message queues. You should also be able to read short Python and SQL.
The problem: two systems, one operation
A payment service rarely changes only its own database. After it captures a payment, it must also tell the order service, send a receipt and update analytics. It can fail between any two of those steps.
Consider this naive code:
- Update the payment to
capturedand commit. - Publish a
payment.capturedevent to a message broker.
If the process crashes between steps 1 and 2, the payment is captured but nobody hears about it. Swapping the order is worse. If you publish first and the commit then fails, other services act on a capture that never happened.
This is the dual-write problem. A database and a broker cannot share one transaction, so any code that writes to both can leave them disagreeing. A payment system cannot accept that, because the disagreement means a customer is charged and the order is never fulfilled, or the reverse.
Two patterns address this. The transactional outbox solves it for one service and one database. A saga solves it for a business operation that spans several services.
The transactional outbox
The outbox pattern turns the two writes into one. You write the event into an outbox table in the same database transaction as the state change. A separate process, the relay, reads unpublished rows and sends them to the broker.
The database transaction gives you atomicity. Either the payment update and the outbox row both commit, or neither does. Publishing becomes a separate step that can be retried until it succeeds.
The following script runs as shown. It uses SQLite so you can try it without a server, but the same structure works in PostgreSQL.
import json
import sqlite3
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE payments (id TEXT PRIMARY KEY, status TEXT NOT NULL);
CREATE TABLE outbox (
id INTEGER PRIMARY KEY AUTOINCREMENT,
event_type TEXT NOT NULL,
payload TEXT NOT NULL,
published INTEGER NOT NULL DEFAULT 0
);
""")
def capture(payment_id):
with db: # one transaction: commits on success, rolls back on error
cur = db.execute(
"UPDATE payments SET status = 'captured' "
"WHERE id = ? AND status = 'authorized'",
(payment_id,),
)
if cur.rowcount != 1:
raise ValueError("payment is not in the authorized state")
db.execute(
"INSERT INTO outbox (event_type, payload) VALUES (?, ?)",
("payment.captured", json.dumps({"payment_id": payment_id})),
)
def relay_once(publish):
rows = db.execute(
"SELECT id, event_type, payload FROM outbox "
"WHERE published = 0 ORDER BY id"
).fetchall()
for event_id, event_type, payload in rows:
publish(event_id, event_type, payload) # may raise; the row stays unpublished
with db:
db.execute("UPDATE outbox SET published = 1 WHERE id = ?", (event_id,))
db.execute("INSERT INTO payments VALUES ('p1', 'authorized')")
db.commit()
capture("p1")
relay_once(lambda i, t, p: print("published", i, t, p))
relay_once(lambda i, t, p: print("never printed")) # nothing left to sendThe WHERE status = 'authorized' condition in the update enforces the state machine inside the database. A second concurrent capture matches zero rows and fails, so it writes no second event.
At-least-once delivery
Look at the relay again. It publishes, then marks the row as published. If it crashes between those two lines, the next run publishes the same event again. The outbox therefore gives you at-least-once delivery, not exactly-once.
You cannot close that gap by reordering the two steps. Marking the row first and then publishing would lose the event on a crash, which is worse. The standard answer is to accept duplicates and make consumers idempotent:
- Give each event a stable ID. The outbox row ID works, as long as it is sent with the event.
- Have each consumer store the IDs it has processed, in the same transaction as its own changes.
- Have the consumer skip an event whose ID it has already seen.
This is the same idea as the idempotency key on your API, applied to messages.
Relay options and ordering
There are two common ways to run the relay.
| Approach | How it works | Trade-off |
|---|---|---|
| Polling relay | A worker queries unpublished rows on a short interval. | Simple to build and run. It adds latency and read load on the database. |
| Change data capture (CDC) | A tool reads the database's write-ahead log and publishes new outbox rows. | Low latency and no polling load. It needs more infrastructure and operational skill. |
If you run several polling workers, they can pick up the same rows. Use SELECT ... FOR UPDATE SKIP LOCKED in PostgreSQL so each worker claims different rows.
Ordering matters for payments. A captured event must not overtake the authorized event for the same payment. Publish events for one payment in order, for example by using the payment ID as the broker partition key. Order across different payments rarely matters.
Delete or archive published rows on a schedule. Otherwise the table grows without limit and slows the relay's query.
Sagas
The outbox keeps one service consistent with its own events. Many payment operations touch several services, each with its own database. A distributed transaction (two-phase commit) across them is usually unavailable, because PSPs and external banks do not take part in it. It also blocks on a failed coordinator.
A saga replaces one large transaction with a sequence of local transactions. Each step commits on its own. If a later step fails, the saga runs a compensating action for each completed step, in reverse order. A compensation is a new action that semantically undoes the earlier one, not a database rollback.
For example, a checkout saga might:
- Reserve inventory. Compensation: release the reservation.
- Authorize the card at the PSP. Compensation: void the authorization.
- Create the order. Compensation: cancel the order.
def run_saga(steps):
"""steps: list of (name, action, compensation) tuples."""
completed = []
try:
for name, action, compensation in steps:
action()
completed.append((name, compensation))
except Exception as exc:
print("step failed:", exc)
for name, compensation in reversed(completed):
compensation()
print("compensated:", name)
return "rolled_back"
return "completed"
def fail():
raise RuntimeError("order service unavailable")
result = run_saga([
("reserve_inventory", lambda: print("reserved"), lambda: print("released")),
("authorize_card", lambda: print("authorized"), lambda: print("voided")),
("create_order", fail, lambda: print("order cancelled")),
])
print(result)This version keeps its progress in memory. A production saga must persist its state after every step, for example in a saga_instances table. After a crash, a worker can then resume it or finish the compensations. Use the outbox to emit each step's command, so that recording progress and sending the next message are atomic.
Orchestration and choreography
There are two ways to drive a saga.
- Orchestration: one component, the orchestrator, tells each service what to do and tracks the saga's state. The flow is easy to read and monitor. The orchestrator becomes a component you must keep available.
- Choreography: each service reacts to events from the others and emits its own. There is no central component. The overall flow is spread across services and becomes hard to follow as steps are added.
For payments, orchestration is usually the better fit. Operators need to answer "where is this payment stuck?" quickly, and one saga record answers that.
Rules for compensations
Compensations carry most of the risk in a saga.
- Make every action and compensation idempotent. The orchestrator may retry either one after a timeout. Reuse the idempotency key approach for calls to the PSP.
- Expect compensations to fail. Retry them with backoff until they succeed, and alert a human if they cannot. A saga that stops halfway through compensating is the worst state to be in.
- Accept that some steps cannot be undone. A captured payment is not voided. Money must be refunded, which is a separate, visible operation with fees and delays. Place steps that are hard to undo late in the saga.
- Accept intermediate visibility. Other readers can see the inventory reserved before the saga finishes. Design states such as
pendingso that this is safe.
Choosing between them
Use the outbox whenever a state change must be accompanied by an event. It is cheap and has few moving parts. Add a saga when a business operation spans services or external systems and you need defined behavior when one step fails. Most payment systems use both. The saga's steps communicate through outbox events.
Exercise
The relay publishes an outbox event to the broker and crashes before marking the row as published. What happens on restart, and what must consumers do about it?
Show answer
The relay finds the row still unpublished and publishes the event a second time, because the outbox guarantees at-least-once delivery. Consumers must be idempotent. They should record the IDs of events they have processed, in the same transaction as their own changes, and skip any event whose ID they have already seen.
Exercise
A saga has authorized a card and then fails while creating the order. List what the saga must do next, and say why that action is not a database rollback.
Show answer
It runs the compensation for the authorization, which is to void it at the PSP, using an idempotent request and retrying until it succeeds. This is not a rollback because the authorization was already committed and recorded at the PSP. The void is a new action that appears in the PSP and ledger records next to the original.