Compensating Transactions: Design Principles
What you'll learn: How to design compensating actions that semantically undo completed transactions without requiring rollback support.
The Core Challenge
In the Saga pattern, when a later step fails, you can't simply "rollback" like in a traditional database transaction. Each local transaction already committed permanently. Instead, you must design compensating transactions — explicit operations that reverse the business effect of what you did earlier.
Key Design Principles
1. Semantic Reversal, Not Technical Rollback
A compensating transaction doesn't delete the original record. Instead, it creates a new operation that logically undoes the effect.
Example: If you reserved inventory by setting quantity_available = quantity_available - 5, the compensating transaction doesn't restore the old row. Instead, it executes quantity_available = quantity_available + 5 as a new operation.
2. Idempotency
Compensations might execute multiple times due to retries. Design them to be safe when repeated.
Example: "Cancel order #123" should check if already cancelled before decrementing counters again.
3. Business Context Matters
Some actions are naturally compensatable (reserving inventory), while others aren't (sending an email). For irreversible actions, you may need "apology" compensations (refund, notification) rather than perfect reversal.
4. Record Everything
Log both the original action and compensation. This creates an audit trail showing what happened and why.
5. Consider Timing Windows
The longer the saga runs, the harder compensation becomes. A reservation held for 5 seconds is easier to cancel than one held for 5 hours after other business logic acted on it.
Key Takeaway: Compensating transactions reverse business effects through new operations, not rollbacks. Design them to be idempotent, semantically meaningful, and audit-friendly, while accepting that some real-world actions cannot be perfectly undone.