Course contentsShow
← Cloud and Infrastructure
Lesson 2735 of 2,98959. Queueing and Async PatternsFree lesson

Compensating Transactions

Design compensating transactions to undo or mitigate effects when saga steps fail in distributed workflows.

Compensating Transactions

What you'll learn: How to design compensating transactions that safely undo or mitigate the effects of failed steps in distributed saga workflows.

The Need for Compensation

In distributed sagas, you can't rely on ACID transactions to automatically roll back when something goes wrong. When a saga step succeeds but a later step fails, you need a way to undo the effects of earlier operations. This is where compensating transactions come in—they're essentially "reverse operations" that restore system state after partial failures.

Core Idea

A compensating transaction is a pre-defined operation that reverses or mitigates the business impact of a previously completed action. Think of it like a banking system: if you successfully withdraw money from Account A, but the transfer to Account B fails, your compensating transaction deposits the money back into Account A.

Key characteristics:

  • Idempotent: Safe to execute multiple times
  • Semantic undo: May not restore identical state, but achieves equivalent business outcome
  • Order-dependent: Execute in reverse order of original saga steps

Design Patterns

When you implement the Saga Pattern (from your earlier lesson), each forward action should have a matching compensating action:

Step 1: Reserve inventory → Compensate: Release inventory reservation
Step 2: Charge payment → Compensate: Refund payment
Step 3: Ship order → Compensate: Initiate return process

If Step 3 fails, execute compensations 2, then 1. Event Deduplication Strategies ensure compensations aren't applied twice if messages are replayed.

Compensation Types

  • Full rollback: Restore exact previous state (release inventory)
  • Partial mitigation: Issue credit instead of refund
  • Manual intervention: Flag for human review when automatic compensation isn't possible

Key Takeaway: Compensating transactions are the "undo" mechanism in distributed sagas, designed in reverse order to safely mitigate failures without traditional database rollbacks.