Course contentsShow
← Cloud and Infrastructure
Lesson 580 of 2,98910. API Gateway and Event-Driven PatternsFree lesson

Saga Pattern for Distributed Transactions

Coordinating long-running transactions across services using compensating events for rollback.

Saga Pattern for Distributed Transactions

What you'll learn: How to coordinate multi-step transactions across distributed services without traditional database locks, using compensating events to roll back when things go wrong.

The Challenge of Distributed Transactions

In microservices, a single business operation might span multiple services—each with its own database. Traditional ACID transactions don't work across service boundaries. If step 3 of a 5-step process fails, how do you undo steps 1 and 2?

What is the Saga Pattern?

A saga breaks a distributed transaction into a sequence of local transactions, each updating one service. If any step fails, the saga executes compensating transactions that undo the completed steps in reverse order.

Think of it like booking a vacation: reserve flight → book hotel → rent car. If the car rental fails, you must cancel the hotel, then cancel the flight. Each service knows how to "undo" its own work.

Two Orchestration Approaches

Choreography: Services publish events after completing their local transaction. Other services listen and react. Failure events trigger compensating actions automatically.

Orchestration: A central saga coordinator explicitly tells each service what to do next and handles failures. This uses the orchestration pattern you learned earlier (Event Choreography vs Orchestration).

Compensating Transactions

Unlike traditional rollbacks, compensating transactions are semantic rollbacks—they issue offsetting business operations (refunds, cancellations, reversals) rather than database-level undos. They must be carefully designed since the original data may already be visible to users.

The saga relies on eventual consistency and idempotency (concepts you've already covered) to handle retries and ensure reliability.

Key Takeaway: The Saga Pattern coordinates long-running distributed transactions by chaining local transactions and using compensating events to roll back completed steps when failures occur, enabling consistency without distributed locks.