The Saga Pattern - managing distributed transactions
The problem Saga solves - no ACID transactions between microservices
In a monolith, a transaction spanning several operations (e.g. creating an order + decrementing stock + charging a payment) is simple - one database transaction, BeginTransaction/Commit/Rollback, as we discussed with EF Core.
In a microservices architecture these operations live in different services, with different databases:
OrderService (its own database) → InventoryService (its own database) → PaymentService (its own database)
You can't simply wrap this in a single SQL transaction - there is no single database you could cover with a BeginTransactionAsync() transaction. The classic two-phase commit (2PC - Two-Phase Commit) at the distributed level is in practice rarely used in microservices - it is slow, blocking and scales poorly.
The Saga Pattern is the answer to this problem: it breaks a large business operation into a sequence of smaller, local transactions, each within a single service, with a mechanism of compensation (compensating actions) if one of the steps fails.
Where the name "Saga" comes from
The name comes from the original 1987 research paper (Hector Garcia-Molina, Kenneth Salem) describing long-lived transactions which - like an epic saga - consist of many successive "chapters" (steps), instead of one atomic event.
Two models of implementing a Saga
1. Choreography - no central coordinator
Each service listens for events and reacts by publishing its own events - nobody "conducts" the whole thing, it's a decentralised, event-driven flow.
// OrderService
public class OrderCreatedHandler
{
public async Task Handle(OrderCreatedEvent orderCreated)
{
// The order was created, publish an event
await _eventBus.PublishAsync(new OrderPlacedEvent(orderCreated.OrderId, orderCreated.Items));
}
}
// InventoryService - listens for OrderPlacedEvent
public class OrderPlacedHandler
{
public async Task Handle(OrderPlacedEvent orderPlaced)
{
var reserved = await _inventoryRepository.TryReserveStockAsync(orderPlaced.Items);
if (reserved)
await _eventBus.PublishAsync(new StockReservedEvent(orderPlaced.OrderId));
else
await _eventBus.PublishAsync(new StockReservationFailedEvent(orderPlaced.OrderId)); // KOMPENSACJA
}
}
// PaymentService - listens for StockReservedEvent
public class StockReservedHandler
{
public async Task Handle(StockReservedEvent stockReserved)
{
var charged = await _paymentGateway.ChargeAsync(stockReserved.OrderId);
if (charged)
await _eventBus.PublishAsync(new PaymentCompletedEvent(stockReserved.OrderId));
else
await _eventBus.PublishAsync(new PaymentFailedEvent(stockReserved.OrderId)); // KOMPENSACJA
}
}
// OrderService - listens for StockReservationFailedEvent / PaymentFailedEvent - COMPENSATION
public class SagaCompensationHandler
{
public async Task Handle(PaymentFailedEvent paymentFailed)
{
await _orderRepository.CancelOrderAsync(paymentFailed.OrderId);
await _eventBus.PublishAsync(new ReleaseStockEvent(paymentFailed.OrderId)); // tell InventoryService to release the reservation
}
}
The advantages of Choreography: - Simplicity for a small number of steps - no additional, centralised component to build - Naturally loose coupling - services don't know each other, only the events
The disadvantages: - Difficulty tracing the whole flow - to understand "what happens when an order is created", you have to go through the handlers in several different services, with no single, readable place describing the whole process - The risk of cyclic dependencies between events in complex sagas with many steps - Harder end-to-end testing of the whole flow
2. Orchestration - a central coordinator
A dedicated component (the Saga Orchestrator) explicitly coordinates all the steps, sending commands to individual services and deciding what to do in case of an error.
public class OrderSagaOrchestrator
{
private readonly IInventoryServiceClient _inventoryClient;
private readonly IPaymentServiceClient _paymentClient;
private readonly IOrderRepository _orderRepository;
public async Task ExecuteAsync(int orderId, List<OrderItemDto> items, decimal amount)
{
try
{
// Krok 1
await _inventoryClient.ReserveStockAsync(orderId, items);
try
{
// Krok 2
await _paymentClient.ChargeAsync(orderId, amount);
}
catch (PaymentFailedException)
{
// COMPENSATION for Step 1 - we have to roll back the stock reservation
await _inventoryClient.ReleaseStockAsync(orderId, items);
throw;
}
// Krok 3
await _orderRepository.MarkAsConfirmedAsync(orderId);
}
catch (Exception)
{
await _orderRepository.MarkAsFailedAsync(orderId);
throw;
}
}
}
A version with an explicit state machine (State Machine) - common in practice, e.g. with the MassTransit library (which supports Sagas natively):
public class OrderSaga : MassTransitStateMachine<OrderSagaState>
{
public State AwaitingStockReservation { get; private set; }
public State AwaitingPayment { get; private set; }
public State Completed { get; private set; }
public State Failed { get; private set; }
public Event<OrderPlacedEvent> OrderPlaced { get; private set; }
public Event<StockReservedEvent> StockReserved { get; private set; }
public Event<PaymentCompletedEvent> PaymentCompleted { get; private set; }
public Event<PaymentFailedEvent> PaymentFailed { get; private set; }
public OrderSaga()
{
InstanceState(x => x.CurrentState);
Initially(
When(OrderPlaced)
.Then(context => context.Saga.OrderId = context.Message.OrderId)
.TransitionTo(AwaitingStockReservation)
.Publish(context => new ReserveStockCommand(context.Message.OrderId)));
During(AwaitingStockReservation,
When(StockReserved)
.TransitionTo(AwaitingPayment)
.Publish(context => new ChargePaymentCommand(context.Saga.OrderId)));
During(AwaitingPayment,
When(PaymentCompleted)
.TransitionTo(Completed),
When(PaymentFailed)
.Publish(context => new ReleaseStockCommand(context.Saga.OrderId)) // KOMPENSACJA
.TransitionTo(Failed));
}
}
The advantages of Orchestration: - A clear, centralised flow - the whole business process visible in ONE place (the Orchestrator/State Machine class) - Easier testing and debugging of the whole sequence - Easier to add timeouts and more complex conditional logic
The disadvantages: - The orchestrator becomes a central point - more responsibility in one place (although it is not a "single point of failure" in the availability sense, if designed properly) - The participating services have to "know" the Orchestrator (at least the format of the commands they receive)
Compensation (Compensating Transactions) - the foundation of a Saga
This is the most important concept in the whole pattern - since there is no distributed rollback (as in a classic SQL transaction), every step of a Saga must have a defined compensating action that "reverses" its effect:
| Step | Action | Compensation |
|---|---|---|
| 1. Reserving stock | ReserveStock() |
ReleaseStock() |
| 2. Charging the payment | ChargePayment() |
RefundPayment() |
| 3. Confirming the order | ConfirmOrder() |
CancelOrder() |
An important property of compensation: it doesn't have to be a "literal undo" - it is a semantic reversal of the business effect. E.g. if the payment has already gone through and the goods have been shipped, "compensation" may mean a refund and a complaints process, not a magical "deletion" of the fact that the transaction happened.
Idempotency - a practical requirement for all the steps of a Saga
Since communication between services goes over the network (a message queue, HTTP), messages can be delivered multiple times (a retry after a timeout, a missing ACK) - every step of a Saga (and its compensation) must be idempotent, i.e. safe to execute multiple times with the same effect:
public async Task ReserveStockAsync(int orderId, List<OrderItemDto> items)
{
// ✅ Idempotent - checks whether a reservation ALREADY exists for this orderId before doing it again
var existingReservation = await _context.StockReservations
.FirstOrDefaultAsync(r => r.OrderId == orderId);
if (existingReservation != null) return; // already done, we do nothing
// faktyczna logika rezerwacji
}
When to use a Saga - a practical rule
A Saga makes sense when you have a business operation spanning multiple independent services/databases which has to be carried out in a coordinated way, without a classic distributed ACID transaction. For simple flows (2-3 steps, few error conditions) Choreography is quicker to implement. For complex flows (many steps, conditions, timeouts, a need to track state) Orchestration (especially with a ready-made library like MassTransit) gives much better readability and testability.
Summary
The Saga Pattern solves the problem of distributed transactions between microservices by breaking a large operation into a sequence of local transactions, each with a defined compensating action in case a later step fails. The two implementation models - Choreography (decentralised, through events, simpler for small sagas) and Orchestration (a centralised coordinator/state machine, better readability and testability for complex flows) - differ mainly in who decides on the next step: in Choreography each service reacts to events on its own, in Orchestration one component explicitly drives the whole process. The key practical requirements are compensation for every step and idempotency of all operations, because network communication doesn't guarantee "exactly once" delivery.