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

What is the Saga Pattern

Understanding sagas as a pattern for managing distributed transactions across multiple services without 2PC.

What is the Saga Pattern

You'll learn: How sagas provide a pattern for managing long-running transactions across multiple microservices without locking resources.

The Problem with Distributed Transactions

When you have a single database, transactions are straightforward—either everything commits or everything rolls back. But in microservices with separate databases per service, traditional two-phase commit (2PC) locks become impractical. They create tight coupling, hurt availability, and contradict the independence microservices aim for.

The Saga Solution

A saga is a sequence of local transactions where each service performs its own database transaction and publishes an event or message to trigger the next step. If any step fails, the saga executes compensating transactions to undo the changes made by previous steps.

Think of it like booking a vacation: you reserve a flight, then a hotel, then a rental car. If the car rental fails, you need to cancel the hotel and flight. Each booking is independent, but together they form a coordinated workflow with explicit rollback steps.

Two Coordination Styles

Choreography: Each service listens for events and knows what to do next. No central controller—services dance together based on events.

Orchestration: A saga coordinator explicitly tells each service what to do, tracking the overall state and invoking compensating actions if needed.

Trade-offs

Sagas sacrifice immediate consistency for eventual consistency. During execution, the system may be temporarily inconsistent. You also need to design compensating transactions carefully—some actions (like sending an email) can't truly be undone, only mitigated.

Key Takeaway: The saga pattern manages distributed transactions through a sequence of local transactions coordinated by events or orchestration, using compensating transactions to handle failures instead of traditional rollbacks.