Architecture PracticeComplete guide

Saga Pattern

The Saga pattern maintains business consistency across independently owned services by coordinating local transactions and compensating completed work when later steps fail.

Overview

A saga decomposes a distributed workflow into local transactions. Each successful step durably records its state and triggers the next action through a command or event. Failures invoke business-specific compensating actions where reversal is possible. Choreography distributes coordination across event handlers; orchestration gives one durable coordinator an explicit state machine. Both require idempotency, duplicate handling, correlation, timeouts, retries, observability, and reconciliation because messages and failures can occur at any boundary.

Official resources

What you will learn

  • Model local transactions, compensation, pivot, and terminal states.
  • Choose orchestration or choreography.
  • Persist workflow state and message deduplication.
  • Handle retries, timeouts, duplicates, and reordering.
  • Use outbox and inbox patterns.
  • Operate reconciliation and manual intervention.

Prerequisites

  • Distributed transactions, messaging, idempotency, and eventual consistency.
  • State machines, retries, timeouts, and observability.
  • Domain owners who can define compensation.

When to use Saga Pattern

Good fit

  • A workflow crosses independently owned transactional boundaries.
  • Business compensation exists.
  • Durable progress and recovery are required.

Choose another approach when

  • One local transaction suffices.
  • The steps are only best-effort calls without recovery.
  • Compensation and intermediate-state semantics are undefined.

Key concepts

Local transactions

Each participant commits owned state.

Compensation

Semantic undo is a new business action.

Orchestration

A coordinator owns explicit workflow state.

Choreography

Participants react to events without one coordinator.

Pivot and retryable steps

The pivot separates reversible work from must-complete work.

Correlation and idempotency

Stable IDs make at-least-once delivery safe.

Timeouts and deadlines

Durable timers detect missing replies.

Reconciliation

Operators inspect and repair stuck workflows.

Architecture

A durable saga state coordinates commands to service-owned local transactions; replies advance the workflow, while failures trigger compensation and telemetry supports reconciliation.

Saga state
Commands + events
Local transactions
Compensation + reconcile

Conceptual architecture · Adapt to your system context

Implementation walkthrough

The sample is an explicit order state machine with deduplication, emitted commands, invalid-transition rejection, and refund compensation.

  1. 01
    Map workflow

    List states, commands, replies, failures, and owners.

  2. 02
    Define compensation

    Specify semantic undo and pivot.

  3. 03
    Persist state

    Store status, version, processed IDs, and deadlines.

  4. 04
    Send reliably

    Persist outgoing messages atomically.

  5. 05
    Handle idempotently

    Deduplicate every reply and command.

  6. 06
    Recover timeouts

    Retry, compensate, or escalate.

  7. 07
    Operate

    Expose timelines, stuck states, and reconciliation.

Code example

An explicit state record makes successful steps and compensation progress durable and safe to retry.

PlaceOrderSaga.cs
public sealed record PlaceOrderSaga(
    Guid SagaId,
    Guid OrderId,
    bool InventoryReserved,
    bool PaymentCaptured,
    string Status);

public static IEnumerable<object> Decide(
    PlaceOrderSaga state, object message) => message switch
{
    InventoryReserved when !state.PaymentCaptured =>
        [new CapturePayment(state.SagaId, state.OrderId)],

    PaymentFailed when state.InventoryReserved =>
        [new ReleaseInventory(state.SagaId, state.OrderId)],

    PaymentCaptured =>
        [new ConfirmOrder(state.SagaId, state.OrderId)],

    _ => [] // Duplicate or already handled message
};

Testing strategy

Test state-machine failure space.

  • Test happy and compensation paths.
  • Duplicate every message.
  • Reorder replies.
  • Restart after each transition.
  • Fail compensation.
  • Trigger timeouts and manual repair.

Security considerations

Saga messages authorize consequential business actions.

  • Authenticate participants.
  • Authorize commands at owners.
  • Validate correlation and tenant.
  • Protect payment and personal data.
  • Audit manual intervention.

Performance and scalability

Workflow throughput depends on message and participant latency.

  • Keep state compact.
  • Index correlation and status.
  • Bound concurrent steps.
  • Avoid polling timers.
  • Measure oldest saga age.

Deployment and operations

State and contracts span rolling versions.

  • Evolve messages additively.
  • Migrate saga state compatibly.
  • Deploy tolerant handlers first.
  • Preserve timers and outboxes.
  • Rehearse rollback with active sagas.

Common problems and fixes

Saga is stuck.

Likely cause: Reply or timeout is missing.

Fix: Inspect timeline and reconcile.

Charge repeats.

Likely cause: Deduplication is absent.

Fix: Persist processed IDs.

Compensation loops.

Likely cause: Retry is unbounded.

Fix: Cap retries and escalate.

Invalid state transition.

Likely cause: Messages are reordered or code versions differ.

Fix: Make transitions tolerant or quarantine.

State and command diverge.

Likely cause: Dual write exists.

Fix: Use an outbox.

Users see ambiguity.

Likely cause: Intermediate states are hidden.

Fix: Expose meaningful pending status.

Best practices

  • Model state explicitly.
  • Persist progress durably.
  • Use outbox and inbox.
  • Make every action idempotent.
  • Define deadlines and compensation.
  • Carry correlation and causation.
  • Expose intermediate status.
  • Test restart and repair.

Production checklist

  • States and terminal outcomes are explicit.
  • Compensation and pivot are domain-approved.
  • State, inbox, and outbox are durable.
  • Handlers are idempotent.
  • Timeouts and retries are bounded.
  • Contracts evolve compatibly.
  • Timelines and stuck-state alerts exist.
  • Repair and rollback are rehearsed.

Common interview questions

Orchestration versus choreography?

Central state machine versus distributed event reactions.

Is compensation rollback?

No, it is a new semantic business action.

Why idempotency?

Messages can be delivered more than once.

What is the pivot?

The point after which remaining steps must complete.

How are timeouts implemented?

As durable scheduled messages or deadlines.

Why outbox and inbox?

To coordinate state, sends, and deduplication atomically.

How repair a stuck saga?

Use its timeline and controlled reconciliation commands.

Dedicated GitHub sample

Clone, run, test, and modify the focused implementation created for this guide.

Verified sample

Saga Order Workflow

A .NET 10 orchestrated order saga demonstrating explicit state transitions, idempotent message handling, emitted commands, invalid transitions, and payment compensation.

.NET 10Saga PatternState MachinexUnit
dedicated-sampleorchestrationcompensationidempotency
Run
dotnet run --project src/SagaOrderWorkflow
Test
dotnet test SagaOrderWorkflow.slnx