SysDesignAtlas

Distributed Transactions & Sagas

Why 2PC blocks, how sagas trade atomicity for availability, designing compensating actions, and the honest answer — avoid needing one.

HLDHard10 min readtransactionssaga2pcconsistency
Confidence

#The problem

A single database gives you ACID across many rows for free. Split those rows across two databases — or two services — and atomicity disappears.

   Book a trip:
     1. Reserve flight     (flight service DB)
     2. Reserve hotel      (hotel service DB)
     3. Charge card        (payment service)

   Step 2 fails after step 1 succeeded.
   The flight is now reserved for a trip that doesn't exist.

You need all-or-nothing across systems that don't share a transaction manager. There are two real answers — two-phase commit and sagas — and one better one: redesign so you don't need a cross-system transaction at all.

#Two-phase commit (2PC)

A coordinator drives all participants to a unanimous decision.

   PHASE 1 — PREPARE
   coordinator ──"can you commit?"──► A, B, C
               ◄──── "yes" ─────────
        Each participant does the work, writes it durably,
        holds LOCKS, and promises it CAN commit if asked.

   PHASE 2 — COMMIT
   coordinator ──── "commit" ───────► A, B, C
               ◄──── "done" ────────
        Any "no" in phase 1 → coordinator sends "abort" instead.

The promise is the key: after voting yes, a participant must be able to commit, even across a crash. So it holds locks and keeps the transaction open until told what to do.

Why 2PC is largely avoided:

It blocks. If the coordinator crashes after participants vote yes but before sending the decision, participants are stuck — they cannot commit (maybe someone voted no) and cannot abort (maybe everyone voted yes). They hold locks and wait, potentially forever. This is the defining flaw.

Locks are held for the full round trip, across the network, across every participant. Any other transaction that wants the same rows has to wait until the whole two-phase exchange finishes. When many transactions touch the same popular rows, they queue behind each other and throughput collapses — and one slow participant stalls everyone.

Availability multiplies down. All participants must be up for the duration. Three services at 99.9% give the transaction 99.7% (0.999 × 0.999 × 0.999).

3PC adds a third phase to stop that blocking, at the cost of another round trip — and it's still unsafe when the network splits, so it's rarely used. The fix that actually works, used by systems like Spanner and CockroachDB: make the coordinator itself a small replicated cluster agreeing by consensus, so it cannot simply vanish mid-decision. A crashed machine no longer strands anyone, because its peers know what was decided. That's the fix that makes 2PC viable, and it's worth naming.

There is also an optimistic alternative to locking participants for the whole round trip: run the transaction against a snapshot without locks and check for conflicts only at commit, aborting the loser. Amazon Aurora DSQL takes this approach across Regions — see multi-region for how its commit path works.

#Sagas

A saga gives up on one big all-or-nothing transaction and instead runs a sequence of small local ones — each committed for real, immediately — where every step has a matching compensating action that undoes its effect if a later step fails.

A compensation undoes the step's meaning, not its data. You can't roll back a committed transaction, so compensation is a new action with the opposite meaning. You don't un-charge a card; you issue a refund, and both appear in the history.

   T1 reserve flight   →  C1 cancel flight
   T2 reserve hotel    →  C2 cancel hotel
   T3 charge card      →  C3 refund card

   Forward:  T1 → T2 → T3 ✓
   T3 fails: T1 → T2 → ✗ → C2 → C1   (compensate backwards)

Each step commits immediately and locally — no distributed locks, no blocking, and each service stays independently available.

What you give up, and you must say this: atomicity and isolation. There is a window where the flight is booked and the hotel isn't. Other transactions can see that intermediate state. A saga is eventually consistent, not atomic.

#Orchestration vs choreography

Orchestration — a coordinator explicitly invokes each step and handles failures.

   ┌──────────────┐
   │ Saga         │──1──► Flight service
   │ orchestrator │──2──► Hotel service
   │ (state       │──3──► Payment service
   │  machine)    │
   └──────────────┘  on failure, invokes compensations in reverse

The process is visible in one place, debuggable, and easy to monitor — you can always answer "what state is this booking in?" Cost: a component that knows about everyone.

Choreography — each service listens for events and reacts, emitting its own.

For example, the flight service publishes FlightReserved, the hotel service hears it and reserves a room, then publishes HotelReserved, which the payment service hears, and so on. No service needs to know about the others — that's the appeal. The cost is that the overall business process isn't written down anywhere. To understand it you have to read every service's event handlers. And loops nobody designed can appear: A's event triggers B, whose event triggers C, whose event triggers A again.

Recommend orchestration for anything with more than ~3 steps or real money involved. Being able to see every booking's progress in one place alone justifies it. Choreography is fine for simple cases where one event triggers a few independent reactions — say, "user signed up" causing a welcome email and an analytics update.

#Designing compensations

