The naive mental model is a function. “Place an order? Reserve inventory, charge the card, create a shipment, return success. If anything throws, catch it and undo the earlier steps. It is a try/catch with some rollback in the finally.” That survives exactly until the interviewer starts asking what happens between the lines. You charged the card, and the process crashed before you created the shipment - who finishes the order, and how do they even know it was half done? The payment service returned a timeout - did the charge go through or not, and do you retry it or refund it? You need to undo three completed steps because the fourth failed - in what order do you undo them, and what if the undo itself fails? Two services you call do not support rollback at all - now what? None of these are edge cases. In a system doing millions of orders, every one of them happens every hour.

A distributed transaction across services is hard because the one tool that would make it easy - a single ACID transaction with a commit and a rollback across all the databases - does not exist across service boundaries. Inventory, payment, and shipping each own their own database; there is no shared lock, no shared commit. The textbook answer, two-phase commit (2PC), requires every participant to hold locks through a blocking prepare phase and hands a single coordinator the power to freeze the whole system if it dies mid-commit - unacceptable for a long-running business transaction that spans seconds to days and calls services that will not hold a lock that long. The saga pattern is the alternative: break the distributed transaction into a sequence of local transactions, each in one service, and for each step define a compensating action that semantically undoes it. If step 4 fails, you run the compensations for steps 3, 2, 1 in reverse. The whole thing lives or dies on one property most people skip: the orchestrator must persist its progress durably at every step, so that when it crashes - and it will - a recovered orchestrator can look at the saga’s state and know exactly whether to go forward or roll back, and from where.

Let me build it properly.

Functional Requirements (FR)

In scope:

  • Execute a multi-step business transaction across services. The canonical example: order fulfillment = reserve inventory -> charge payment -> create shipment -> confirm order. Each step is a call to a different service that commits locally.
  • Define a saga as an ordered sequence of steps, each with a forward action and a compensation. Step N has do() (reserve inventory) and undo() (release the reservation). The orchestrator drives the sequence.
  • Persist saga state durably at every transition. Before and after each step, the orchestrator records where it is (which step, succeeded or failed, what the result was) so a crash cannot lose progress.
  • Resume after a crash. A recovered orchestrator (or a different orchestrator node) reads persisted state and continues the saga from exactly where it stopped - either driving the next forward step or starting compensation - with no human intervention.
  • Compensate in reverse order on failure. If a forward step fails and is not retriable, run the compensations for all previously completed steps, in strict reverse order, until the saga is fully rolled back.
  • Retry transient failures with backoff before giving up. A timeout or a 503 from a service is retried (idempotently) a bounded number of times before the step is declared failed and compensation begins.
  • Idempotent steps and compensations. Because the orchestrator is at-least-once (it may re-send a step after a crash where it is unsure the step ran), every forward action and every compensation must be safe to invoke more than once.
  • Visibility. Query a saga’s current state, its step history, and its final outcome (completed / compensated / failed-and-stuck). Operators need to see stuck sagas.

Explicitly out of scope (own the scope):

  • The business logic inside each service. We orchestrate “call reserve-inventory, then charge-payment”; what reserving inventory means (which warehouse, which SKU rules) lives in the inventory service. We own the transaction coordination, not the domain.
  • Strong isolation / serializability across the saga. A saga is not an ACID transaction. Other transactions can see the intermediate state (inventory reserved but order not yet confirmed). We get atomicity (all steps or all compensated) and durability, but not isolation - we address the anomalies that causes, we do not pretend they vanish.
  • Guaranteeing a compensation perfectly reverses a side effect. Compensation is semantic, not physical. You cannot un-send an email; you send an apology. You cannot un-charge instantly; you issue a refund that leaves a trace. We model this honestly.
  • Choreography as the primary model. We build an orchestrated saga (a central coordinator drives steps). We contrast it with choreography (services react to each other’s events with no central brain) and say why orchestration wins for complex rollback ordering, but we do not build the choreographed variant.
  • Cross-saga distributed locking / global deadlock resolution. Two sagas contending for the same inventory is handled at the service level (its own concurrency control); we do not build a global lock manager.

The one decision that drives everything: a saga orchestrator is a durable, crash-recoverable state machine, not a function call stack. The sequence of steps is data in a database, not frames on a stack, because a stack dies with the process and a database does not. Every forward step and every compensation is a transition recorded durably before it is attempted and confirmed after, so that recovery is just “read the last durable state and decide the next move.” Everything below is a consequence of treating the saga as persisted state rather than running code.

