Skip to main content

Sagas

1. Executive Summary​

A saga is a long-lived business transaction decomposed into a sequence of local transactions, each committing independently within its own service boundary. If a later step fails, the saga executes compensating transactions to undo or logically reverse the effects of prior steps—because there is no distributed rollback across already-committed local transactions.

Sagas were introduced by Garcia-Molina and Salem (1987) as an alternative to distributed locking protocols like 2PC. Two coordination styles dominate modern architectures: choreography (each service reacts to events and knows what to do next) and orchestration (a central coordinator directs steps and compensations). Sagas trade strong atomicity for availability, loose coupling, and scalability across microservices.

This chapter covers saga semantics, compensating vs semantic undo, choreography vs orchestration tradeoffs, idempotency and ordering requirements, failure modes (poison messages, incomplete compensation, lost events), comparison with 2PC and outbox patterns, production implementations (Temporal, Camunda, custom event-driven), and principal-level interview framing.

Try it: §25 Hands-On — Lab 010 saga orchestrator on :8093; then engineer guide for runtime walkthrough. Pairs with Lab 009 outbox.

2. Why This Topic Matters​

Principal interviews frequently pose: "How do you maintain consistency across microservices without 2PC?" The saga pattern is the standard answer—but weak answers stop at "use events."

Strong candidates explain:

  • Compensating transactions are not always true rollbacks—they are semantic reversals (issue refund, not delete row).
  • Choreography scales teams but obscures global flow; orchestration centralizes visibility but risks a god-service.
  • Every step must be idempotent because messages are at-least-once.
  • Sagas are eventually consistent—intermediate states are visible.

Production failures include double refunds, orphaned orders, compensations that fail silently, and "saga stuck" states blocking customer support. Architects who design sagas without state machines, timeouts, and reconciliation build distributed workflows that are harder to debug than monolith transactions.

3. Problems Being Solved​

ProblemMonolith ACIDSaga
Cross-service atomic commitSingle transactionSequence of local commits
Service independenceCoupled schemaAutonomous bounded contexts
Availability during partial failureRollback allForward progress + compensate
Long-running workflowsLong DB locksAsync steps with durable state
Heterogeneous technologyOne databasePolyglot persistence

Sagas solve cross-service business process coordination without distributed locks. They do not provide instant global consistency, isolation of intermediate states from external readers, or automatic compensation if business rules forbid undo (e.g., shipped physical goods).

4. Assumptions and System Model​

Assume microservices with private databases and asynchronous messaging (or synchronous calls with durable saga log):

  • Each local transaction is ACID within one database.
  • Messages are delivered at-least-once unless using exactly-once infrastructure (rare end-to-end).
  • Compensations are application-defined and may be partial or delayed.
  • Failures: Process crash, network partition, duplicate messages, slow consumers.
  • Not Byzantine unless discussing fraud detection separately.

Not assumed: Compensations restore identical prior state—only business-equivalent state. Global serializability. Automatic saga completion without monitoring.

5. Essential Terminology​

TermDefinition
SagaSequence of local txs with compensating txs on failure.
Compensating transactionSemantic undo of a completed local step.
ChoreographyDecentralized: services react to events without central controller.
OrchestrationCentral saga manager issues commands and tracks state.
Forward recoveryRetry failed step (transient error).
Backward recoveryRun compensations for completed steps.
Semantic lockBusiness rule preventing conflicting actions during saga (e.g., no ship until paid).
Saga logDurable record of saga state and step outcomes.
Pivot transactionLast step after which compensation is impossible—switch to manual resolution.
Idempotency keyDedupes retried step execution.

Mnemonic: Saga = Steps forward, Compensate backward, Never global lock.

6. Core Mechanism​

Orchestrated saga (happy path)​

Figure 1: Orchestrator drives sequential local commits; each step durable before next.

Compensation path​

Figure 2: Backward recovery—compensations run in reverse order of successful forward steps.

Choreography vs orchestration​

Figure 3: Choreography flows through events; orchestration centralizes control and state.

7. Step-by-Step Walkthrough​

Scenario: Travel booking—flight, hotel, car. Orchestrated saga.

StepActionState if next fails
1Book flight (committed)Compensate: cancel flight
2Book hotel (committed)Compensate: cancel hotel, then flight
3Book car failsRun: cancel hotel, cancel flight
4Saga ends COMPENSATEDCustomer charged $0 net; may see brief flight hold

