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.
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).
Orchestrated Checkout Saga: Pivot Failure & Semantic Rollback
No distributed DB locks are held; failed pivot steps trigger idempotent backward compensations.
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.
Why Sagas Lack Isolation (ACD vs. ACID Countermeasures)
- 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.
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.
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.
| Choice | What it buys | What it costs |
|---|---|---|
| Good Candidate: Multi-Service Checkout, Travel & Loan Workflows | Keeps 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 Operations | Use a standard local ACID transaction—zero compensation or outbox overhead. | Building a saga inside one database adds needless complexity. |
| Avoid: Zero-Dirty-Read Financial Ledgers | Use a NewSQL database (Spanner / CockroachDB) if strict cross-partition serializability is mandatory. | Sagas expose intermediate `PENDING` states until completion or compensation. |
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.
How Transactional Outbox & Idempotent Consumers are implemented
- No backpressure on spikes
- Implicit shared state
- Cascading tail latency
- 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.
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.
Alternatives: Orchestration vs. Choreography vs. 2-Phase Commit
| Choice | What it buys | What 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. |
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.
Local ACID Commit + Transactional Outbox + Idempotent Inbox
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.
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: Make the trade-off yourself.
In a Saga, why is it unsafe to send a customer confirmation email or shipping webhook *before* the Pivot transaction (`ChargeCard`) succeeds?