Non-Functional Requirements (NFR)

  • Scale: on the order of millions of active sagas per day, with a steady start rate of thousands of new sagas/sec at peak (an e-commerce checkout flow), each saga having 3-8 steps. Sagas are long-running: most finish in seconds, but a step can wait on a slow external service (a payment gateway, a shipping carrier) for seconds to minutes, and some sagas legitimately stay open for hours or days (a pre-order, a manual approval).
  • Latency: the orchestrator’s own overhead per step (read state, call service, persist result) should be single-digit milliseconds; end-to-end saga latency is dominated by the downstream services, not by us. A happy-path 4-step order should complete within the sum of its service calls plus a few ms of orchestration.
  • Availability: 99.95%+ on starting and advancing sagas. No orchestrator node is a single point of failure - a node dying must not strand the sagas it was driving; another node picks them up within seconds.
  • Durability / correctness - the headline: once a saga starts, it reaches a terminal state (completed or fully compensated) despite any crash. No saga is left half-applied silently. Persisted saga state survives node and disk loss (replicated store). This is the property the entire design exists to protect.
  • Consistency semantics: atomicity without isolation. Either all forward steps commit, or all completed steps are compensated - never a permanent partial state. But intermediate states are visible to the outside world (no serializable isolation), so the design must tolerate and bound the resulting anomalies.
  • Execution semantics: at-least-once for every step and compensation. A step may be invoked more than once (after a crash where we cannot tell if it ran), so steps must be idempotent. Exactly-once across service boundaries is impossible; we engineer idempotency to make duplicates harmless.

Back-of-the-Envelope Estimation (BoE)

Let me ground it in numbers.

Saga volume and step rate:

New sagas/day:          10,000,000  (orders)
Peak start rate:        assume 4x average over a 6-hour active window.
   avg = 10M / 86,400 ~ 116/sec; peak ~ thousands/sec at a sale/flash event.
   Design target: 5,000 new sagas/sec peak.
Steps per saga:         ~4 forward (reserve, charge, ship, confirm)
   On failure: up to 4 compensations. So a failed saga does ~8 transitions.
Failure rate:           say 5% of sagas hit a non-retriable failure and compensate.
Transitions/sec peak:   5,000 sagas/sec * ~4 steps = 20,000 forward step
   executions/sec; + compensations on the 5% that fail.

The first non-obvious number: the orchestrator writes to its durable store at least twice per step (once to record “about to attempt step N,” once to record “step N succeeded/failed”). So 20,000 step executions/sec is ~40,000+ durable writes/sec to the saga log at peak. The store write rate, not the service call rate, is often the orchestrator’s own bottleneck.

Durable state store load:

Writes:  ~40,000 state-transition writes/sec at peak (2+ per step).
Reads:   each step starts by reading the saga's current state (or it is cached
         in the owning node's memory, backed by the log). Recovery re-reads.
Write pattern: append-mostly (a log of transitions) + a current-state row updated.

Storage:

Per saga: id, type, status, current step, per-step records (name, state,
   request, response/result, timestamps, attempt count), compensation state.
   Say ~2-4 KB per saga including its step log.
10M sagas/day * 3 KB = ~30 GB/day of saga state.
Hot retention (active + recently completed, for debugging): 30 days
   = ~900 GB, * replication 3 = ~2.7 TB. Modest for a sharded store.
Completed sagas older than the retention window roll to cold storage;
   the active working set (open sagas) is far smaller - most close in seconds.
Active (open) sagas at any instant: if avg saga lifetime is 10s and start
   rate is ~2,000/sec average, in-flight = 2,000 * 10 = ~20,000 open sagas.
   Long-running sagas (hours/days) add a slowly-accumulating tail -> maybe
   low millions of open sagas if many pre-orders/approvals stay open.
   The hot in-flight set is what each orchestrator node holds/tracks.

Orchestrator fleet:

20,000 step executions/sec, each step = read state + call a service (IO-bound,
   waiting on the downstream) + write state. Say 50ms average wall time per step
   dominated by the service call.
Concurrent in-flight steps = 20,000/sec * 50ms = ~1,000 concurrent calls... but
   many steps wait minutes on slow carriers -> model as async, not thread-per-saga.
With async IO, one node drives thousands of in-flight sagas. Say ~2,000 sagas
   per node -> millions of open sagas / 2,000 = low hundreds of nodes, sized by
   open-saga count and write throughput, not by CPU.

The headline shape: the scarce resources are durable write throughput to the saga log (2+ writes per step) and the count of open sagas held in flight, not raw storage or CPU. The services we call are the latency; our own cost is the persistence. Size the store for ~40K writes/sec, partition it, and never block a thread per saga - drive sagas as async state machines so a saga waiting three minutes on a carrier costs a row, not a thread.

High-Level Design (HLD)

