Volume 4 · Chapter 8 — .NET Distributed Systems and Microservices Architecture

Saga Pattern

Goutham Mayaluri 8 min read .NETC#MicroservicesSaga

8.1 Introduction

A traditional ACID transaction works within one database, but a business operation in microservices often spans several services with their own data - and you cannot hold a transaction across them. The Saga pattern manages such distributed transactions by breaking them into a sequence of local transactions, each publishing an event that triggers the next, with compensating actions that undo prior steps if a later one fails. It trades immediate global consistency for availability and loose coupling - the standard approach for cross-service workflows.

8.2 Local Transactions Plus Compensation

Each saga step commits a local transaction in its own service. If a later step fails, the saga runs compensating transactions thatsemanticallyundo prior steps - not by rolling back committed history (you can’t), but by performing a new business action that restores a valid state (a refund undoes a charge, a release undoes a reservation).

sequenceDiagram
  autonumber
  participant O as Orchestrator
  participant Acct as Account (debit)
  participant Credit as Account (credit)
  participant Notif as Notification
  O->>Acct: debit source
  Acct-->>O: debited
  O->>Credit: credit destination
  Credit--xO: FAILED (account closed)
  Note over O,Credit: Compensate
  O->>Acct: refund source (compensating transaction)
  O->>Notif: notify transfer failed

8.3 Choreography vs Orchestration Sagas

A choreography saga has no central coordinator - each service reacts to the previous step’s events. Simple and decentralized for short flows, but the overall process becomes implicit and hard to follow, debug, and change as it grows. An orchestration saga uses a central coordinator (a state machine) that drives the steps and compensations explicitly - more visible and manageable for complex, long-running flows, at the cost of a coordinator that must be resilient.

8.4 State, Correlation, and Idempotency

Long-running sagas must track state (current step, completed actions, pending compensations), correlated by an id that links all the messages of one saga instance. In .NET, MassTransit’s saga state machine implements this. And because messages are delivered at-least-once, every saga participant must be idempotent, keyed by the correlation/operation id, so retries and redeliveries don’t double-apply.


// MassTransit saga state machine (sketch): explicit orchestration with compensation.
public sealed class TransferSaga : MassTransitStateMachine<TransferState>
{
    public State Debiting { get; private set; } = null!;
    public State Crediting { get; private set; } = null!;
    // On TransferRequested -> send Debit; on Debited -> send Credit;
    // on CreditFailed -> send RefundDebit (compensation) then mark Failed.
    // All correlated by TransferId; each handler idempotent.
}
Senior Interview Question

Why not use distributed database transactions across microservices, and what do you use instead?

I avoid distributed database transactions (two-phase commit across services) because they don’t fit the scalability and independence goals of microservices, and instead use the saga pattern with eventual consistency. The problems with distributed transactions: they’re synchronous and blocking - a coordinator asks all participants to prepare and hold locks, then commit only if all agree, which requires multiple round trips (slow), and, most dangerously, blocks: if the coordinator fails after participants prepare, those participants hold locks indefinitely, unable to safely proceed, which can cascade into wider unavailability. They tightly couple the participating services and the coordinator, undermining the independence that’s the whole point of microservices, and they scale poorly as the number of participants grows and don’t work well across heterogeneous data stores or over unreliable networks. In a distributed, independently-deployed, resilience-focused architecture, that blocking, coupling, and poor scalability is unacceptable. So instead I use sagas: a business operation spanning services becomes a sequence of local transactions, each committing in its own service and publishing an event (or being driven by an orchestrator) that triggers the next step, with compensating transactions that semantically undo prior steps if a later one fails - a refund undoes a charge, a release undoes a reservation. This gives up immediate global consistency in exchange for availability, loose coupling, and scalability: each service commits independently without holding locks across the whole operation, no service blocks on a distributed coordinator, and the system stays available even if a participant is temporarily down. To make sagas reliable I combine them with the transactional outbox (so each local state change and its event commit atomically) and idempotent handlers (since messages are delivered at-least-once), and I design the user experience around the resulting eventual consistency (showing “processing” until the saga completes). For flows that truly need atomic consistency, I keep that within a single service/aggregate where a normal local transaction suffices, rather than spanning services. So the answer is: distributed transactions are blocking, coupling, and unscalable, so across services I use sagas - local transactions plus compensation, backed by outbox and idempotency - accepting eventual consistency as the right trade for the availability and independence microservices require, which is exactly why the industry moved away from 2PC toward sagas for cross-service business transactions.

