Distributed Transactions: 2PC and Sagas

Keep data consistent across services and databases with two-phase commit or sagas with compensating actions, and know when each is appropriate.

Advanced · about 4 hours · difficulty 4/5

Learn first: Delivery Guarantees and Event-Driven Design, Consistency Models, CAP and PACELC

A single database gives you ACID transactions. Once an order touches the order service, inventory service and payment service, each with its own database, you need another approach.

Two-phase commit (2PC)

  • A coordinator asks every participant to prepare (lock resources and promise to commit).
  • If all vote yes, it tells them to commit; otherwise abort.
  • Gives atomicity across databases, but it is blocking: if the coordinator dies after prepare, participants hold locks until it recovers. It also adds latency and couples availability of all participants. Common inside databases (XA, Spanner style systems), rare across microservices.

Sagas

A saga splits the business transaction into a sequence of local transactions, each with a compensating action that semantically undoes it:

  1. Create order (compensate: cancel order)
  2. Reserve inventory (compensate: release inventory)
  3. Charge payment (compensate: refund)
  4. Confirm order

If step 3 fails, run compensations for steps 2 and 1. There is no global isolation, so other requests may briefly see intermediate states ("payment pending").

Coordinating a saga

  • Choreography: each service listens for events and emits the next. Fine for 2 or 3 steps.
  • Orchestration: a saga orchestrator (or a workflow engine like Temporal) drives the steps and tracks state. Easier to reason about, retry and monitor.

Design rules

  • Every step and every compensation must be idempotent and retryable.
  • Some actions cannot be undone (an SMS was sent). Order steps so irreversible ones come last.
  • Use the outbox pattern so each step's state change and event are atomic.

Pitfalls

  • Using 2PC across services owned by different teams.
  • Forgetting compensations can fail too and need retries and alerting.

You are ready to move on when you can write the saga for booking a flight plus hotel, including compensations and what the user sees when the hotel step fails.

Key concepts

  • Two-phase commit
  • Blocking and coordinator failure
  • Sagas and compensating actions
  • Choreography vs orchestration sagas
  • Workflow engines (Temporal)
  • Semantic locks and pending states

Mini project

Build an orchestrated saga for a food order across three toy services (order, restaurant, payment) with compensations. Inject a payment failure and a restaurant timeout and show the final states in each service's database.

Check yourself

Why do sagas give up isolation, and how can you stop a user from seeing or acting on a half-finished order?

Free resources