The system splits into planes: an API tier that starts sagas and answers status queries; a durable saga store (sharded, replicated) that holds every saga’s definition, current state, and step log - the source of truth; an orchestrator tier of worker nodes that each own a partition of sagas, drive their steps forward (or their compensations backward), and persist every transition; a durable command/event bus between the orchestrator and the participant services so step invocations and their replies survive crashes; and the participant services (inventory, payment, shipping) that each expose an idempotent action and an idempotent compensation. A coordination service (Raft/ZooKeeper-style) assigns saga partitions to orchestrator nodes and handles failover. A timer/timeout service wakes sagas that are waiting (a step that has not replied, a saga parked for a scheduled resume).

  CLIENT                        ┌──────────── COORDINATION (Raft quorum) ─────────────┐
 ┌────────┐                     │  - partition assignment: which node owns which       │
 │ start  │                     │    saga partition                                    │
 │ order  │                     │  - node liveness / failover: reassign a dead node's  │
 └───┬────┘                     │    partitions in seconds (fencing epoch per grant)   │
     │ 1. POST /sagas           └───────────────┬──────────────────────────────────────┘
     ▼                                          │ watch assignments
 ┌─────────┐   2. create saga   ┌───────────────▼───────────────────────────────┐
 │  API    │──────────────────► │          SAGA STORE (sharded, replicated)       │
 │  tier   │  (type, input,     │   partition by saga_id                           │
 └─────────┘   idempotency key) │   saga row: status, current_step, direction      │
                                │   step log: per step {state, request, response,  │
                                │             attempt, idempotency_key, ts}         │
                                └───────────────┬───────────────────────────────────┘
                                                │ 3. owning orchestrator loads saga,
   ┌──────────── ORCHESTRATOR TIER ─────────────┤    picks next action from state
   │  node O0 owns partitions {0,3}             │
   │  node O1 owns partitions {1,4}  ◄──────────┘  4. record "attempting step N"
   │  node O2 owns partitions {2,5}                   (durable WRITE before the call)
   │  each: for each owned saga, run the state machine:                           │
   │    forward -> next step | failed -> compensate backward | done -> terminal   │
   └───────────────┬──────────────────────────────────────────────────────────────┘
                   │ 5. send command (durable)              ▲ 7. reply (success/fail)
                   ▼                                        │    -> record result (WRITE),
        ┌──────────────────────────┐                       │       advance / start rollback
        │   COMMAND / EVENT BUS     │  6. deliver command, participant runs its
        │   (durable, partitioned)  │     LOCAL transaction (idempotent), replies
        └───────┬──────────┬────────┘
                ▼          ▼          ▼
        ┌───────────┐ ┌──────────┐ ┌───────────┐     each service exposes:
        │ INVENTORY │ │ PAYMENT  │ │ SHIPPING  │       do():   local txn, idempotent
        │  service  │ │ service  │ │  service  │       undo(): compensation, idempotent
        └───────────┘ └──────────┘ └───────────┘

        TIMER SERVICE ── wakes sagas waiting on a reply (step timeout) or parked
                         for a scheduled resume; re-drives them via the owner node.

Request flow - starting a saga (the entry path):

  1. A client calls POST /sagas with the saga type (order_fulfillment), the input (order details), and a client idempotency key (so a retried checkout does not create two orders). The API validates it.
  2. The API writes a new saga row to the saga store in status started, with its ordered step list materialized from the saga definition, current_step = 0, direction = forward. It is durable and replicated now; the saga will run to a terminal state no matter what. The API acks the client with the saga id.

Request flow - driving a step forward (the happy path):

  1. The orchestrator node that owns this saga’s partition picks it up (from its in-memory active set, primed from the store, or on recovery by scanning the store). It reads the saga’s state and decides the next action: the next forward step.
  2. Before invoking the step, it writes a durable transition: step N -> attempting, with a freshly minted per-step idempotency key. This write-ahead record is what makes recovery possible: if we crash now, recovery sees “step N was being attempted” and knows to check/redo it.
  3. It sends the step’s command onto the durable command bus (reserve inventory, with the idempotency key). The bus persists the command so it is not lost if the orchestrator dies between send and reply.
  4. The participant service receives the command, runs its local transaction (reserve the stock), deduplicating on the idempotency key so a redelivered command does not double-reserve, and replies with success and a result (a reservation id).
  5. The orchestrator records step N -> succeeded with the result (a durable write), advances current_step, and loops to step N+1. When the last forward step succeeds, it writes status completed - a terminal state.

Request flow - failure and compensation (the rollback path):

  • If a step’s reply is a transient failure (timeout, 503), the orchestrator retries it with backoff (re-sending the same idempotency key, so a duplicate is harmless) up to a bound.
  • If a step fails non-retriably (payment declined) or exhausts retries, the orchestrator flips direction = backward and begins compensation: it walks the completed steps in strict reverse order, and for each, writes compensating, sends the step’s undo() command (release the reservation, void the charge) with a compensation idempotency key, records compensated, and moves to the previous step. When all completed steps are compensated, it writes status compensated - also a terminal state. The failing step itself needs no compensation (its local transaction did not commit).

The key architectural insight: the orchestrator never holds the saga’s progress only in memory or on a call stack - every transition is written to the durable store before and after the side effect. A single function with try/catch keeps its progress on the stack, so a crash erases “I already charged the card” and no recovered process can learn it. By making the saga a persisted state machine, recovery becomes trivial and uniform: load the last durable state, and the state alone tells you whether to go forward, retry, or roll back - the orchestrator is stateless about which saga it drives, because all the state is in the store.

Component Deep Dive

Four hard parts: (1) the coordination model itself - why orchestration over 2PC and over choreography; (2) persisting step state so the orchestrator resumes correctly after a crash - the write-ahead log and the recovery algorithm; (3) compensation - running rollbacks in the right order, idempotently, when a compensation itself can fail; and (4) making every step idempotent and surviving the “did it run?” ambiguity. I will walk each from naive to correct.

1. The Coordination Model: Why Not 2PC, and Why Orchestration Over Choreography

We need “all services commit or all roll back” across databases that share nothing. The instinct is to reach for a distributed-transaction protocol.

Approach A: Two-phase commit (2PC) across the services (the textbook instinct)

A coordinator asks every participant to prepare (do the work, hold locks, promise you can commit), and when all vote yes, tells them all to commit; if any votes no, tells all to abort.

