Course contentsShow
← Software Engineering
Lesson 1420 of 1,93341. Scalability and Distributed SystemsFree lesson

Distributed Transactions with Saga Pattern

Implementing long-running distributed transactions as a sequence of local transactions with compensating actions.

Distributed Transactions with Saga Pattern

What you'll learn: How to implement long-running distributed transactions as a series of local transactions with compensating actions to undo work when failures occur.

The Core Problem

Traditional distributed transactions (like 2PC) lock resources across multiple services, creating tight coupling and reducing availability. The Saga pattern offers an alternative: break a large distributed transaction into a sequence of local transactions, where each service commits immediately and publishes an event to trigger the next step.

How Sagas Work

Instead of one atomic transaction spanning multiple services, a Saga is a chain of independent steps. Each step:

  1. Performs its local transaction and commits
  2. Publishes an event or triggers the next step
  3. Defines a compensating transaction to undo its work if a later step fails

The Rollback Mechanism

When a step fails midway through a Saga, you can't simply abort and rollback like a database transaction. Instead, you execute compensating actions in reverse order—think of them as "semantic rollbacks" that restore business consistency.

Analogy: Booking a vacation requires reserving a flight, hotel, and car. If the car rental fails, you don't have a global lock—instead, you explicitly cancel the hotel booking, then cancel the flight booking. Each cancellation is a compensating action.

Example Flow

  1. Order service: Create order → committed
  2. Payment service: Reserve funds → committed
  3. Inventory service: Reserve items → fails
  4. Compensating: Payment service releases funds
  5. Compensating: Order service marks order as failed

Each service maintains its own consistency, while the Saga ensures overall business consistency through forward progress or backward compensation.

Key Takeaway: The Saga pattern trades immediate consistency for availability by implementing distributed transactions as sequences of local transactions with explicit compensating actions, allowing services to remain loosely coupled and highly available.