Choreography equivalent:

EventConsumer action
TripRequestedFlight svc books, emits FlightBooked
FlightBookedHotel svc books, emits HotelBooked
HotelBookedCar svc fails, emits CarBookingFailed
CarBookingFailedHotel listens, cancels; emits HotelCancelled
HotelCancelledFlight listens, cancels

Risk: Implicit distributed state machine—harder to visualize than orchestrator's single log.

Parallel saga steps (advanced): When flight and hotel are independent, orchestrator may fan out steps 1 and 2 in parallel—reducing latency. Compensation order must still respect reverse completion order or explicit dependency graph: if hotel books before flight confirms, compensate hotel first. Parallelism without a documented DAG causes compensation races.

Saga state machine (explicit):

StateMeaningAllowed transitions
STARTEDSaga initiated→ STEP_N_RUNNING
STEP_N_RUNNINGForward step in flight→ STEP_N_OK, COMPENSATING
STEP_N_OKStep committed→ next step or COMPLETED
COMPENSATINGRunning compensations→ COMPENSATED, FAILED
COMPLETEDAll forward steps doneterminal
COMPENSATEDRollback completeterminal
FAILEDManual intervention requiredterminal (ops)

Persist state after every transition—crash recovery replays from last durable state, not from memory.

Customer-visible timeline example:

TimeDB state (order svc)DB state (payment)Customer sees
T0——Checkout clicked
T1PENDING order—Spinner
T2PENDINGAUTHORIZEDStill spinner
T3CONFIRMEDCAPTUREDOrder confirmation email

Between T1–T3, support tools must show in-flight saga—not "no order" or duplicate orders on retry.

Compensation ordering rules:

  1. Compensate in reverse order of successful forward steps (stack discipline).
  2. Skip compensation for steps that never committed.
  3. If step N compensation fails, do not compensate N-1 automatically unless business allows partial state—often halt and page ops.
  4. Idempotent compensation: calling Refund(payment_id) twice must not double-refund—payment provider idempotency keys required.

8. Invariants and Guarantees​

PropertyTypeStatement
Local ACIDSafetyEach step atomic within service DB
Compensation completenessSafetyApplication responsibility—not automatic
Global atomicityNot providedIntermediate states visible
Eventual business consistencyLiveness-oriented goalAfter saga completes or compensates
No duplicate side effectsSafety (with idempotency)Requires idempotent steps
TerminationLivenessRequires timeouts, DLQ, human escalation

Semantic vs physical undo: DELETE order vs status=CANCELLED—compensations are domain-specific.

9. Failure Scenarios​

Scenario 0: Cyclic compensation dependency​

Setup: Choreographed saga where Service A waits for B's compensation event while B waits for A's.

Effect: Deadlock at application level—no progress.

Mitigation: Orchestrator breaks cycle; define acyclic compensation graph; timeout to manual queue.

Scenario 1: Compensation fails​

Setup: Payment refunded fails after inventory release failed.

Effect: Inconsistent state—customer charged, no inventory.

Mitigation: Retry with backoff; saga log marks COMPENSATION_FAILED; alert; manual playbook; reconciliation job.

Scenario 2: Duplicate message​

Setup: ChargePayment delivered twice without idempotency.

Effect: Double charge.

Mitigation: Idempotency key on payment_id; dedup table.

Scenario 3: Lost event (choreography)​

Setup: HotelBooked never delivered; car never booked; flight stuck.

Effect: Saga hung; customer billed for flight only.

Mitigation: Outbox, CDC, orchestrator timeout, state query API.

Scenario 4: Out-of-order events​

Setup: PaymentRefunded arrives before PaymentCompleted processed.

Effect: Invalid state transition.

Mitigation: Versioned saga state; reject invalid transitions; partition by saga_id.

Scenario 5: Visible dirty intermediate state​

Setup: Order created (visible) before payment; customer sees unpaid order.

Effect: UX confusion—not a bug if documented; support tickets.

Mitigation: PENDING status hidden from catalog; semantic locks.

10. Performance Characteristics​

FactorImpact
Async stepsHigher latency than sync monolith—acceptable for many flows
Message overheadEach step: publish + consume + DB
OrchestratorSingle coordination bottleneck—scale horizontally with sharded saga_id
CompensationExtra round trips—failure path slower
Choreography fan-outN services subscribe—broker throughput