Where it breaks: three fatal problems for our setting. First, locks held across the whole transaction - the payment and shipping services must hold a prepared-but-uncommitted transaction (and its locks) from the prepare vote until the final commit, which spans the latency of every other participant. For a saga that waits minutes on a carrier, that is minutes of held locks; for one parked for manual approval, it is hours. No high-throughput service will hold a row lock that long. Second, the coordinator is a blocking single point of failure: if it crashes after participants voted yes but before it sends commit/abort, every participant is stuck in-doubt, holding locks, unable to decide alone - the system freezes. Third, many services do not support a prepare/commit protocol at all (a third-party payment gateway has no “prepare” verb). 2PC assumes a level of participant cooperation and lock tolerance that cross-service, long-running business transactions do not have.

Approach B: Choreography - services react to each other’s events (no central brain)

Each service listens for events and reacts: inventory reserves and emits InventoryReserved; payment listens for that, charges, emits PaymentCharged; shipping listens and ships. On failure, a service emits a failure event and upstream services listen for it and compensate themselves.

  • Good for simple, linear flows: no central coordinator, loosely coupled, each service owns its piece.
  • Where it breaks at complexity: the control flow is smeared across every service - there is no single place that knows the saga’s state or the step order, so understanding “where is this order and what happens next” means tracing events through N services. Worse for our hard part: compensation ordering becomes emergent and fragile. When step 4 fails, the correct reverse-order rollback (undo 3, then 2, then 1) has to be reconstructed from each service independently reacting to failure events, and getting the order and completeness right (did everyone who needed to compensate actually do it?) is nearly impossible to reason about as steps grow. Cyclic event dependencies and “who compensates whom” turn into a distributed-systems puzzle with no central answer. Choreography also has no natural home for the durable saga state that recovery needs.

Approach C: Orchestration - a central coordinator drives the saga as a persisted state machine

A single orchestrator owns the saga definition (the ordered steps and their compensations), calls each service in turn, records every transition durably, and on failure drives the compensations in reverse - all from one place.

  • No distributed locks, no in-doubt freeze. Each step is a local transaction in one service that commits immediately and independently; nothing is held across the whole saga. There is no prepare phase and no global lock. A slow carrier just means the saga’s row sits in a waiting state - cheap - instead of a held lock.
  • The rollback order is explicit and centralized. Because one component knows the full step sequence and which steps completed, it runs compensations in exactly reverse order, and it knows when rollback is complete. This is the decisive advantage for our focus: correct, ordered, complete compensation is a property of having a central state machine, and it is the thing choreography cannot give you cleanly.
  • There is a single durable home for saga state, which is exactly what crash recovery needs (part 2). The orchestrator being central does not make it a 2PC-style single point of failure, because it holds no locks and its state is in the replicated store, not in the process - any orchestrator node can pick up any saga from the store. “Central logic” is not “central fragility” once the state is externalized and the nodes are interchangeable.

The trade we accept, stated honestly: orchestration gives up the loose coupling of choreography (services now receive commands from a coordinator rather than only reacting to events) in exchange for a single, reasoned-about place that owns ordering, state, and rollback. For a transaction whose hard part is correct compensation ordering and crash recovery, that trade is clearly right.

ModelLocks heldRollback orderingDurable state homeFails when
2PCYes, across whole txnN/A (atomic commit)Coordinator logCoordinator dies mid-commit -> in-doubt freeze; participants must support prepare
ChoreographyNoEmergent, fragile as steps growNone (smeared)Complex flows; compensation order/completeness hard to guarantee
OrchestrationNoExplicit, central, completeReplicated saga storeNeeds a well-built recoverable orchestrator (this design)

2. Persisting Step State So the Orchestrator Resumes After a Crash

This is the heart of the problem. The orchestrator will crash mid-saga. A recovered node must look at what is persisted and resume correctly - without re-charging a card that was already charged or forgetting a reservation it already made.

Approach A: Keep progress in memory / on the call stack (naive)

The orchestrator runs the saga as a function: call reserve, await, call charge, await, call ship. Progress lives in local variables and the stack.

Where it breaks: the process crashes between “charge succeeded” and “ship.” The stack is gone. There is no record anywhere that the charge happened. A restarted process has no idea this saga exists, let alone that it is half done. The order is permanently stuck: the customer was charged, nothing shipped, and no component knows to finish or refund. This is the exact failure the system exists to prevent, and in-memory state guarantees it on every crash.

Approach B: A durable write-ahead saga log, written before and after every side effect

Model the saga as a persisted state machine with a write-ahead log of transitions. The invariant: never perform a side effect without a durable record that you are about to, and record the outcome durably before moving on.

For each step N:
  1. WRITE (durable, replicated):  step N -> ATTEMPTING, idempotency_key = K_N
  2. invoke the service step with K_N   <-- the only side effect
  3. on reply:
       WRITE:  step N -> SUCCEEDED (result) ... or FAILED (reason)
  4. advance current_step / set direction=backward

The saga’s durable record looks like:

