Sub topic 10
Keeping state consistent: outbox and sagas
This chapter assumes you know database transactions, the retry and idempotency ideas from earlier chapters, and short Python and SQL snippets. It covers two patterns that keep a payment service consistent when one action touches the database and something else.
The dual-write problem
When a payment is captured, the service must update its own database and tell other systems, such as the ledger or a webhook sender. A database and a message broker do not share a transaction. If you write to both, one write can succeed while the other fails.
- Commit first, then publish: a crash between the two loses the event.
- Publish first, then commit: a rollback leaves an event for something that never happened.
Transactional outbox
The outbox pattern writes the event into an outbox table in the same local transaction as the state change. A separate relay process reads unsent rows and publishes them.
BEGIN;
UPDATE payments SET status = 'captured' WHERE id = :payment_id AND status = 'authorized';
INSERT INTO outbox (id, aggregate_id, event_type, payload, published_at)
VALUES (gen_random_uuid(), :payment_id, 'payment.captured', :payload, NULL);
COMMIT;The state change and the event now commit together or not at all. The relay publishes rows where published_at IS NULL, then marks them. If it crashes after publishing but before marking, the event is sent again. Delivery is therefore at least once, so consumers must deduplicate, for example by event id.
Sagas
A saga is a sequence of local transactions across services, each with a compensating action that undoes it. You use one when a business operation spans services and no distributed transaction is available.
Example: a payment that must reserve inventory, authorize the card, and create a shipment.
- Reserve inventory.
- Authorize the card.
- Create the shipment.
If step 3 fails, run compensations in reverse: void the authorization, then release the inventory. Compensations must themselves be idempotent and retryable, since they can fail too.
def run_saga(steps):
"""steps: list of (action, compensation) callables."""
done = []
try:
for action, compensation in steps:
action()
done.append(compensation)
except Exception:
for compensation in reversed(done):
compensation()
raiseThis sketch keeps state in memory. A real saga persists its progress, usually in a table, so it can resume after a crash.
Orchestration and choreography
| Style | How it works | Trade-off |
|---|---|---|
| Orchestration | A coordinator tells each service what to do next | Easy to follow and monitor, but the coordinator is a central component |
| Choreography | Services react to each other's events | Loosely coupled, but the overall flow is hard to see |
Common errors
- Publishing events directly after commit instead of using an outbox.
- Consumers that are not idempotent, so duplicate events cause double effects.
- Compensations that cannot run twice safely.
- Treating a captured payment as undoable by a compensation. Money that has moved needs a refund, which is a new forward action.
Exercise
A service commits the payment update, then publishes payment.captured to the broker. The process crashes between the two steps. What happens, and which pattern fixes it?
Show answer
The payment is captured but no event is ever published, so downstream systems such as the ledger never learn about it. The transactional outbox fixes this by writing the event in the same transaction as the update, so a relay can publish it later. Consumers must tolerate duplicates.
Exercise
Why must saga compensations be idempotent?
Show answer
A compensation can fail or time out and be retried, or the coordinator can crash and replay it. If running it twice has a different effect than running it once, such as releasing inventory twice, state becomes wrong.