Course contentsShow
← Software Engineering
Lesson 1367 of 1,93340. Event-Driven ArchitectureFree lesson

Compensating Transactions

Designing compensating actions that undo or mitigate the effects of completed steps when a saga fails.

Compensating Transactions

What You'll Learn

You'll learn how to design compensating actions that undo or reverse the effects of completed steps when a saga fails partway through.

The Core Idea

In a distributed saga (lesson 1366), multiple services execute a series of local transactions. But what happens when step 5 succeeds, step 6 fails, and you can't roll back like in a traditional database transaction?

Enter compensating transactions: explicit actions that semantically undo what a previous step did.

Think of it like booking a vacation. You reserve a flight (step 1), then a hotel (step 2), then a rental car (step 3). If the car rental fails, you can't magically "undo" the database writes at the airline and hotel—they're separate systems. Instead, you must explicitly cancel the hotel reservation and cancel the flight reservation. Those cancellations are your compensating transactions.

Key Characteristics

Not true rollbacks: Compensating transactions don't rewind state; they create new, offsetting actions. Your order might go from "Reserved" → "Canceled" rather than never existing.

Business logic-driven: You design what "undo" means. Canceling a payment might trigger a refund event. Releasing inventory might increment stock counts.

Order matters: Compensations typically run in reverse order of the original steps. If you did A → B → C and C fails, you compensate B, then A.

Idempotency required: Since messages might be retried, compensating actions should be safe to execute multiple times.

Example Flow

  1. Reserve inventory → succeeds
  2. Charge payment → succeeds
  3. Send shipment → fails

Compensation sequence:

  • Refund payment (compensate step 2)
  • Release inventory (compensate step 1)

Key Takeaway: Compensating transactions provide semantic rollback in distributed sagas by explicitly reversing business effects through new actions, typically executed in reverse order when failures occur.