saga {
  id, type, status: started|running|compensating|completed|compensated|failed,
  direction: forward | backward,
  current_step: int,
  steps: [
    { name: "reserve_inventory", state: SUCCEEDED, idem_key, request, result, attempt, ts },
    { name: "charge_payment",    state: ATTEMPTING, idem_key, request, result=null, attempt, ts },
    { name: "create_shipment",   state: PENDING, ... },
    ...
  ]
}
  • Why write-ahead (before the call) is non-negotiable. If you only wrote after the call, a crash between the call and the write would leave a committed side effect (card charged) with no record of it - the same silent-loss failure. Writing ATTEMPTING before the call means recovery always sees that a step was in flight and can resolve it. The order is: durable intent, then side effect, then durable outcome.
  • Each step-attempt carries a stable idempotency key minted at the ATTEMPTING write. If recovery re-sends step N, it re-sends the same key, so the participant (which dedups on the key) treats the retry as a no-op if it already ran. This is what makes “redo a step we are unsure about” safe (part 4).

The recovery algorithm (the payoff)

On startup, or when a partition is reassigned to it, an orchestrator node scans the store for its sagas in non-terminal states and, for each, resolves state purely from the persisted log:

recover(saga):
  if status in {completed, compensated, failed}: done, skip.
  find the last step with state == ATTEMPTING or COMPENSATING (the in-flight one):

  case ATTEMPTING (forward, outcome unknown):
     we don't know if the service ran it. Resolve it:
       - query the participant by idempotency_key (preferred): "did K_N complete?"
            ran    -> record SUCCEEDED, continue forward
            not    -> re-send step N with the SAME K_N (idempotent), await reply
       - or just re-send with K_N and let the participant's dedup decide.
  case SUCCEEDED on all up to current_step, direction forward:
     drive the next PENDING step forward.
  case FAILED (non-retriable) or direction == backward:
     resume COMPENSATION from the current backward position (part 3).
  case COMPENSATING (a compensation was in flight):
     re-send that compensation (same comp idem key), then continue backward.

Because every decision is derived from durable state, recovery is deterministic and idempotent: it does not matter whether the original node or a new one runs it, nor how many times recovery itself restarts. The saga converges to its terminal state. The orchestrator node is effectively stateless about saga content - all saga state is in the store - so losing a node loses nothing but the work of re-reading a few rows.

  • Partition ownership for who recovers what. Sagas are partitioned (by saga_id) and each partition is owned by one orchestrator node via the coordination service (same pattern as a sharded scheduler). On a node death, its partitions are reassigned within a heartbeat timeout and the new owner runs recover() for each open saga it inherits. A fencing epoch on the partition grant stops a zombie old owner from also driving the saga (its stale-epoch writes are rejected by the store), so two nodes never drive the same saga concurrently.
  • Optimistic concurrency on the saga row. Every transition write is a CAS on a version column (UPDATE ... WHERE id=? AND version=?). If two nodes briefly both think they own a saga (failover overlap), only one write wins; the loser notices the version moved and backs off. Ownership plus fencing usually prevents the overlap; the version CAS is the correctness backstop.

Persisting a write-ahead log of transitions turns crash recovery from “impossible” into “replay from the last durable state,” and it is the single property that separates a real saga orchestrator from a function with a try/catch.

3. Compensation: Ordered, Idempotent Rollback When Undo Itself Can Fail

A forward step failed non-retriably. Now undo everything that committed, correctly.

Approach A: Undo in any order, best-effort (naive)

Loop over the completed steps and call each one’s undo, fire-and-forget, in whatever order is convenient.

Where it breaks: two problems. First, order matters. If reserving inventory happened before charging payment, and a later step needs the compensations to respect dependencies (e.g. a loyalty-points step that was applied because payment succeeded), undoing payment before undoing the points can leave an inconsistent intermediate the services do not expect. The safe, general rule is strict reverse order - the mirror of the forward order - because step K+1 may depend on the state step K created, so you must unwind K+1 before K. Second, best-effort fire-and-forget loses failed compensations: if release_inventory times out and nobody tracks it, the reservation leaks forever. Compensation must be as durable and tracked as the forward path.

Approach B: Reverse-order, durably-tracked, retried, idempotent compensations

Treat compensation as the forward path run backward, with the same durability discipline:

compensate(saga):   # direction = backward
  for step K from (current_step - 1) down to 0, where step K state == SUCCEEDED:
     WRITE: step K -> COMPENSATING, comp_idem_key = C_K   # write-ahead, as before
     send step K.undo() command with C_K                   # idempotent compensation
     on reply success: WRITE step K -> COMPENSATED; move to K-1
     on transient failure: retry with backoff (same C_K)
     on repeated failure: see "compensation that won't succeed" below
  when all SUCCEEDED steps are COMPENSATED: WRITE status = compensated (terminal)
  • Strict reverse order, driven from central state. Because the orchestrator holds the full ordered step log, it compensates step N-1, then N-2, …, down to 0, and it knows when it is done. The failing forward step itself is skipped (its local transaction never committed, so there is nothing to undo). This ordered completeness is exactly what Approach A and choreography cannot guarantee.
  • Compensations are idempotent and write-ahead logged, identical to forward steps. A crash mid-compensation recovers by re-sending the in-flight COMPENSATING step with the same key - void_charge called twice voids once. Recovery (part 2) resumes compensation from the current backward position; it never restarts rollback from the top or skips a step.
  • Compensation is semantic, not physical - model it that way. You do not un-charge a card; you refund it (a new ledger entry). You do not un-reserve by deleting history; you release the reservation (which may itself emit an event). Design each undo() as a real forward operation in its service that semantically negates the do(), and accept that it leaves a trace (a refund line, a cancellation record). This is fine and often required for audit.

