Skip to main content
← CONCEPTS / SOFTWARE DESIGN & ARCHITECTURE
An end-to-end domain learning journey

Saga &
Compensation Patterns.

A Saga coordinates a multi-service business transaction as a sequence of local ACID transactions paired with compensating actions that semantically undo prior steps on failure, avoiding distributed 2-Phase Commit locks at the cost of eventual consistency.
Start the journey7 sections· Last modified Oct 23, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When each microservice owns its own database, a checkout spanning Order, Inventory, and Payment cannot use a single, design every saga step before the pivot transaction to be idempotent and paired with a compensating action, and persist state transitions via a transactional outbox so crashes never leave workflows orphaned.

TL;DR30-second simplified summary
▾

Core Mechanics: When each microservice owns its own database, a checkout spanning Order, Inventory, and Payment cannot use a single local ACID transaction—and 2-Phase Commit (2PC) holds cross-network locks that stall throughput.

Visual & Structural Flow: Depicts Orchestrated Checkout Saga: Pivot Failure & Semantic Rollback (Temporal Orch -> Order DB -> Inventory DB -> Payment (Pivot)); Local ACID Commit + Transactional Outbox + Idempotent Inbox (Participant Service -> Domain Table -> Outbox / Inbox Table -> Debezium CDC -> Kafka).

Trade-Offs & Production: Choose the coordination style based on workflow length, service count, and observability needs. A Temporal workflow orchestrates Order (PENDING semantic lock + TTL sweeper), Inventory (commutative delta + inbox dedup), and Payment (Pivot).

Failure Modes & Application: Compare Sagas with 2PC, Transactional Outbox CDC, and idempotent APIs.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Transaction Isolation & Distributed ACID
Isolation levels control which concurrent read/write anomalies a database permits, trading throughput and lock/abort rates for correctness—while distributed ACID extends those guarantees across shards via 2PC, TrueTime, or HLCs.
Idempotency & Deduplication
Idempotency keys and deduplication logs ensure that network retries, at-least-once message deliveries, and double-clicks execute state mutations at most once while returning the original cached outcome.
Full walkthrough · 7 stages
01
STAGE 01 · WHAT IT ISL4 · FUNDAMENTALS

What is a Saga.

Why this matters: The mechanism: understand how a Saga works from first principles.

Think of What is a Saga as the intuition layer for Saga & Compensation Patterns: The mechanism: understand how a Saga works from first principles.

When each microservice owns its own database, a checkout spanning Order, Inventory, and Payment cannot use a single local ACID transaction—and 2-Phase Commit (2PC) holds cross-network locks that stall throughput. A Saga splits the workflow into local ACID transactions, classifying steps into: Compensable (ReserveInventory -> undoable via ReleaseInventory), Pivot (ChargeCard -> point of no return), and Retriable (ConfirmOrder, SendEmail -> guaranteed to succeed after Pivot).

Saga Compensation Flow

Orchestrated Checkout Saga: Pivot Failure & Semantic Rollback

Temporal OrchOrder DBInventory DBPayment (Pivot)1. T1: Create Order (PENDING)2. T2: Reserve Stock (semanticlock)3. T3: ChargeCard (declined!)4. C2: ReleaseStock (idempotent)5. C1: CancelOrder (CANCELLED)

No distributed DB locks are held; failed pivot steps trigger idempotent backward compensations.

02
STAGE 02 · WHY WE NEED ITL4 · FUNDAMENTALS

Why Sagas Lack Isolation (ACD vs. ACID Countermeasures).

Why this matters: The problem: see what breaks without Why Sagas Lack Isolation under real concurrency or scale.

Think of Why Sagas Lack Isolation (ACD vs. ACID Countermeasures) as the intuition layer for Saga & Compensation Patterns: The problem: see what breaks without Why Sagas Lack Isolation under real concurrency or scale.

Because each local transaction commits immediately, Sagas provide ACD (Atomicity, Consistency, Durability) without Isolation: concurrent sagas can observe intermediate PENDING states (dirty reads) or cause lost updates. To prevent anomalies without 2PC locks, use Semantic Locks (status = PENDING_RESERVATION with TTL sweepers), Commutative Updates (delta +/- instead of absolute SET), and Transactional Outboxes to eliminate dual-write split-brain.

Request & State Flow

Why Sagas Lack Isolation (ACD vs. ACID Countermeasures)

CallerService EntryCore ProcessorState Store1. Submit bounded request2. Apply domain invariant3. Persist or read state4. Return verified response
Engineering Decision Framework
Problem
How to implement Saga & Compensation Patterns without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
When each microservice owns its own database, a checkout spanning Order, Inventory, and Payment cannot use a single, design every saga step before the pivot transaction to be idempotent and paired with a compensating action, and persist state transitions via a transactional outbox so crashes never leave workflows orphaned.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Saga & Compensation Patterns experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

Compensations Must Also Be Idempotent & Retriable

If ReleaseStock times out and retries, duplicate execution must not inflate stock—attach saga_id + step_name idempotency keys.

Never Put Non-Undoable Side Effects Before Pivot

Sending confirmation emails or shipping webhooks before ChargeCard succeeds forces awkward apology emails on rollback.

03
STAGE 03 · WHERE IT IS USEDL5 · APPLIED DESIGN

Where Sagas excel (and where Local ACID or NewSQL wins).

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Think of Where Sagas excel (and where Local ACID or NewSQL wins) as the intuition layer for Saga & Compensation Patterns: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Use Sagas for multi-database or long-running workflows; stay with local ACID or NewSQL when strict serializability is required.

