Sub topic 13
Sagas: Coordinating Multi-Step Processes
This chapter assumes you know what events, brokers and idempotent consumers are, and that you understand eventual consistency. It also assumes you know what a local database transaction is.
The problem a saga solves
Placing an order often touches several services. The order service records the order, the payment service charges the card, and the inventory service reserves stock. Each service owns its own database. A single ACID transaction cannot span all three without a distributed transaction protocol such as two-phase commit. That protocol couples the services tightly and often isn't available across brokers and independent databases.
A saga replaces one big transaction with a sequence of local transactions. Each step commits on its own and then publishes an event. That event triggers the next step. If a step fails, the saga does not roll back. Instead it runs compensating actions that undo the effects of the steps that already committed.
Compensation, not rollback
A compensating action is a new business action that semantically reverses an earlier one. A refund compensates a charge. A stock release compensates a reservation. The original change was committed and may already be visible to other users, so you cannot erase it.
Some steps have no clean reversal. You cannot unsend an email. Place such steps last, or make them a notification that tolerates a later correction.
Two ways to coordinate
| Style | How it works | Strength | Weakness |
|---|---|---|---|
| Choreography | Each service reacts to events from others. No central owner. | Loose coupling, simple for 2 or 3 steps | The flow is spread across services and is hard to see or change |
| Orchestration | A coordinator sends commands and tracks state. | The flow lives in one place and is easy to monitor | The coordinator is another component to build and run |
Choreography fits short flows. Once a process has many steps, branches or timeouts, an orchestrator is usually easier to reason about.
A minimal orchestrator
The sketch below runs steps in order. If one fails, it runs the compensations of the completed steps in reverse. A real orchestrator would persist its state after every step so it can resume after a crash.
def run_saga(steps):
done = []
for name, action, compensate in steps:
try:
action()
done.append((name, compensate))
print("done:", name)
except Exception as exc:
print("failed:", name, "-", exc)
for done_name, undo in reversed(done):
undo()
print("compensated:", done_name)
return "cancelled"
return "completed"
def charge_card():
raise RuntimeError("card declined")
steps = [
("reserve stock", lambda: None, lambda: None),
("charge card", charge_card, lambda: None),
]
print(run_saga(steps))Running it prints done: reserve stock, then the failure, then compensated: reserve stock, and finally cancelled.
Common errors
- Assuming isolation. Other requests can see the intermediate state, such as stock reserved for an order that is later cancelled. Model that state explicitly, for example with a
pendingstatus. - Non-idempotent steps. Brokers with at-least-once delivery redeliver messages. Every step and compensation needs a deduplication check.
- Lost events. If a step commits but its event is never published, the saga stalls. Use the outbox pattern for each step.
- No timeouts. A saga waiting forever for a reply holds resources. Set a deadline and treat expiry as a failure.
- Failing compensations. Retry with backoff, then send the case to a dead-letter queue or a human.
Exercise
An order saga has three steps: reserve stock, charge card, send confirmation email. The card charge fails. Which compensations run, and why is the email step placed last?
Show answer
Only the stock reservation was completed, so only its compensation (release stock) runs. The charge never succeeded, so it needs no refund. The email is placed last because it cannot be undone, so it should run only after every step that might fail has succeeded.