The compensation that will not succeed

The ugly case the interviewer is waiting for: a compensation keeps failing (the payment gateway is down, or worse, the step is not compensable - you already shipped the physical package). Options, and you must pick and state one:

  • Retry with backoff indefinitely for transient failures, because the compensation must eventually run to make the saga atomic - a refund that is down now will come back. Keep the saga in compensating and keep trying.
  • After a bound, escalate to a dead-letter / manual-intervention queue. A compensation that fails N times (or a step known to be non-compensable at this stage) parks the saga in a compensation_stuck state and alerts an operator. Atomicity is now a human-assisted guarantee, not an automatic one - which is honest, because some real-world actions cannot be programmatically reversed.
  • Design to avoid non-compensable steps late in the saga. Order the saga so that irreversible or hard-to-reverse steps come last (ship the package only after inventory, payment, and fraud checks all succeeded), so that by the time you do the thing you cannot undo, everything that could fail already has not. A pivot step: once past it, the saga is designed to only go forward (retry-to-completion), never compensate. Many real sagas have a point of no return, and you place it deliberately.

Compensation is the forward path mirrored - reverse order, write-ahead logged, idempotent, retried - and the real engineering is ordering irreversible steps last and having an explicit escalation path for a rollback that cannot complete on its own.

4. Idempotency and the “Did It Actually Run?” Ambiguity

Every forward step and every compensation can be invoked more than once (recovery re-sends an ATTEMPTING step; a retry fires after a timeout where the work may have succeeded but the reply was lost). Duplicates must be harmless.

Approach A: Assume each call runs exactly once (naive)

Send the command once, trust the reply. If no reply, re-send.

Where it breaks: the classic ambiguity - the orchestrator sends charge_payment, the payment service charges the card successfully, and the reply is lost (network drop, orchestrator crash before reading it). The orchestrator cannot distinguish “charged, reply lost” from “never charged.” If it re-sends naively, the card is charged twice. If it gives up and compensates, but the charge actually went through, it must refund - but it does not even know there is a charge to refund. Non-idempotent calls make the unavoidable at-least-once reality corrupting.

Approach B: Idempotency keys end to end, with a participant-side dedup ledger

Every command the orchestrator sends carries a stable idempotency key, minted once at the ATTEMPTING (or COMPENSATING) write and reused on every retry/recovery of that same step:

forward step N key:       saga_id + ":" + step_index + ":do"
compensation for step N:  saga_id + ":" + step_index + ":undo"

Each participant service keeps a small dedup ledger: when it processes command with key K, it records processed(K) -> result in the same local transaction as the business change. On a redelivered K, it skips the business logic and returns the stored result. Now:

  • “Charged, reply lost” is safe. The orchestrator re-sends the same key; the payment service sees K already processed and returns the original result (the charge id) without charging again. The orchestrator learns the true outcome and proceeds. The ambiguity is resolved not by guessing but by the participant being authoritative on “did K run.”
  • Recovery is safe. Re-sending an ATTEMPTING step with its original key either completes it (if it had not run) or returns the prior result (if it had). Either way the orchestrator converges.
  • The dedup record and the business write are atomic together. If a service wrote the business change but crashed before recording the key, a retry would double-apply. Putting processed(K) in the same local transaction as the effect closes that gap - the service either did both or neither.
  • Querying by key as an alternative/complement. For services that expose it, the orchestrator can query “what happened with K?” during recovery instead of blindly re-sending - useful for steps where even a deduplicated re-send is undesirable. Either way, the key is the correlation handle.

The honest limit

If a participant does not support idempotency keys or a dedup ledger (a crude third-party API), the orchestrator cannot make that call exactly-once alone. Mitigations: wrap the call in your own dedup proxy (a small service that records “key K -> external call made, result R” in its own store before/after calling the third party, check-then-act), or accept at-most-once for that specific step and compensate conservatively. State it plainly: at-least-once delivery plus idempotent participants gives effectively-once; a non-idempotent participant forces either a dedup wrapper you build or a weaker guarantee you declare.

Idempotency keys carried end to end, deduplicated in the same local transaction as the business change, turn the unavoidable “did it run?” ambiguity from a double-charge bug into a safe no-op - and they are the precondition that makes crash recovery and retries correct rather than corrupting.

API Design & Data Schema

Saga management API (control plane)

POST /sagas                                  # start a saga
  { "type": "order_fulfillment",
    "input": { "order_id": "...", "items": [...], "amount": 4999, "address": {...} },
    "idempotency_key": "checkout-7f3a" }       # client-supplied; dedups double-submits
  -> 201 { "saga_id": "saga_9f2a", "status": "started" }
  (a retry with the same idempotency_key returns the SAME saga_id, not a new saga)

GET    /sagas/{id}            -> { status, direction, current_step, steps:[...], outcome }
GET    /sagas/{id}/steps      -> full step log (state, attempts, timestamps, results)
POST   /sagas/{id}/cancel     -> request compensation of an in-flight saga (if past a
                                  pivot/point-of-no-return, rejected or forced-forward)
