System Design · 06. Architecture · 12 min · Advanced

Sagas & Distributed Transactions

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

In short

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.

Key ideas

  • Phase 1: prepare and vote. Phase 2: commit or abort. Nobody commits until everybody has said yes. (step 2)
  • A saga gives up isolation to keep availability. The business rule must be fine with the in-between states. (step 4)
  • One database transaction can hold both the data and the event. The relay turns the event into a message. (step 8)
  • At-least-once delivery plus idempotent steps behaves like exactly once. (step 9)

Good to know

  • Choreography suits short sagas of 2 to 4 steps with clear events. (step 6)
  • Orchestration is easier to follow as sagas grow; workflow engines (Temporal, AWS Step Functions) provide it ready-made. (step 7)

Watch out

  • This is the price of a database per service: you give up the single transaction. (step 1)
  • 2PC trades availability for strict consistency. It is used inside some databases, rarely across microservices. (step 3)
  • A compensation is a business action, such as a refund, not a database rollback. Design it for every step. (step 5)
OrchestratorInventoryPaymentsShipping

Key numbers

Locks held
20 ms each
Steps done
3 of 3
Order
Confirmed

Terms

Distributed transaction
One business action that must change data in several databases or services.
Two-phase commit (2PC)
A coordinator asks every service to prepare and vote, then tells all to commit or abort.
2PC blocking
If the coordinator dies after the votes, services keep their locks and wait.
Saga
A chain of local transactions, each committed at once, with undo steps for failures.
Compensation
A new action that cancels the effect of an already committed step, such as a refund.
Choreography
Services trigger each other by publishing and reacting to events, with no central controller.
Orchestration
A central orchestrator runs the saga's steps and compensations and saves its state.
Outbox pattern
Write the data and the event in one local transaction, and let a relay publish the event.
Idempotent step
A step that can be repeated safely, because a unique key lets it recognise duplicates.