Compared to 2PC: Lower lock hold time, better availability; higher complexity and eventual consistency window.

11. Scalability Limits​

  • Orchestrator state store grows with active sagas—partition by saga_id.
  • Choreography debugging doesn't scale with team count—needs tracing (OpenTelemetry).
  • Compensation storms during outages amplify load.
  • Human-in-the-loop steps don't automate—pivot to manual queue.

12. Operational Considerations​

  • Saga dashboard: active, stuck, compensating counts.
  • Timeouts per step with escalation policy.
  • DLQ for poison messages; replay tooling with idempotency.
  • Correlation ID (saga_id, trace_id) across all services.
  • Reconciliation batch jobs compare payment provider vs order DB nightly.
  • Runbooks for COMPENSATION_FAILED and pivot transactions.

13. Security Considerations​

  • Orchestrator privilege: High-trust component—authenticate internal commands.
  • Event tampering: Sign or encrypt sensitive saga commands on bus.
  • Replay attacks: Idempotency keys bound to principal and time window.
  • Compensation authorization: Refund endpoint must verify saga state server-side.

14. Cost Considerations​

  • Engineering: State machines, idempotency, monitoring—higher than monolith.
  • Infrastructure: Workflow engine (Temporal), message broker, extra storage for saga log.
  • Support cost: Intermediate states confuse users without clear UX.
  • Saved cost: Avoids 2PC coupling, coordinator HA, cross-DB locks.

15. Production Implementations​

Temporal / Cadence​

Durable workflow execution—orchestration with automatic retries, timers, saga-style compensation via workflow code. Implementation choice for long-running sagas.

Camunda / Zeebe​

BPMN-based process orchestration—visual flows; enterprise workflow.

AWS Step Functions​

State machine as orchestrator—serverless; step limits and cost model apply.

Custom event-driven (Kafka + choreographed handlers)​

Common in microservices—requires rigorous outbox and idempotency discipline.

NestJS / microservices patterns​

Lightweight sagas via message patterns—team owns correctness.

eBay / large-scale choreographed sagas​

Historical microservices literature describes event-driven sagas at scale with rigorous idempotency and compensating business processes—anecdotal operational experience emphasizing that choreography requires strong conventions (event schemas, versioning, ownership) to remain comprehensible as service count grows.

Banking and payment sagas​

Payment networks often use state machines with explicit states (AUTHORIZED, CAPTURED, REFUNDED) rather than physical deletes. Compensation is a new forward transaction (refund) not an undo of capture—regulatory audit requires append-only payment history. Architects on financial paths should never assume DELETE FROM payments is a valid compensating action.

Saga timeout hierarchies​

Production orchestrators define step timeout < saga timeout < business SLA. Example: payment step 30s, checkout saga 5m, customer-facing checkout 10m. Exceeding saga timeout transitions to REQUIRES_MANUAL_INTERVENTION with paging—not infinite retry loops that amplify outages.

Testing matrix:

TestPurpose
Fail each step onceCompensation order correct
Duplicate every messageIdempotency holds
Slow step past timeoutEscalation fires
Compensation failsAlert + stuck state visible
Concurrent sagas same aggregateSerialization or conflict policy

16. Alternatives and Tradeoffs​

PatternCouplingConsistency windowComplexity
Saga (orch)Medium (orchestrator)Visible intermediateState machine
Saga (choreo)Low between servicesSameDistributed debugging hard
2PC/XAHighNone (atomic)Blocking, ops
Outbox + process managerMediumAsyncGood default combo
MonolithHigh internalImmediateDoesn't scale teams
Event sourcingLowReplayable historySteep learning curve

17. Common Misconceptions​

MisconceptionReality
"Saga = 2PC with events"No global atomicity; compensations are semantic.
"Compensation = DELETE"Often status flip, refund API, release hold.
"Choreography is always better"Loses visibility; orchestration aids ops.
"Exactly-once saga"At-least-once + idempotency = effective once.
"Saga hides intermediate state"Other services/users may observe partial completion.
"Failed step auto-rolls back DB"Prior steps already committed—must compensate.

18. Principal Architect Perspective​

  1. Draw the state machine before choosing choreography vs orchestration.
  2. Define pivot points where compensation ends and humans intervene.
  3. Mandate idempotency keys on every saga step API.
  4. Pair with outbox for reliable event emission from local commits.
  5. Nightly reconciliation catches what sagas miss—belt and suspenders.