POST   /sagas/{id}/retry      -> operator: re-drive a compensation_stuck saga
GET    /sagas?status=compensation_stuck   -> operators find stuck sagas to fix

Participant service contract (data plane, over the durable bus)

Every service that participates exposes two idempotent operations and dedups on the key:

COMMAND  do(step):   { saga_id, step_index, idempotency_key, request }
   -> runs local transaction (idempotent on idempotency_key), replies:
      { status: "succeeded"|"failed", retriable: bool, result: {...} }

COMMAND  undo(step): { saga_id, step_index, compensation_key, original_result }
   -> runs compensating local transaction (idempotent on compensation_key), replies:
      { status: "succeeded"|"failed", retriable: bool }

   # participant keeps:  processed(key) -> result   (written in the SAME local txn)

Data model: the saga store

The store needs strong single-saga consistency (transition CAS must not race), point lookup by saga_id, a scan of non-terminal sagas per partition (for recovery and for finding timed-out sagas), and horizontal sharding by saga_id.

sagas (one row per saga - the current-state record):

saga_id           STRING   PRIMARY KEY
partition         INT      # hash(saga_id) % numPartitions; owned by one orchestrator
type              STRING   # order_fulfillment, etc. -> looks up the step definition
status            ENUM     # started|running|compensating|completed|compensated|
                           #   failed|compensation_stuck
direction         ENUM     # forward | backward
current_step      INT
client_idem_key   STRING   UNIQUE   # dedups POST /sagas retries
input             JSON
version           BIGINT   # optimistic concurrency / fencing on every transition
owner_epoch       BIGINT   # fencing token from the partition grant
deadline          TIMESTAMP  # overall saga timeout (nullable for long-runners)
created_at, updated_at TIMESTAMP

INDEX idx_partition_status (partition, status)   # recovery scan: open sagas per partition
INDEX idx_deadline (deadline)                     # find sagas that timed out
UNIQUE (client_idem_key)

saga_steps (one row per step per saga - the write-ahead log):

saga_id           STRING   # part of PK, co-located with the saga (same partition)
step_index        INT      # (saga_id, step_index) PRIMARY KEY
name              STRING   # reserve_inventory | charge_payment | create_shipment ...
state             ENUM     # pending|attempting|succeeded|failed|
                           #   compensating|compensated
idempotency_key   STRING   # forward key for this step
compensation_key  STRING   # undo key for this step
attempt           INT
request           JSON
result            JSON     # participant's returned result (reservation id, charge id)
error             TEXT
updated_at        TIMESTAMP

PRIMARY KEY (saga_id, step_index)   # step log reads/writes are single-partition

Participant-side dedup ledger (in each service’s own DB, not ours):

idempotency_key   STRING   PRIMARY KEY
result            JSON      # the outcome to replay on a duplicate
created_at        TIMESTAMP # TTL'd once the saga's redelivery window is safely past
# written in the SAME local transaction as the business change

Coordination / timer state (in the Raft quorum and timer service):

partition_assignment: partition_id -> { owner_node, epoch, lease_until }
timers:               saga_id -> fire_at   # step timeout or scheduled resume

SQL vs NoSQL - the choice and why. The saga store wants strong consistency on a single saga (the transition CAS, UPDATE ... WHERE version=?), co-location of a saga and its steps (all a saga’s writes are one logical unit, ideally one partition), and horizontal sharding by saga_id. The access pattern is almost entirely single-partition (one saga at a time), with only the recovery/timeout scans crossing rows within a partition. That is a great fit for a sharded relational store (Postgres/MySQL sharded by partition, or NewSQL like CockroachDB/Spanner) or a strongly-consistent key-value/wide-column store (DynamoDB with saga_id as partition key and step_index as sort key, giving a single-partition transaction over the saga and its steps; the conditional write gives the CAS). The deciding factor is the conditional/transactional write - you must have a real UPDATE ... WHERE version=? or a conditional expression to make transitions race-free. An eventually-consistent store with no conditional write is the wrong pick for saga state. Because each saga is self-contained in one partition, you do not need cross-partition transactions, which is why this scales horizontally cleanly - unlike 2PC, there is no distributed commit in our own store either. The participant dedup ledgers live in each service’s own database (co-located with its business tables, so processed(K) and the effect share one local transaction).

Bottlenecks & Scaling

Where it breaks first, in order, and the fix for each:

1. In-memory saga state loses everything on a crash. The foundational failure: progress on a stack dies with the process, stranding half-applied transactions. Fix: the durable write-ahead saga log - record ATTEMPTING before the side effect, the outcome after, every transition a replicated write. Recovery replays from the last durable state. This is the design’s reason to exist.

2. Saga store write throughput (2+ writes per step). At ~20K steps/sec, ~40K+ transition writes/sec, the store is the orchestrator’s own bottleneck. Fix: shard by saga_id so writes spread across partitions; keep each saga’s writes single-partition (fast, no distributed txn); batch the ATTEMPTING+send where safe; use an append-friendly store for the step log. Writes scale with partition count.

