Distributed transactions and sagas

Why 2PC is avoided, choreography versus orchestration, compensating actions, and the saga that gets stuck halfway.

12 min read🔀 Distributed Data Patterns

Placing an order touches inventory, payment and the order record. In one database that is one transaction: all three or none. Split the three across services and there is no transaction any more — only three local ones, and every way the second can fail after the first committed. This lesson is about the two answers: the one that tries to keep the transaction (and why nobody wants it), and the one that gives it up deliberately.

Two-phase commit, and its cost

2PC keeps the atomic guarantee across databases with a coordinator: phase one asks every participant to prepare (do the work, hold the locks, promise you can commit), phase two tells them all to commit or all to abort. Java has had it for twenty-five years as XA and JTA, and application servers built their reputations on it.

The cost is in the word "hold". Between prepare and commit every participant keeps its locks, and if the coordinator dies in that window they keep them until it comes back — a prepared transaction is a lock that no timeout releases, because releasing it would break the promise. So the whole system's availability becomes the coordinator's, the slowest participant sets everyone's latency, and a participant that is not a database — a payment provider's HTTP API, a mail service — cannot prepare at all. That last point is the one that settles it for a service architecture: most of what you would want in the transaction cannot join one.

2PC is the right tool inside a single database's replication, and inside Kafka's own transactions, where the participants are built for it. Between services, it is the design that turns a payment provider's five-minute outage into your order table's five-minute lock.

A saga: local transactions, plus the way back

A saga replaces the one transaction with a sequence of local ones, each committed on its own, and for each a compensating action that undoes its effect if a later step fails:

plaintext
T1  reserve inventory          C1  release the reservation
T2  charge the card            C2  refund the charge
T3  create the order           C3  cancel the order

If T2 fails, run C1. If T3 fails, run C2 then C1. The guarantee is weaker than atomicity and it is the guarantee you actually get: every step completes, or every completed step is compensated. In between — after T2 and before T3 — the system is visibly inconsistent: the card is charged and there is no order. A saga does not hide that window; it bounds it and promises to resolve it.

Two consequences follow. Compensation is semantic, not a rollback: a refund is a new transaction the customer can see on their statement, not the absence of a charge, and some actions have no compensation at all (an email sent, a shipment dispatched) — those go last, after everything that can fail. And every step must be idempotent, because the saga will retry it after a crash and cannot know whether the previous attempt landed; the distributed-systems course's idempotency lesson is a prerequisite here, not a nice-to-have.

Choreography: the steps react to each other

Nobody coordinates. Inventory listens for OrderRequested, reserves, and publishes InventoryReserved; payment listens for that, charges, and publishes PaymentTaken; orders listens for that and creates the order. A failure publishes its own event — PaymentFailed — and inventory listens for that to release.

It is the observer pattern across services, and it has observer's costs at scale: no single place says what the saga is. The order of steps is the graph of who listens to whom, which lives in every service and in none, and the question "why is this order stuck" is answered by reading four codebases. Choreography is right for two or three steps that rarely change; at five steps with branches it is a state machine nobody drew.

Orchestration: one component runs the script

An orchestrator — a class, a workflow engine, a Spring state machine — holds the saga's definition and drives it: send the reserve command, wait for the reply, send the charge command, and on failure send the compensations in reverse order. The participants are simple (do this, reply); the orchestrator is the one place the sequence exists, which is where you want it.

java
class OrderSaga {
    void run(OrderRequest req) {
        var reservation = inventory.reserve(req.lines());              // step 1
        try {
            var payment = payments.charge(req.customer(), req.total()); // step 2
            try {
                orders.create(req, reservation, payment);              // step 3
            } catch (Exception e) { payments.refund(payment); throw e; }
        } catch (Exception e) { inventory.release(reservation); throw e; }
    }
}

That is the shape, and its flaw is the reason engines exist: if the orchestrator's process dies between step 2 and step 3, the try is gone and so is the knowledge that a refund is owed. A real orchestrator persists the saga's state after every step — a saga table with id, step, status, or Temporal, Camunda, or Axon doing that for you — so a restart picks up where the crash happened. Persisting the state is the whole difficulty; the sequencing is trivial.

The cost of orchestration is a component that knows about every participant and a temptation to put business rules in it; keep it a sequencer, and keep each step's rules in the service that owns them.

The saga that gets stuck

Every saga will eventually stop halfway: the payment provider times out, the refund fails because the charge is still pending, the orchestrator restarts and the reply was lost. Design for the stuck state before the first one happens:

  • Timeouts per step, and a saga-level deadline after which it is compensated or escalated, never left.
  • Retries with backoff on every step, which is only safe because every step is idempotent.
  • A status you can query — the persisted state above — and a dashboard or a query that lists sagas older than the deadline. The stuck saga that nobody can see is the one that becomes a support ticket a week later.
  • Compensation that can also fail, so a compensation is retried the same way, and a compensation that keeps failing is a human's job: an alert with the saga id, not a silent loop.
  • Semantic locks for the window: the reserved inventory is marked PENDING, not removed, so a reader can tell the difference between sold and in-flight.