Governance: Establish an integration team or architecture guild that owns saga event schemas (OrderCreatedV1), compensation contracts, and breaking-change policy. Without this, choreographed systems become incomprehensible graphs where no one knows the full checkout flow. Version every event; consumers must tolerate unknown fields and dual-subscribe during migrations.

Business stakeholder communication: Sagas are eventually consistent—legal and product must accept that "order confirmed" may lag "payment captured" by seconds. Document SLAs for saga completion and what customer support should say during PENDING states. Escalation paths for FAILED sagas should be defined before launch, not during the first production incident.

19. Architecture Review Exercise​

Scenario: Choreographed checkout: Order → Payment → Shipping via Kafka events; no central saga store; compensation = OrderCancelled event.

Review prompts:

  1. How detect stuck saga after 1 hour?
  2. Duplicate PaymentCompleted handling?
  3. Shipping reads order before payment event—race?
  4. Payment compensated but shipping already dispatched?
  5. Redesign with orchestrator + semantic lock on ship?

Expected findings: Add saga_id state table or workflow engine; idempotency; cannot_ship_until_paid invariant; pivot manual for shipped goods.

20. Whiteboard Explanation​

90-second version:

"A saga breaks a business transaction into local database transactions per service. Each step commits on its own—no distributed rollback. If step three fails, you run compensating transactions in reverse order—refund payment, cancel order—not database UNDO. Orchestration uses a central coordinator with a saga log; choreography uses events where each service knows its role. Compensations are semantic—cancel reservation, not delete row. Messages are at-least-once, so every step must be idempotent. Sagas trade strong consistency for availability compared to 2PC. You see intermediate states, so UX and monitoring matter. Pair with outbox for reliable events and reconciliation jobs for money paths."

21. Interview Questions​

  1. What is a saga?

    • Signals: Local txs sequence; compensate on failure; no global lock.
  2. Compensation vs rollback?

    • Signals: Semantic undo after commit; not MVCC rollback.
  3. Choreography vs orchestration?

    • Signals: Event-driven decentralized vs central coordinator.
  4. Why idempotency in sagas?

    • Signals: At-least-once delivery; duplicate step safety.
  5. Saga vs 2PC?

    • Signals: Eventual vs atomic; availability vs blocking.
  6. What is a pivot transaction?

    • Signals: Point of no compensation—manual resolution.
  7. Visible intermediate state—problem?

    • Signals: UX, support; mitigate with PENDING status.
  8. How handle compensation failure?

    • Signals: Retry, alert, manual playbook, reconciliation.
  9. Semantic lock example?

    • Signals: Don't ship until payment confirmed.
  10. Design flight+hotel booking saga.

    • Signals: Order of steps, compensation order, failure points.
  11. Temporal vs Kafka choreography?

    • Signals: Durable workflow vs event graph; ops visibility.
  12. Lost event in choreography?

    • Signals: Timeout, outbox, orchestrator preferred for critical paths.
  13. Saga and CQRS?

    • Signals: Read models may lag; project from events.
  14. Testing sagas?

    • Signals: State machine tests, chaos on message delay, property-based order.
  15. Can saga steps run in parallel?

    • Signals: Yes with DAG; compensation order must respect dependencies.
  16. What state should support tools show mid-saga?

    • Signals: In-flight status, saga_id, last completed step—not silent failure.

Scoring rubric (principal loop):

DimensionStrongWeak
Atomicity scopeLocal ACID per step"Distributed transaction" hand-wave
Failure pathCompensation order + idempotency"Roll back"
OpsTimeouts, stuck detection, reconciliationNo monitoring
Style choiceChoreo vs orch tradeoffs namedOne-size-fits-all

22. Interview Follow-Ups​

  1. Customer double-charged in saga—debug steps?

    • Signals: Idempotency audit, payment provider id, saga log, duplicate delivery.
  2. When refuse saga and use single DB?

    • Signals: Strong invariants, small team, no scale-out need.
  3. Saga across 12 services—orchestrator bottleneck?

    • Signals: Shard orchestrator, async steps, simplify graph.

22A. Production Low-Level Design (Interview + Game Day)​

Orchestrated checkout saga with compensations. Production LLD and Game Day Standard.

State machine (LLD)​

