Database.Advanced.What is Saga pattern ?

The Saga pattern is a design pattern used to manage distributed transactions in microservices or distributed systems, where traditional ACID transactions are not feasible across services or databases.

🧠 What Problem Does It Solve?

In distributed systems:

  • A single business process often spans multiple services.
  • You can’t use a traditional database transaction across them (too slow or impossible).
  • You need a way to ensure consistency, even if one service fails.

✅ Saga pattern breaks the big transaction into a sequence of smaller, local transactions, and manages rollback through compensating actions if something fails.


🧩 Example: Flight Booking System

Business Process:

  1. Book a flight
  2. Reserve a hotel
  3. Rent a car

If car rental fails:

  • Cancel the hotel
  • Cancel the flight
    🔁 That’s the Saga — a set of forward actions + their corresponding rollbacks.

🔄 Two Types of Sagas

1. Choreography (Decentralized)

  • Each service listens for events and triggers the next step.
  • No central coordinator.
[Flight Service] → emits "FlightBooked"
↓
[Hotel Service] → emits "HotelReserved"
↓
[Car Service] → fails → emits "CarBookingFailed"
↓
[Hotel Service] → compensates → "CancelHotel"
↓
[Flight Service] → compensates → "CancelFlight"

✅ Simple
❌ Hard to track/debug

2. Orchestration (Centralized)

  • A central controller (orchestrator) coordinates the entire saga.
[Saga Orchestrator]
→ call FlightService.book()
→ call HotelService.reserve()
→ call CarService.rent()
← if failure, call compensating methods in reverse

✅ Easier to control and debug
❌ More tightly coupled

🔐 Compensating Transactions

Each forward step needs a compensating (undo) transaction:

  • chargeCustomer()refundCustomer()
  • reserveInventory()releaseInventory()

🔧 Common Use Cases

DomainExample
E-commerceOrder creation, payment, stock
Travel bookingFlight, hotel, rental car
BankingMoney transfer across institutions

✅ Summary

The Saga pattern is how you build reliable, eventually consistent workflows across multiple services when traditional distributed transactions aren’t an option.

It trades strong consistency for availability and resilience through compensating actions.

This entry was posted in Без рубрики. Bookmark the permalink.