The outbox lesson next is the mechanism that makes "publish an event in the same step as the local write" reliable, which every saga above quietly assumed.

Under the hood: orchestration as durable replay, and why compensation cannot be a rollback

What an orchestration engine actually persists. The OrderSaga snippet above says "a real orchestrator persists the saga's state after every step" and points at a saga table with id, step, status as the simple version. Engines built for this (Temporal and Camunda are the ones you will meet) generally do not implement that as a flat status column — they persist an append-only history of everything the workflow has done: each step started, each step's result, each timer fired. Recovering a crashed saga does not mean reading a status field and branching on it; it means re-executing the workflow function from the beginning, with the engine intercepting every call the code makes to a previously-completed step and returning the recorded result instead of running it again, so the code only actually executes past the point it reached before the crash. This is why workflow code written for these engines has to be deterministic — no direct Random, no direct wall-clock reads, no direct I/O outside the framework's own calls — because replay has to reproduce the identical sequence of decisions given the identical history, or the recovered saga silently diverges from the one that crashed. It is worth naming the resemblance directly: this is the event-sourcing fold from the CQRS lesson, applied to a workflow's control flow instead of an aggregate's fields — a durable log of what happened, replayed to reconstruct where things stand, rather than a mutable status flag.

Compensation is a new transaction, not an inverse of the old one — and there is a reason it has to be. A real rollback restores an exact prior state, which is only possible because a database transaction holds its changes uncommitted until the moment it decides. A saga's steps have already committed by the time a later step fails, so "undoing" T1 cannot mean making it as if T1 never ran — other transactions may have observed and acted on T1's committed effect in the meantime. What a saga's compensations do instead is closer to Garcia-Molina and Salem's original framing of sagas as long-lived transactions with compensating steps: a compensation is expressed as a new, independently forward-moving action on current state — release(3 units), not set inventory back to 47 — which is exactly what lets it compose correctly no matter what else happened to that row between T1's commit and the compensation running. A refund is a transaction your customer can see on their bank statement, dated after the charge, not the charge's disappearance; releasing a reservation puts stock back into the pool as of now, regardless of what else moved through that pool in between.

This also explains why some steps genuinely cannot be compensated, and why they belong last: an email sent, a shipment physically dispatched, a push notification delivered — there is no forward action that undoes "the customer already knows" or "the box already left the warehouse." Chris Richardson's classification of a saga's steps names this directly: a compensatable transaction can be undone by a later compensation; the pivot transaction is the point of no return — once it succeeds, the saga is committed to finishing forward, never compensated further back than that point; and retriable transactions, which come after the pivot, are ones the design guarantees will eventually succeed (because they are, themselves, either idempotent or have no failure mode worth compensating), so the saga never needs to compensate past the pivot at all. Placing the irreversible step at or after the pivot — never before it — is the actual design rule "actions with no compensation go last," stated one level more precisely.

Try it yourself

Place the irreversible step, using the pivot

A saga has four steps: reserve inventory (compensatable — release), charge the card (compensatable — refund), send a "your order is on its way" push notification (no compensation possible), create the order record (compensatable — cancel). Where does the notification step go, and which step is the pivot?

Work it through with the compensatable / pivot / retriable classification

The notification has no compensation, so by the rule above it must go last, after every step that can still fail and be undone. That leaves: reserve → charge → create order → notify. Reordering to put "create order" last (matching the business-readable order in the original list) would put a compensatable step after the uncompensatable one, which is exactly backwards — if the order-record creation failed after the notification already went out, there would be no way to undo the customer already knowing.

The pivot is whichever of the compensatable steps, once it succeeds, the saga commits to finishing regardless — here that's naturally "create order," the last step before the point of no return: once the order record exists, the saga is going to notify no matter what (there's nothing left to fail that would still be worth compensating the charge or the reservation for). Everything before "create order" is compensatable; "notify" is retriable in the sense that it is expected to essentially always succeed once reached, and if it doesn't, retrying the send is the answer, not unwinding the order.

Misconceptions

  • "A saga's compensating transaction undoes the original transaction, the way a database ROLLBACK does." A rollback discards uncommitted changes before anyone else could see them; a saga's steps have already committed and may already be observed elsewhere by the time a compensation runs. Compensation is a new, independently visible forward action — a refund, a release — expressed against current state, not a restoration of a prior snapshot.
  • "2PC and sagas give you the same consistency guarantee — a saga is just the distributed, more scalable version." They are different guarantees, not the same one at different costs. 2PC (when every participant can actually join it) keeps the system's visible state atomic — no other transaction sees a partial result. A saga explicitly does not: the window between a committed step and its eventual compensation or completion is externally visible by design, which is why every step and every compensation has to be idempotent and safe to observe mid-flight, a concern 2PC's participants never have to handle.

Sources

  • Chris Richardson, microservices.io — the Saga pattern, including the compensatable/pivot/retriable transaction classification.
  • Hector Garcia-Molina and Kenneth Salem, "Sagas" (1987) — the original paper introducing sagas as long-lived transactions with compensating steps.
  • Temporal documentation — workflow determinism and history-based replay (the mechanism orchestration engines built on this model use to recover from a crash).
Progress is saved on this device and to your account when signed in.