StepForwardCompensate
1Reserve inventoryRelease reservation
2Authorize paymentVoid / refund
3Create shipmentCancel shipment

Step-by-step flow:

StepNotes
1–3Each local TX + outbox/command; orchestrator persists saga state
4Compensations are business undo, not DB rollback
*Idempotent steps; timeouts → unknown → status before compensate

API sketch​

POST /sagas/checkout → {saga_id}; GET /sagas/{id} status; commands idempotent by saga_id+step.


22B. Game Day Playbooks​

#DrillInjectDetectMitigateVerify
GD-1Fail after pay before shipKill ship serviceSaga stuck PaidCompensate payment + inventoryNo orphan charge
GD-2Duplicate step messageRedeliver reserveIdempotent noop—Single reservation
GD-3Compensate failsRefund 5xxCompensating alarmRetry / manualOps runbook clears

GD-1 — Mid-saga failure​

23. Strong Answer Example​

Question: "Design checkout across order, payment, inventory services."

Answer this as a 45-minute design discussion using the PRACTICE framework. Below is how a strong student sounds aloud—saga + orchestration, not XA, and compensate ≠ DB rollback.

PRACTICE interview answer map for checkout saga across three services

Figure A: PRACTICE map — Problem → Requirements → Assumptions → Capacity → Topology → Invariants → Constraints → Evolution.


Student interview script (PRACTICE)​

P — Problem framing​

"Checkout spans three services / three databases: Order, Inventory, Payment. We can't use XA/2PC across independently deployed services—blocking, coupling, and the card PSP isn't an XA participant anyway.

So I'd design a saga: each step is a local ACID transaction; on failure we run compensating transactions in reverse—semantic undo, not distributed rollback.

Coordination: For checkout I'd pick orchestration—a durable workflow / saga table keyed by checkout_id—so ops can see one state machine. Choreography works but loses global visibility on a money path.

Short answer: Orchestrated saga: create PENDING order → reserve inventory (hold + TTL) → capture payment → mark PAID / confirm stock—with idempotent steps, timeouts, and reconciliation."

R — Requirements​

RequirementDesign implication
No oversellConditional reserve / hold before confirm
No orphan chargeDon't capture until reserve OK (or auth+capture split)
No double charge on retryIdempotency key = checkout_id (or payment intent id)
Customer UXHide or clearly label PENDING; don't show false "paid"
Support / opsSaga dashboard; stuck → page; manual pivot after ship
Ship only if paidSemantic lock: dispatch consumes PAID only

"I'd clarify: physical goods vs digital? Auth-then-capture vs immediate charge? Multi-warehouse inventory?"

A — Assumptions (state aloud)​

AssumptionWhy it matters
Separate DBs per serviceNo shared transaction
At-least-once messagingEvery step must be idempotent
Payment via external PSPCompensations = refund/void, not DELETE
Inventory is soft-hold then confirmTTL releases abandoned carts
Shipping is later / out of saga or after pivotCan't auto-unship easily

"I'd say out loud: messages are at-least-once; effective exactly-once = idempotent handlers."

C — Capacity​

Checkout QPS (say 1k peak) → orchestrator must shard / partition by checkout_id
Inventory hot SKU → row locks / conditional UPDATE; watch contention
Payment PSP p99 → step timeout < saga timeout < UX SLA
Hold TTL (e.g. 15m) → balance conversion vs abandoned-cart waste
Reconciliation nightly + lag alerts → mandatory for money

"I'd size holds and timeouts to conversion, not leave reservations forever."

T — Topology (draw this)​

Checkout saga orchestration across order, inventory, payment

Figure B: Orchestrator drives forward steps; dashed path is backward recovery (release hold, cancel order; refund if charged).

Happy path (my default order):

StepLocal TXOutbox / result
1Order: insert PENDINGOrderCreated
2Inventory: reserve if available >= qtyHold id + TTL
3Payment: capture/charge with idempotency keyPaymentCaptured
4Order → PAID; Inventory → confirm holdCheckoutCompleted

Why reserve before pay: Prefer failing on stock before charging; reduces refund volume. Alternate (pay then reserve) is OK if product wants payment-first—then inventory failure must refund/void.

Checkout states, compensations, and failure modes

Figure C: State machine, reverse compensations, and common pitfalls (idempotency, holds, TTL, pivot).

Forward stepCompensation
Create PENDING orderCancel / expire order
Reserve stockRelease hold
Capture paymentRefund / void (idempotent)
Confirm reservationRare—usually after pivot; manual if shipped

