Compensation and recovery
Why compensation is needed
A local database transaction can commit or roll back changes within its transaction boundary. A distributed order process may involve inventory, payments and shipping, each with its own local transaction. A workflow does not automatically make those transactions atomic. A saga coordinates local commits and defines business actions that repair partial progress. Compensation is a new action, such as releasing a reservation; it is not necessarily a restoration of the entire original database state. Other orders may have changed stock in the meantime.
At Byte Books, reserve one book with reservation R17. If the mock payment is definitively declined, release R17, not every reservation for that book. If the payment outcome is unknown, reconcile it using the original operation ID first. A timeout is not a decline. If shipping is irreversible, recovery may require a return or manual review rather than reversing a database row. Choose compensation order by dependencies and business rules.
Run a local state transition model
The following Python example is an offline, sequential state-transition model. It has no network, real payment, database, scheduler or durable state. An event must already be verified by the caller. Unrecognized or out-of-order events leave the state unchanged; a real service must also log, validate and distinguish duplicates from invalid transitions. Run with Python 3; no dependencies.
def advance(state, event): # The caller supplies verified synthetic outcomes, not real API calls. transitions = { ("new", "reserved"): "reserved", ("new", "unavailable"): "rejected", ("reserved", "approved"): "payment-pending", ("reserved", "denied"): "release-pending", ("reserved", "approval-expired"): "release-pending", ("payment-pending", "paid"): "complete", ("payment-pending", "declined"): "release-pending", ("payment-pending", "unknown"): "reconcile", ("reconcile", "confirmed-paid"): "complete", ("reconcile", "confirmed-unpaid"): "release-pending", ("release-pending", "released"): "compensated", ("release-pending", "retry-exhausted"): "manual-review", } return transitions.get((state, event), state)
state = "new"for event in ("reserved", "approved", "unknown", "confirmed-unpaid", "released"): state = advance(state, event) print(state)Expected output:
reservedpayment-pendingreconcilerelease-pendingcompensatedThe payment result is unknown, so the model waits for reconciliation. Only after confirmed nonpayment does it release stock. The released event represents a successful mock compensation, not a real action. Try replacing unknown with paid and omitting the remaining recovery events: the result is complete. This model neither invokes nor implements actual payment or inventory operations.
Make forward and compensating actions repeatable
Use stable operation IDs, for example O17:reserve and O17:release, and store the result durably. A reservation service can enforce uniqueness of its operation ID and atomically update inventory and its own operation record. When a retry reuses that ID, return the recorded result; reject the same ID with conflicting input. When an external system owns the side effect, use its documented idempotency and reconciliation facilities; a local database transaction alone cannot guarantee atomicity with a remote service.
If a release times out, check the reservation status, then retry with the same operation ID when safe. Never add stock twice for one release. Preserve completed operations, failure details and the required compensations. If retry bounds are exhausted, move to manual review; an operator verifies actual inventory and payment records before choosing a supported recovery action. Do not label compensation successful merely because it was requested.
A transactional outbox can record a local state update and an event-to-publish in the same local transaction. A separate publisher may resend after a crash, so receivers still need deduplication. Use a unique execution key and versioned state updates to prevent two concurrent callbacks advancing the same order incorrectly.
Review failure scenarios
Example A: reservation fails before any stock change. Reject the order; there is no reservation to release. Example B: reservation succeeds, approval expires. Release the recorded reservation once and mark compensated only after confirmation. Example C: payment status is unknown. Reconcile; a confirmed payment leads to completion in this simplified order flow, while confirmed nonpayment leads to release. Example D: release repeatedly fails. Stop automated attempts, retain evidence and require manual recovery.
For 200 accepted orders, suppose 15 are declined after reservation, 5 approvals expire and 2 unknown payments are confirmed unpaid. Under disjoint groups, 22 releases are required. If 3 releases need one extra attempt, there are 25 release attempts, not 25 logical releases. Two unresolved releases mean only 20 of the 22 releases are confirmed; completion dashboards must distinguish them. Never treat retry count as the number of unique business operations.
Recovery and operational evidence
Use least-privilege workload identities for each task, limit callback lifetime and protect workflow histories from unauthorized access. Define a manual review queue with order and operation IDs, last verified state, retry budget, escalation owner and audit trail. Version workflow definitions and event schemas; a change must account for already-running executions. Rehearse recovery with mock data before any live integration.
Sources: Compensating transaction pattern, Saga pattern, AWS error handling, Google callback waits. Official excerpts reviewed 2026-11-28. Practice: specify the transition and safe recovery for each failure case, including a duplicate release result and an exhausted retry budget.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Compensation and recovery — knowledge check
Choose the best answer for each offline scenario.
A payment request times out after stock is reserved. What next?
Which is a compensation for a confirmed stock reservation?
22 releases are required; three each retry once. How many attempts?
A release fails after the retry budget expires. What state is appropriate?
How can a local service safely handle duplicate release commands?