3. A saga is driven by two orchestrators at once (failover overlap). Availability needs multiple nodes; a reassigned partition can briefly have two claimants. Fix: partition ownership via the coordination quorum (one owner per partition) + fencing epoch on the grant (stale-epoch writes rejected) + version CAS on every transition (only one write wins). Ownership for efficiency, fencing + CAS for correctness.

4. Double-charge on retry / recovery (the “did it run?” ambiguity). At-least-once re-sends a step whose reply was lost. Fix: end-to-end idempotency keys minted at the ATTEMPTING write, reused on every retry, with a participant dedup ledger written in the same local transaction as the business change. A duplicate returns the stored result; nothing double-applies.

5. Compensation in the wrong order or lost. Best-effort, unordered rollback leaves inconsistent state or leaked reservations. Fix: strict reverse-order compensation driven from the central step log, each undo() write-ahead logged, idempotent, and retried - identical durability to the forward path. Recovery resumes compensation from the current backward position.

6. A compensation that will not complete. Gateway down, or a non-compensable step (already shipped). Fix: retry transient failures with backoff (the refund will come back); after a bound, park in compensation_stuck and alert for manual intervention; order irreversible steps last behind a pivot/point-of-no-return so the saga only goes forward past the thing it cannot undo.

7. A step never replies (lost command or hung service). The saga would wait forever. Fix: a timer/timeout service arms a deadline when a step is sent; on expiry it wakes the owning node to retry (same idempotency key) or, after a bound, declare the step failed and compensate. Overall-saga deadline catches a saga stuck anywhere.

8. Long-running sagas pile up as open state. Pre-orders and manual approvals stay open for hours/days. Fix: do not hold a thread per saga - drive sagas as async state machines so a waiting saga is a row + a timer, not a blocked worker. Open sagas cost storage and a timer, not compute; the orchestrator fleet sizes to active transition rate, not open-saga count.

9. Hot partition. One partition’s sagas disproportionately active (a flash sale on a few SKUs). Fix: enough partitions that any one is a small slice; hash by saga_id (not by SKU or customer, which skew) so load spreads; split a persistently hot partition and reassign. Service-level contention on a hot SKU is the inventory service’s concurrency problem, not ours.

10. Coordination service as a single point of failure. If partition assignment dies, no failover. Fix: run coordination as a replicated Raft quorum (3 or 5 nodes) tolerating a minority failure; keep its state tiny (partition assignments, epochs, liveness). Orchestrators cache their current assignment so a brief coordinator blip does not stall in-flight sagas.

11. No isolation - dirty intermediate reads. Another transaction sees inventory reserved for an order that later compensates, or reads a balance mid-saga. Fix: this is inherent to sagas (atomicity without isolation); bound it with semantic locks (mark a reserved item pending so other sagas treat it as unavailable until the saga resolves), commutative updates (increment/decrement balances rather than set, so order of visibility matters less), and re-read / re-validate at the pivot step. State clearly that sagas trade isolation for availability and you manage the anomalies, not eliminate them.

12. Run-history / completed-saga storage growth. 10M sagas/day of step logs. Fix: keep active + recently completed sagas hot (days to weeks for debugging), roll terminal sagas to cold storage, and TTL participant dedup-ledger entries once the redelivery window for that saga has safely passed (the key only needs to outlive possible retries/recovery).

Wrap-Up

The trade-offs that define this design:

  • Orchestration over 2PC and over choreography. We give up 2PC’s cross-service atomic commit (and its blocking locks and in-doubt freeze) and choreography’s loose coupling, in exchange for a central state machine that owns step order, durable state, and - decisively - correct, complete, reverse-order compensation. No distributed locks, no coordinator freeze, because each step is a local transaction and all state is externalized.
  • The saga is persisted state, not a call stack. Every transition is written to a durable, replicated store before the side effect (write-ahead) and confirmed after, so crash recovery is just “load the last durable state and decide the next move.” This single property is what makes the orchestrator resumable, and it is the difference between a real saga system and a try/catch.
  • Atomicity without isolation, honestly. We guarantee all-steps-or-all-compensated and durability, but intermediate states are visible; we manage the resulting anomalies with semantic locks and commutative updates rather than pretending a saga is serializable.
  • At-least-once plus idempotency, because exactly-once is impossible. Lost replies and recovery re-sends mean a step can be invoked twice; end-to-end idempotency keys with a participant dedup ledger (written in the same local transaction as the effect) make the duplicate a safe no-op and resolve the “did it run?” ambiguity authoritatively.
  • Compensation is semantic, ordered, and sometimes manual. Undo is a real forward operation that negates its step, run in strict reverse order with full write-ahead durability; irreversible steps are ordered last behind a pivot, and a rollback that cannot complete escalates to a human rather than silently corrupting - an honest guarantee, not a fake one.

One-line summary: a durable, sharded, write-ahead saga store that holds each long-running transaction as a persisted state machine; an orchestrator tier that partitions saga ownership (fencing-guarded, version-CAS’d) and drives steps forward or - on failure - compensates in strict reverse order; end-to-end idempotency keys with participant dedup ledgers that make an inherently at-least-once path effectively-once; and a recovery algorithm that resumes any saga from its last durable transition after any crash, so every started transaction reaches a terminal state of completed or fully compensated.