Choreography vs orchestration: I'd use orchestration for checkout (visibility, timeouts, single saga log). Choreography OK for simpler fan-out; still need outbox + idempotency + a way to detect stuck flows.

I — Invariants (safety)​

"Non-negotiable:

  1. No XA across the three services.
  2. Each step local ACID + outbox for reliable handoff.
  3. Idempotent forward and compensate APIs.
  4. Compensations in reverse of successful steps; skip steps that never committed.
  5. Holds have TTL; abandoned checkout must release stock.
  6. Pivot: after ship (or irreversible fulfill), stop auto-compensate—human / support playbook.
  7. Reconciliation payment ledger ↔ orders ↔ inventory holds."

C — Constraints (second C)​

ConstraintDesign response
PSP latency / outagesAuth hold + capture; retries with same key; degrade gracefully
Hot SKU racesConditional UPDATE … WHERE available >= qty; or queue per SKU
Orchestrator crash mid-sagaDurable saga state; resume; never assume in-memory only
Compensation failsHalt → COMPENSATION_FAILED alert; don't silently continue
Poison messagesDLQ + replay with same idempotency key
Customer retries "Buy"Client/checkout_id dedupe returns same saga

E — Evolution (prove it)​

Phased delivery:

PhaseDeliverable
M1Saga state machine + ADR (orch vs choreography; step order)
M2Order + outbox; inventory reserve/release with TTL
M3Payment idempotent charge/refund; wire orchestrator
M4Timeouts, dashboard, COMPENSATION_FAILED paging
M5Chaos: kill orch mid-pay; duplicate events; inventory fail
M6Nightly reconcile + support tools for stuck checkouts

Failure modes:

FailureMitigation
Double chargeIdempotency key on PSP + local payment row unique
OversellConditional reserve; confirm only after pay
Orphan holdTTL + sweeper + metrics on aged holds
Paid but order not updatedOrchestrator retry; reconcile job
"Roll back via Kafka" wishful thinkingExplicit compensations + state machine

Observability: saga state counts, step latency, compensation rate, hold age, unpaid/paid mismatch, DLQ depth, PSP idempotency conflicts.


Closing line (interview)​

"So: orchestrated saga—not XA. Create PENDING order, reserve inventory with TTL, charge with idempotency key checkout_id, then mark paid and confirm stock. Failures run compensations in reverse. Every step is local ACID + outbox; messages are at-least-once so handlers are idempotent. I'd add step/saga timeouts, a dashboard for stuck flows, shipping gated on PAID, and reconciliation. After an irreversible pivot like ship, humans take over—not blind auto-undo."

Scoring signals​

StrongWeak / red flag
Saga + local TX + compensate"Just use Kafka / 2PC / roll back"
Orchestration rationale for checkoutPure choreography with no stuck story
Idempotency keysIgnores duplicates
Hold TTL + reverse compensationsPhysical DELETE as undo
Pivot + reconciliationNo money/ops follow-through
Rejects XA with reasonProposes distributed transaction casually

Compact outline (if time-boxed to 2 minutes)​

"Orchestrated saga, not XA. PENDING order → reserve stock (TTL) → idempotent pay → confirm. Compensate in reverse. Outbox per step. Timeouts, dashboard, reconcile. Shipping only after PAID. Pivot to humans after irreversible fulfill."

24. Weak Answer Example​

Question: "Design checkout across order, payment, inventory services."

"Use Kafka events between services. If something fails, roll back."

Why weak / red flags: No local-commit reality, no compensation semantics, no idempotency, no saga state/timeouts, no stuck-flow or reconciliation story—treats events as distributed rollback.

25. Hands-On Exercise​

Lab 010: Saga Orchestration (runnable)​

Full hands-on lab at labs/lab-010-saga-orchestration/ — Go HTTP API on port 8093, orchestrator + in-process participant stubs (payment → inventory → shipping).

cd labs/lab-010-saga-orchestration
go test ./... -v
docker compose -p lab010 -f docker/docker-compose.yml up --build -d
curl http://localhost:8093/health
chmod +x scripts/demo_saga.sh && ./scripts/demo_saga.sh