This is the real engineering, and the part usually left thin.

  • Compensation is semantic, not a rollback. You can't un-send an email; you send an apology. You can't un-charge a card; you issue a refund, which is a new transaction that appears on the statement. The customer sees both.
  • Compensations must be idempotent. They'll be retried. See Idempotency.
  • Compensations can fail too. Retry with backoff, and after N attempts escalate to a human via an alert and a dead-letter store. A saga stuck half-complete with no human path is an outage waiting to be discovered by a customer.
  • Some steps can't be compensated. Order the saga so irreversible steps come last, after everything reversible has succeeded. Charge the card after inventory is confirmed, not before.
  • Pivot transactions. The step after which the saga can no longer be aborted, only completed forward. In an online shop, that's often "charge the card": before it, any failure means undo; after it, any failure means keep retrying until the goods ship. Identifying it explicitly clarifies the whole design.

Forward recovery is the alternative to backward compensation: instead of undoing, keep retrying until the step succeeds. Right when the operation must eventually complete (the payment has been taken; the goods must ship).

#Avoiding the problem

The strongest answer is usually to not need a distributed transaction at all. Volunteer these before designing a saga:

1. Fix the boundaries. A transaction spanning services often means the service boundary is drawn in the wrong place. If order and inventory must always change together, maybe they belong to one service with one database. In other words: data that must change together should live together. Draw service and database boundaries around what has to be updated atomically — this is the single most valuable observation in this whole topic.

2. Choose a partition key that keeps the transaction local. Sharding by customer_id keeps everything about one customer's order on one shard, so it's an ordinary local transaction. Most "distributed transaction" problems are sharding key problems in disguise.

3. Use the outbox pattern. For "update the database and publish an event," you don't need 2PC. In one local transaction, update your table and insert the event into an "outbox" table in the same database. A separate background process (the relay) then reads the outbox and publishes each event to the queue, retrying until it succeeds. See CDC & Outbox.

4. Reserve-then-confirm. Model the intermediate state explicitly in the domain instead of hiding it:

   1. Reserve inventory with a TTL (status = reserved, expires_at)
   2. Take payment
   3. Confirm the reservation (status = committed)

   If step 2 fails or times out, the reservation simply EXPIRES.
   No compensation needed — the TTL is the compensation.

This is how ticket booking and hotel reservations actually work, and it's elegant: expiry handles the failure path automatically, with no coordinator and no compensating transaction to get wrong.

5. Accept eventual consistency and reconcile. Let the steps happen independently and run a periodic job that finds and fixes mismatches. Every large financial system does this regardless of its other mechanisms — reconciliation is the safety net that catches everything the design missed.

#Choosing

SituationApproach
Rows in one databasePlain ACID transaction
Shards of one cluster with a replicated coordinator2PC over consensus
Across independent services, reversible stepsSaga (orchestrated)
Update + publish an eventOutbox
Reserving limited inventoryReserve-with-TTL, then confirm
Steps that must eventually completeSaga with forward recovery
Anything financialAll of the above plus reconciliation

#Check yourself

How does two-phase commit work?Show answer
Phase 1: the coordinator asks every participant to prepare — do the work, hold locks and promise it can commit. Phase 2: if all said yes, it sends commit; any no means abort.
Why is 2PC largely avoided across services?Show answer
It blocks: if the coordinator dies after the votes, participants can neither commit nor abort and hold locks indefinitely. Locks span the whole round trip, and all participants must be up, so availability multiplies down.
What makes 2PC viable inside systems like Spanner and CockroachDB?Show answer
The coordinator is itself replicated by consensus, so it can't vanish mid-decision — and it all runs within one trust and latency domain.
What is a saga, and what does it give up?Show answer
A sequence of local transactions, each committed immediately, each with a compensating action that semantically undoes it. It gives up atomicity and isolation: other transactions can see the in-between state.
Orchestration or choreography for a saga with real money involved?Show answer
Orchestration: a coordinator drives the steps as a state machine, so you can always see each booking's state and run compensations in reverse. Choreography hides the process across services.
Name three rules for designing compensations.Show answer
Compensations are new semantic actions (a refund, not an un-charge); they must be idempotent; they can fail too, so retry then escalate to a human; and irreversible steps go last.
How does reserve-with-TTL avoid compensation entirely?Show answer
Reserve inventory with an expiry, take payment, then confirm. If payment fails or times out, the reservation simply expires — the TTL is the compensation.
What should you check before designing any distributed transaction?Show answer
Whether you need one at all: maybe the service boundary is wrong, a better partition key keeps it local, or an outbox (database write plus event) is all that's needed. Add reconciliation for anything financial.

#What to carry forward

  • Splitting data across systems loses free atomicity; there are two real answers and one better one.
  • 2PC blocks on coordinator failure; it's viable only with a consensus-replicated coordinator in one domain.
  • Sagas trade atomicity and isolation for availability; orchestrate them and design idempotent, ordered compensations.
  • Reserve-with-TTL and the outbox remove the need for most coordination.
  • The best fix is usually redrawing boundaries or partition keys — and reconciliation is the safety net.
00:00
/ 10m