06. Architecture / Lesson 3 of 4

Sagas & Distributed Transactions

How to keep one business action correct when it spans several services and databases.

  • 12 min
  • Advanced
  • 10 steps
  • Locks held—
  • Steps done0 of 3
  • OrderPending (warning)

Order #7

1. reserve stock

2. charge $40

3. create shipment

✗ one transaction? no

OrdersInventoryPaymentsShipping
  • Request
  • Response
  • Health check
  • Write
  • Failed request
Step 1/10

Step 1 of 10: One order, three services, three databases

Read every step as text
  1. Step 1: One order, three services, three databases

    Placing an order of 1 item for $40 means three steps: reserve the stock (inventory), charge the card (payments) and create the shipment (shipping). Each service owns its own database.

    In one database you would wrap the three changes in a single transaction: all happen or none. Across three databases there is no such wrapper, and a failure half-way leaves a mess: money taken but nothing shipped.

    This is the price of a database per service: you give up the single transaction.

  2. Step 2: Two-phase commit: ask everyone, then decide

    Two-phase commit (2PC) uses a coordinator. In phase 1 it asks every service to prepare: do the work, hold the locks and vote yes or no. In phase 2, if all said yes, it tells everyone to commit; if any said no, everyone rolls back.

    It gives true all-or-nothing. Each service holds its locks from its vote until the answer: 20 ms of work + a 5 ms round trip to vote + a 5 ms round trip to commit = 30 ms.

    Phase 1: prepare and vote. Phase 2: commit or abort. Nobody commits until everybody has said yes.

  3. Step 3: When the coordinator dies, everyone waits

    Suppose the coordinator crashes after the yes votes but before it says commit. Each service has promised to commit if told to, so it cannot decide alone: it holds its locks and waits.

    Until the coordinator is back, say 5 minutes, the rows for order #7 are locked in all three databases and other orders that need them are stuck. 2PC is also slow, needs every service up, and many cloud databases and message systems do not support it at all.

    2PC trades availability for strict consistency. It is used inside some databases, rarely across microservices.

  4. Step 4: A saga: a chain of small local transactions

    A saga drops the global lock. Each step is an ordinary local transaction that commits at once: reserve the stock, then charge the card, then create the shipment. Locks last only 20 ms per step and no step waits for another service.

    The price: while the saga runs, other users can see the in-between state (stock reserved, card not yet charged). A saga is atomic eventually, not isolated.

    A saga gives up isolation to keep availability. The business rule must be fine with the in-between states.

  5. Step 5: If a step fails, run the undo steps backwards

    Say the shipment fails: the address is invalid. Stock is reserved and $40 is taken, and both already committed, so they cannot be rolled back. Instead each step has a compensation, a new action that cancels its effect: refund $40, then release the stock.

    Compensations run in reverse order and must be safe to retry. Some things cannot be undone (an email already sent), so the order of steps matters: put steps that are hard to undo last.

    A compensation is a business action, such as a refund, not a database rollback. Design it for every step.

  6. Step 6: Choreography: services react to each other's events

    In choreography there is no boss. Orders publishes OrderCreated; inventory hears it, reserves the stock and publishes StockReserved; payments hears that and charges the card; and so on. Failure events trigger the compensations the same way.

    It is loosely coupled and has no central part to fail. But the flow lives in many places, so with five or six steps nobody can see the whole process and cyclic dependencies creep in.

    Choreography suits short sagas of 2 to 4 steps with clear events.

  7. Step 7: Orchestration: one service runs the steps

    In orchestration an orchestrator holds the saga's steps. It tells inventory to reserve, waits, tells payments to charge, and so on, saving its state after every step. On a failure it sends the compensations itself.

    The whole process is in one place: easy to read, monitor and change. The cost is a central component that must be reliable (its state lives in a database) and that knows about every service.

    Orchestration is easier to follow as sagas grow; workflow engines (Temporal, AWS Step Functions) provide it ready-made.

  8. Step 8: Outbox: never lose the event

    A service must change its database and publish an event. Doing both separately is dangerous: if it crashes between them, the order exists but nobody hears about it.

    The outbox pattern writes the order row and an event row into an outbox table in the same local transaction. A separate relay reads new outbox rows and publishes them, then marks them sent. If the relay dies, it resumes later, so the event is published at least once.

    One database transaction can hold both the data and the event. The relay turns the event into a message.

  9. Step 9: Messages can repeat, so every step must be safe to repeat

    The relay and the broker deliver at least once, so payments may get ChargeCard for order #7 twice. Without care the customer pays $80 instead of $40.

    Make each step idempotent: the message carries a unique key such as order-7-charge. Payments saves the keys it has seen and, on a repeat, returns the first result without charging again. Compensations get keys too.

    At-least-once delivery plus idempotent steps behaves like exactly once.

  10. Step 10: Sagas in one picture

    Across services there is no single transaction. Two-phase commit gives all-or-nothing but blocks (locks for 5 min if the coordinator dies). A saga commits each local step at once, in 20 ms, and undoes failures with compensations.

    Choreography uses events, orchestration uses a central runner. The outbox makes the event reliable, and idempotent steps make repeats harmless.