Course contentsShow
← Computer Science
Lesson 2722 of 2,87260. Distributed Data and CommunicationFree lesson

Compensating Transactions

Designing idempotent compensation logic to undo committed operations when a saga step fails in distributed workflows.

Compensating Transactions

What you'll learn: How to design idempotent undo logic that safely reverses committed operations when a saga step fails in distributed workflows.

The Challenge

When using the Saga Pattern (introduced in lesson 2721), each step commits its transaction immediately rather than waiting for a global coordinator. If a later step fails, you can't simply "rollback" — those earlier transactions are already committed! Instead, you must explicitly undo each completed step by running a compensating transaction.

Core Idea

A compensating transaction is a separate operation that semantically reverses the effect of a previously committed transaction. Think of it like a "ctrl+z" for distributed systems — but unlike a database rollback that prevents changes from becoming visible, a compensating transaction creates new changes that counteract the old ones.

Example

Imagine an e-commerce saga:

  1. Reserve inventory (commits)
  2. Charge credit card (commits)
  3. Ship order (fails)

To compensate, you execute:

  • Un-charge the credit card (issue refund)
  • Unreserve inventory (release stock)

Idempotency is Critical

Compensating transactions must be idempotent — running them multiple times produces the same result as running once. Why? Because network failures might cause retries. If "refund 50"runstwiceduetoaretry,you′drefund50" runs twice due to a retry, you'd refund 100!

Solution: Check state first. Example: "If payment X exists and isn't already refunded, then refund it."

Design Patterns

  • Semantic undo: Don't literally reverse bits; apply business logic (e.g., "cancel reservation" not "restore database row")
  • Store compensation data: Save enough context during the forward step to enable accurate compensation later

Key Takeaway: Compensating transactions provide eventual consistency in sagas by explicitly undoing committed work through idempotent reverse operations, trading immediate atomicity for forward progress in distributed systems.