Course contentsShow
← System Design
Lesson 589 of 1,91916. Distributed TransactionsFree lesson

Saga Fundamentals: Local Transactions and Compensations

How sagas decompose a distributed transaction into a sequence of local transactions with compensating actions.

Saga Fundamentals: Local Transactions and Compensations

What You'll Learn

You'll understand how sagas break down complex distributed transactions into manageable local transactions, each paired with a compensating action to undo work if needed.

The Core Idea

A saga decomposes one big distributed transaction into a sequence of local transactions, where each local transaction commits immediately to its own database. Instead of locking resources across systems (like Two-Phase Commit does), each step completes independently.

The clever part: every local transaction has a compensating transaction—essentially an "undo" operation—that reverses its effects if something goes wrong later in the sequence.

How It Works

Think of booking a vacation:

  1. Local Transaction 1: Reserve hotel room → Compensation: Cancel hotel
  2. Local Transaction 2: Book flight → Compensation: Cancel flight
  3. Local Transaction 3: Charge credit card → Compensation: Refund card

If step 3 fails (card declined), you don't have a global lock on the hotel and airline systems. Instead, you execute the compensations in reverse order: refund attempt, cancel flight, cancel hotel. Each system handles its own rollback locally.

Why This Matters

Unlike 2PC where all participants must wait and agree before committing, sagas let each service commit immediately and move forward. If failure happens, you explicitly undo through compensations rather than preventing all commits upfront.

Trade-off: There's a window where some steps are committed but others aren't yet—temporary inconsistency exists. This fits naturally with eventual consistency patterns you've learned.

Key Takeaway: Sagas replace distributed locking with local commits plus compensating actions, trading immediate consistency for better availability and avoiding the blocking problems of Two-Phase Commit.