Principal Engineer Question

How do you design a reliable long-running workflow (e.g. a money transfer) across services?

A money transfer that spans account, payment, notification, and audit services can’t be one ACID transaction, so I model it as a saga and engineer it for reliability at every point. First, structure: I use an orchestration saga for a business-critical, multi-step flow like this, because an explicit orchestrator (a state machine) makes the workflow visible, easy to monitor, and easy to reason about, and it centralizes the compensation and timeout logic - which matters more than choreography’s decentralization when the process is complex and money is involved. The saga proceeds as local transactions: debit the source account (local transaction), then credit the destination (local transaction), then notify and record audit; each step commits in its own service. Compensation: if a later step fails - say the credit fails because the destination is closed after the debit succeeded - the saga runs a compensating transaction to semantically undo the prior step (refund the source), restoring a valid state, since I can’t roll back the committed debit. I define a compensating action for every step that has a side effect. State and correlation: the saga tracks its state (current step, what’s completed, what needs compensating) persisted durably, and every message is correlated by a transfer id so all the events/commands of one saga instance are tied together and the saga can resume after a crash. Idempotency: because messages are delivered at-least-once and steps may be retried, every participant is idempotent - keyed by the transfer id and step - so a redelivered debit or credit or compensation is applied at most once, which is essential to avoid double debits or double refunds. Reliable messaging: each service publishes its step’s events via the transactional outbox so state and event commit atomically (no lost or phantom events), and durable messaging ensures nothing is dropped. Failure handling: transient failures are retried with backoff; steps that can’t proceed trigger compensation; and I handle timeouts (a step that never responds) explicitly in the state machine, and route unprocessable messages to dead-letter queues. Concurrency/correctness on the money itself: the debit and credit use the account service’s own concurrency control (optimistic concurrency/atomic balance updates) so concurrent operations don’t corrupt balances. User experience and observability: I design the UX around eventual consistency - showing the transfer as “processing” until the saga completes rather than pretending it’s instant - and I make the whole saga observable with correlation ids, tracing, and monitoring of saga state so operators can see stuck or compensating sagas and intervene. In .NET I’d implement this with a framework like MassTransit’s saga state machine over a durable broker, which provides the state persistence, correlation, and messaging plumbing. So a reliable long-running workflow = an orchestration saga of local transactions with a defined compensation for every step, durable correlated state that survives crashes, idempotent participants (for at-least-once delivery), reliable publishing via the outbox, explicit retry/timeout/compensation and dead-letter handling, proper concurrency control on the underlying data, a UX designed for eventual consistency, and full observability - which lets a multi-service business transaction complete correctly, or be cleanly compensated, despite the failures and duplicates inherent in distributed systems, without ever resorting to a distributed database transaction.

8.5 Banking Enterprise Scenario

A money transfer spans account validation, debit, credit, notification, and audit. An orchestration saga coordinates it: it debits the source, then credits the destination; if the credit fails after the debit succeeded, a compensating transaction refunds the source and the transfer is marked failed. State is tracked and correlated by transfer id, every step is idempotent (at-least-once delivery), events publish via the outbox, and the UI shows “processing” until the saga completes - correct, compensatable, observable money movement without a distributed transaction.

Chapter Revision Notes

  • Sagas replace cross-service ACID transactions with local transactions plus compensation.
  • Compensation semantically undoes prior steps (a refund undoes a charge) - it can’t roll back history.
  • Choreography for simple flows; orchestration (a state machine) for complex, long-running ones.
  • Track saga state, correlate by id, and make every participant idempotent (at-least-once).
  • Combine with the outbox for reliable publishing; MassTransit implements sagas in .NET.