When to reach for it
- Agents trigger external side effects.
- Distributed transactions are unavailable.
- Error reversal is technically feasible.
Every forward step ships with its own undo.
A long-running transaction is split into steps, each paired with a compensating action; when a later step fails, the already-committed steps are undone in reverse order via their compensations, because a distributed transaction cannot hold a lock across all the resources at once.
In practiceA travel-booking agent books a flight, then a hotel; when the car-rental step fails, it automatically cancels the hotel and then the flight via their respective compensating actions.
Every step that changes something outside comes with an action that undoes it. When a later step fails, the completed steps are undone in reverse order.
1 · Forward
2 · When a step fails
| Step | Action | Result |
|---|---|---|
| 1 | Book the flight | Booked |
| 2 | Book the hotel | Booked |
| 3 | Rent the car | Fails: no car is available |
| 4 | Compensate step 2: cancel the hotel | Cancelled |
| 5 | Compensate step 1: cancel the flight | Cancelled, with a fee of 50 EUR |
def book_trip(trip):
steps = [(book_flight, cancel_flight),
(book_hotel, cancel_hotel),
(rent_car, cancel_car)]
done = [] # compensations of the steps that committed
try:
for action, compensation in steps:
reference = action(trip)
done.append((compensation, reference))
except BookingError as error:
# undo in reverse order
for compensation, reference in reversed(done):
compensation(reference)
return f"Nothing booked: {error}"
return "Trip booked"When to reach for it
When it backfires
The refund step fails. The system is now half-rolled-back: order canceled, money still gone. Compensation is treated as if it cannot itself error.
Countermeasure
Treat each compensation as a workflow with its own retries and dead-letter. Persist intent before attempting compensation so a recovery process can drive it to completion.
One step has no possible undo — an email sent, a payment settled, a message posted. A later failure cannot roll it back, so the saga cannot restore a consistent state.
Countermeasure
Order irreversible steps last (the pivot), so everything before them is compensatable and everything after is retriable; gate a genuinely irreversible mid-flow action behind a human approval.
Keep going
Search patterns, frameworks, and pages.