Sub topic 13
Sagas: Coordinating Multi-Step Processes
This chapter assumes you know the earlier material: events, brokers, at-least-once delivery, idempotent consumers, and eventual consistency. It also assumes you know what a local database transaction guarantees.
The problem: one business action, several services
Placing an order can touch three services. The order service records the order. The payment service charges the card. The inventory service reserves stock. Each service owns its own database.
In a single database you would wrap all three changes in one transaction. If anything failed, the database would roll everything back. Across services there is no shared transaction. Distributed transactions (two-phase commit) exist, but they need every participant to support them, they hold locks while waiting on the network, and most brokers and cloud APIs do not take part in them.
A saga is the usual alternative. It splits the business action into a sequence of local transactions, one per service. Each step commits on its own. If a later step fails, the saga runs compensating actions that semantically undo the earlier steps.
What a saga guarantees
A saga gives you one outcome: either every step completes, or every completed step has been compensated. It does not give you isolation. While a saga is running, other readers can see its intermediate state. For example, stock is reserved but payment has not yet been taken.
Compensation is not rollback. A rollback erases a change as if it never happened. A compensation is a new business action that cancels the effect of the first one.
| Step | Compensation |
|---|---|
| Create order as `pending` | Mark order `cancelled` |
| Charge card | Issue a refund |
| Reserve stock | Release the reservation |
| Send confirmation email | Send a cancellation email (it cannot be unsent) |
The customer may have seen the charge and the refund. Both are real events in your history, and your design has to accept that.
Two ways to coordinate: choreography and orchestration
There are two styles of coordination.
In choreography, no one is in charge. Each service reacts to events and publishes its own. The order service publishes order.placed. The payment service reacts and publishes payment.completed or payment.failed. The inventory service reacts to payment.completed, and so on. Failure events trigger compensation in the services that already acted.
In orchestration, one component (the orchestrator) holds the saga's state. It sends commands to each service, waits for the reply events, and decides what happens next, including which compensations to run.
| Aspect | Choreography | Orchestration |
|---|---|---|
| Where the flow is defined | Spread across services | One place |
| Coupling | Services know which events to listen for | Services know only the commands they accept |
| Easy to follow | Gets hard beyond about 3 or 4 steps | Flow can be read in one file |
| Single point of concern | None, but cyclic dependencies can appear | Orchestrator must be reliable and not absorb business logic |
| Good fit | Short flows, few participants | Longer flows, branching, timeouts |
Choreography feels natural in event-driven systems, but the overall process becomes implicit. To answer "what happens when an order is placed?" you have to read every service. Orchestration makes the process explicit at the cost of one more component to run.
The saga as a state machine
An orchestrated saga is a state machine. Each state means "waiting for the reply to the last command". Each reply moves it forward or into compensation.
Note that PaymentFailed goes straight to Cancelled. Nothing needs compensating, because the failed step made no change. Compensation applies only to steps that completed.
A minimal orchestrator in Python
This in-memory version shows the core logic: run steps in order, remember which ones finished, and on failure run compensations in reverse order.
class PaymentDeclined(Exception):
pass
def create_order(ctx):
ctx["order"] = "pending"
print("order created")
def cancel_order(ctx):
ctx["order"] = "cancelled"
print("order cancelled")
def charge_card(ctx):
if ctx["card_ok"]:
ctx["charged"] = True
print("card charged")
else:
raise PaymentDeclined("card declined")
def refund_card(ctx):
ctx["charged"] = False
print("card refunded")
def reserve_stock(ctx):
if ctx["in_stock"]:
print("stock reserved")
else:
raise RuntimeError("out of stock")
def release_stock(ctx):
print("stock released")
STEPS = [
("create_order", create_order, cancel_order),
("charge_card", charge_card, refund_card),
("reserve_stock", reserve_stock, release_stock),
]
def run_saga(steps, ctx):
completed = []
for name, action, compensate in steps:
try:
action(ctx)
except Exception as exc:
print(f"step {name} failed: {exc}")
for done_name, undo in reversed(completed):
print(f"compensating {done_name}")
undo(ctx)
return "compensated"
completed.append((name, compensate))
return "completed"
print(run_saga(STEPS, {"card_ok": True, "in_stock": False}))The run prints order created, card charged, then step reserve_stock failed: out of stock. It then compensates charge_card and create_order in that order, and returns compensated. The failed step is not in completed, so it is not compensated.
Making it work in a real system
The in-memory sketch hides the hard parts. A production saga must handle these points.
- Persist saga state. The orchestrator can crash between steps. Store the saga ID, current state, and completed steps in a database. On restart, the orchestrator reads that record and continues.
- Send commands reliably. Updating saga state and sending the next command are two separate writes. Use the transactional outbox from the previous chapter, so the state change and the command are committed together.
- Make every step idempotent. Delivery is at-least-once, so a service may receive
ChargeCardtwice. Use the saga ID, or a step ID derived from it, as the idempotency key. The same applies to compensations: refunding twice would be a serious bug. - Handle timeouts. A reply may never arrive. Give each waiting state a deadline. When it passes, retry the command or start compensation.
- Make compensations retryable and, if possible, unable to fail permanently. If a refund fails, you cannot undo the saga. Retry with backoff, and route persistent failures to a dead-letter queue or a human operator.
Handling the missing isolation
Because other readers see intermediate state, sagas can produce anomalies similar to dirty reads. These countermeasures are common:
- Semantic status fields. Mark the order
pendingrather thanplaceduntil the saga finishes. Other code treatspendingas provisional. - Reorder steps. Put steps that are hard to undo, or that expose data to customers, at the end.
- Reservations instead of final changes. Reserve stock with an expiry, then confirm it. An unconfirmed reservation expires by itself.
- Commutative updates. Design updates so that order does not matter, such as adding and subtracting amounts rather than setting absolute values.
Common errors
- Treating compensation as rollback. Compensations create new facts. Design them as business operations, with their own events such as
payment.refunded. - No saga ID in events. Without a correlation ID you cannot tie events to one process, and you cannot debug a stuck saga.
- Business logic inside the orchestrator. The orchestrator should decide only the order of steps. Pricing, stock rules and similar decisions belong in the services.
- Cyclic event chains in choreography. Service A reacts to B, B to C, C to A. Draw the event graph before adding a new subscription.
- Forgetting the stuck states. Every state that waits needs a timeout and a way to see how many sagas sit in it for too long. Monitor this, as the observability chapter covers.
- Using a saga where one database would do. If all the data lives in one database, use a normal transaction.
Exercise
An order saga has three steps: reserve stock, charge the card, send a confirmation email. The charge step fails after stock was reserved. Which compensations run, in what order, and where should the email step be placed relative to the others? Also, what must the stock service do if the release command is delivered twice?
Show answer
Only the completed step is compensated, so the stock reservation is released. The charge step failed and made no change, and the email was never sent, so neither needs compensation. Because an email cannot be unsent, it should be the last step, after every step that can fail. If the release command arrives twice, the stock service must treat the second one as a no-op. It can do this by recording the saga ID (or a step ID) of the release it already applied, so stock is not released twice.