Demo flow (landing page at http://localhost:8093/):

StepEndpointWhat happens
1POST /v1/sagasPayment → inventory → shipping → completed
2POST /v1/chaos/inventory-failEnable inventory failure injection
3POST /v1/sagasInventory fails → compensate_payment → compensated
4POST /v1/chaos/resetClear chaos flag
5POST /v1/sagas/{id}/crashSimulate orchestrator crash after payment
6POST /v1/sagas/{id}/recoverResume from saga log

Complements Lab 009 outbox — outbox per step, orchestrator for global flow.

Engineer guide: how the local stack works​

This section documents the runtime behavior of lab-010 as you would read it in a production runbook — component boundaries, saga state machine, and how to verify compensation.

Runtime topology​

ProcessPort / entrypointResponsibility
Saga API:8093 — go run ./src/main.go --serveHTTP orchestrator; drives saga state machine
Payment stubin-processReservePayment / CompensatePayment (idempotent by key)
Inventory stubin-processReserveInventory — chaos flag fails next call
Shipping stubin-processCreateShipment — final forward step

Browser entrypoints: http://localhost:8093/ (HTML landing), http://localhost:8093/docs (Swagger UI), http://localhost:8093/health.

API contract — POST /v1/sagas​

Request body

FieldRule
product_idRequired — logical product being ordered
idempotency_keyOptional — duplicate key returns same saga (no double charge)

State transitions (happy path)

started → payment_reserved → inventory_reserved → shipped → completed

Compensation path (inventory failure after payment)

payment_reserved → compensating → compensated

Each transition is appended to Saga.Log — inspect via GET /v1/sagas/{id}.

Chaos and recovery​

EndpointPurpose
POST /v1/chaos/inventory-failNext saga fails at inventory — triggers compensation
POST /v1/chaos/resetDisable failure injection
POST /v1/sagas/{id}/crashSimulate orchestrator crash mid-saga
POST /v1/sagas/{id}/recoverResume from last committed log entry

Verify compensation: GET /health → compensate_calls: 1, sagas_compensated: 1.

Contrast with Lab 009: outbox ensures reliable events; saga ensures multi-step business process consistency via compensations. Production systems often combine both (outbox per step, orchestrator for global flow).

Self-study checklist (optional)​

  1. Model checkout as state machine (diagram in lab README).
  2. Run happy path; inspect saga log transitions.
  3. Inject inventory failure; verify compensation order.
  4. Retry same idempotency_key — observe deduplication.
  5. Simulate crash + recover — no double payment reservation.
  6. Document pivot: what if compensation impossible (e.g., shipped goods)?

26. Knowledge Check​

  1. Saga compensations run in? (Reverse order of successful steps.)
  2. Choreography coordination via? (Events, no central controller.)
  3. Why not physical DELETE for compensate? (Already committed; business semantics.)
  4. At-least-once requires? (Idempotent handlers.)
  5. Saga provides global ACID? (No.)

27. Flashcards​

#FrontBack
1SagaLocal tx sequence + compensations.
2CompensationSemantic undo of committed step.
3ChoreographyEvent-driven decentralized saga.
4OrchestrationCentral coordinator + saga log.
5Backward recoveryCompensate prior steps on failure.
6Forward recoveryRetry failed step.
7Pivot transactionNo auto-compensation beyond here.
8Semantic lockBusiness guard during in-flight saga.
9vs 2PCAvailable, eventual, not atomic global.
10Idempotency keyDedup retried saga steps.
11Garcia-Molina 1987Original saga paper.
12Intermediate stateVisible—design UX accordingly.

28. Cheat Sheet​

SAGA
Forward: local ACID steps
Backward: compensate in reverse
No global rollback

STYLES
Choreography: events, loose coupling, hard debug
Orchestration: central state, easier ops

REQUIREMENTS
Idempotent steps
saga_id correlation
Timeouts + DLQ
Reconciliation for money

VS 2PC
Saga: eventual, available
2PC: atomic, blocking

OPS
Stuck saga dashboard
COMPENSATION_FAILED runbook

30. References​

Primary sources​

  • Garcia-Molina, H., & Salem, K. (1987). "Sagas." SIGMOD — original saga definition.
  • Gray, J., & Reuter, A. (1993). Transaction Processing — contrast with 2PC.

Production and engineering​

Distinction​

Claim typeSource
Saga definitionGarcia-Molina & Salem (1987)
Orchestration patternsRichardson; Temporal docs
Comp vs 2PC tradeoffsKleppmann; engineering practice