The Problem: Distributed Transactions

Imagine a travel booking application. When a user books a trip, three distinct services might need to be invoked:

  1. Flight Service: Reserve a seat.
  2. Hotel Service: Book a room.
  3. Payment Service: Charge the customer's credit card.

If the Flight and Hotel bookings succeed but the Payment fails, we can't simply "rollback" the database transaction because the flight and hotel reservations are in different databases. We need a mechanism to undo the changes made by the previous steps. This is where Sagas come in.

Advertisement

What is a Saga?

A Saga is a sequence of local transactions. Each local transaction updates the database and publishes a message or event to trigger the next local transaction in the saga. If a local transaction fails because it violates a business rule, the saga executes a series of compensating transactions that undo the changes that were made by the preceding local transactions.

Key Concepts

  • Compensating Transaction: An operation that undoes the effect of a previous step. For example, "Cancel Flight" compensates for "Book Flight".
  • Pivot Transaction: The point of no return. If this transaction commits, the saga will run to completion. If it fails, the saga will unwind.
  • Retryable Transaction: Transactions that follow the pivot transaction and are guaranteed to succeed eventually.
Advertisement

Orchestration vs. Choreography

There are two main ways to coordinate sagas:

Feature Choreography Orchestration
Description Services exchange events without a centralized point of control. A centralized controller (Orchestrator) tells participants what local transactions to execute.
Pros Simple, loose coupling, no single point of failure. Centralized logic, easier to understand workflow, reduced cyclic dependencies.
Cons Hard to track status, potential for cyclic dependencies. Tighter coupling to orchestrator, orchestrator can become a bottleneck.

Interactive Visualization: Booking Saga

Explore the interactive visualization below to see how a booking saga handles both success and failure scenarios using an orchestration approach.

When to Use Sagas

Use the Saga pattern when:

  • You need to ensure data consistency across multiple microservices without tight coupling.
  • You require long-running transactions that shouldn't block resources.
  • You can accept eventual consistency rather than immediate consistency.