ChoiceWhat it buysWhat it costs
Good Candidate: Multi-Service Checkout, Travel & Loan WorkflowsKeeps local DB transactions fast and lock-free even across external APIs or multi-second workflows.Requires building compensating actions, idempotency keys, and semantic lock sweepers.
Avoid: Single-Database OperationsUse a standard local ACID transaction—zero compensation or outbox overhead.Building a saga inside one database adds needless complexity.
Avoid: Zero-Dirty-Read Financial LedgersUse a NewSQL database (Spanner / CockroachDB) if strict cross-partition serializability is mandatory.Sagas expose intermediate `PENDING` states until completion or compensation.
04
STAGE 04 · HOW IT IS MANAGEDL5 · APPLIED DESIGN

How Transactional Outbox & Idempotent Consumers are implemented.

Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.

Think of How Transactional Outbox & Idempotent Consumers are implemented as the intuition layer for Saga & Compensation Patterns: Operational control: configure bounds, failure handling, and safe production defaults.

Write domain mutations and outbox events in the same local ACID transaction (tailed by Debezium CDC or FOR UPDATE SKIP LOCKED relay), and enforce an inbox(event_id PRIMARY KEY) table on every participant.

Design Trade-Off

How Transactional Outbox & Idempotent Consumers are implemented

Before · Unbounded Coupling
  • No backpressure on spikes
  • Implicit shared state
  • Cascading tail latency
After · Bounded & Observable
  • Explicit capacity budgets
  • Isolated failure domains
  • Predictable p99 latency
# Idempotent Transactional Outbox relay loop (Python + Postgres)
def publish_pending_outbox_events(db_conn, kafka_producer, batch_size: int = 100) -> int:
    rows = db_conn.execute(
        "SELECT id, aggregate_id, payload FROM outbox WHERE published_at IS NULL "
        "ORDER BY id ASC LIMIT %s FOR UPDATE SKIP LOCKED",
        (batch_size,),
    ).fetchall()
    for event_id, agg_id, payload in rows:
        kafka_producer.send("saga.events", key=agg_id, value=payload)
        db_conn.execute("UPDATE outbox SET published_at = NOW() WHERE id = %s", (event_id,))
    db_conn.commit()
    return len(rows)

# Note: Wrap batch in try/except Exception: db_conn.rollback(); raise so failed Kafka sends do not leave partial DB state.
05
STAGE 05 · ALTERNATIVESL6 · SCALE & TRADE-OFFS

Alternatives: Orchestration vs. Choreography vs. 2-Phase Commit.

Why this matters: The trade-off: compare competing approaches across latency, consistency, and operational cost.

Think of Alternatives: Orchestration vs. Choreography vs. 2-Phase Commit as the intuition layer for Saga & Compensation Patterns: The trade-off: compare competing approaches across latency, consistency, and operational cost.

Choose the coordination style based on workflow length, service count, and observability needs.

Component Topology

Alternatives: Orchestration vs. Choreography vs. 2-Phase Commit

CalleringressRouter / APIcomputeProcessorstorageState Layercontrolrequestdispatchread/write
ChoiceWhat it buysWhat it costs
Orchestration (Temporal / AWS Step Functions)Centralizes control flow, timeouts, and compensation order in one debuggable workflow.Adds an orchestrator platform dependency to operate.
Choreography (Kafka Domain Events)Loose service coupling—no central coordinator.Global state is scattered across >4 services and hard to trace without strict `correlation_id`s.
Two-Phase Commit (2PC / XA)Full ACID isolation across participants.Cross-network locks destroy throughput and block if the coordinator crashes mid-commit.
06
STAGE 06 · PRODUCTION ARCHITECTUREL7 · STAFF / PRINCIPAL

Production example: Temporal Orchestrator + Outbox + Semantic Locks.

Why this matters: Production architecture: see how the components compose end to end under real load.

Think of Production example: Temporal Orchestrator + Outbox + Semantic Locks as the intuition layer for Saga & Compensation Patterns: Production architecture: see how the components compose end to end under real load.

A Temporal workflow orchestrates Order (PENDING semantic lock + TTL sweeper), Inventory (commutative delta + inbox dedup), and Payment (Pivot). Every service commits domain state + outbox rows atomically, eliminating dual-write split-brain.

Zero Dual-Write

Local ACID Commit + Transactional Outbox + Idempotent Inbox

Participant Service1 Local ACID TxDomain TablePENDING semantic lockOutbox / Inbox TablePK(event_id) dedupDebezium CDC -> KafkaAt-least-once relay

1.1. Atomic Outbox: Domain row and outbox event commit together—eliminating crash-induced split-brain.

2.2. Inbox Dedup: INSERT INTO inbox(event_id) ON CONFLICT DO NOTHING makes at-least-once retries safe.

3.3. TTL Sweeper: Stuck PENDING semantic locks expire cleanly if a saga hits workflow timeout.

Outbox + Inbox + Semantic Locks give Sagas reliable execution without distributed 2PC locks.

07
STAGE 07 · PROBLEMS SOLVED & FURTHER DEEP DIVEL7 · STAFF / PRINCIPAL

Problems solved by Sagas & Related Distributed Concepts.

Why this matters: Applied problems: connect these internals to concrete system design and debugging scenarios.

Think of Problems solved by Sagas & Related Distributed Concepts as the intuition layer for Saga & Compensation Patterns: Applied problems: connect these internals to concrete system design and debugging scenarios.

Compare Sagas with 2PC, Transactional Outbox CDC, and idempotent APIs.

Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

In a Saga, why is it unsafe to send a customer confirmation email or shipping webhook *before* the Pivot transaction (`ChargeCard`) succeeds?

Recommended Learning Flow