TExcelTAD
Home › System Design › Distributed Transactions

Distributed Transactions

A database transaction makes several changes atomic: all happen or none do. That's easy inside one database. But when a checkout must reserve stock in the inventory service, charge the card in the payment service and create a shipment in the shipping service, each with its own database, there is no single transaction to wrap around them. Two families of solutions exist: two-phase commit (atomic, blocking) and sagas (eventually consistent, with compensations).

Two-phase commit (2PC)

A coordinator asks every participant to get ready, then tells all of them the outcome.

text
Phase 1 (prepare / vote)              Phase 2 (commit or abort)
coordinator --prepare--> inventory     coordinator --commit--> inventory
            --prepare--> payment                   --commit--> payment
            --prepare--> shipping                  --commit--> shipping
each participant: lock rows, write     all voted YES -> commit everywhere
a durable "prepared" record, vote      any NO / timeout -> abort everywhere

Once a participant votes YES it must be able to commit later, even after a crash, so it keeps its locks until it hears the decision.

python · try it yourself
class Participant:
    def __init__(self, name, can_commit=True):
        self.name, self.can_commit, self.state = name, can_commit, "idle"

    def prepare(self):
        self.state = "prepared" if self.can_commit else "aborted"
        return self.can_commit

    def finish(self, decision):
        if self.state == "prepared":
            self.state = "committed" if decision == "commit" else "rolled back"

def two_phase_commit(participants):
    votes = {p.name: p.prepare() for p in participants}       # phase 1
    decision = "commit" if all(votes.values()) else "abort"
    for p in participants:                                      # phase 2
        p.finish(decision)
    return votes, decision

for payment_ok in [True, False]:
    ps = [Participant("inventory"), Participant("payment", payment_ok), Participant("shipping")]
    votes, decision = two_phase_commit(ps)
    print(f"votes {votes} -> {decision.upper()}")
    print("   final states:", {p.name: p.state for p in ps})
votes {'inventory': True, 'payment': True, 'shipping': True} -> COMMIT
   final states: {'inventory': 'committed', 'payment': 'committed', 'shipping': 'committed'}
votes {'inventory': True, 'payment': False, 'shipping': True} -> ABORT
   final states: {'inventory': 'rolled back', 'payment': 'aborted', 'shipping': 'rolled back'}

The blocking problem

2PC's weak point is the coordinator. If it crashes after the participants voted YES but before it sent the decision, they are stuck: they can't commit (maybe someone voted NO) and can't abort (maybe the coordinator already told someone to commit). They hold their locks until the coordinator comes back.

python · try it yourself
def timeline(coordinator_crash_at, recovery_after):
    events, locked_since = [], None
    for step in range(10):
        if step == 1:
            events.append(f"{step}: all participants prepared, rows locked")
            locked_since = step
        if step == coordinator_crash_at:
            events.append(f"{step}: coordinator crashes before sending decision")
        if step == coordinator_crash_at + recovery_after:
            events.append(f"{step}: coordinator recovers, reads its log, sends COMMIT")
            events.append(f"   rows were locked for {step - locked_since} steps")
            break
    return events

for line in timeline(coordinator_crash_at=2, recovery_after=6):
    print(line)
1: all participants prepared, rows locked
2: coordinator crashes before sending decision
8: coordinator recovers, reads its log, sends COMMIT
   rows were locked for 7 steps

Real implementations (XA transactions, database-internal 2PC in Spanner or CockroachDB) make the coordinator itself highly available by replicating its decision log with consensus. Across independent services, 2PC is rarely used: it couples everyone's availability and holds locks across network calls.

Sagas

A saga splits the business transaction into a sequence of local transactions, one per service. Each step commits immediately. If a later step fails, the saga runs compensating actions for the steps already done, in reverse order: release the stock, refund the payment.

python · try it yourself
log = []

def step(name, action, compensation, fail=False):
    return {"name": name, "action": action, "compensation": compensation, "fail": fail}

def run_saga(steps):
    done = []
    for s in steps:
        if s["fail"]:
            log.append(f"FAIL  {s['name']}: {s['action']}")
            for d in reversed(done):                     # compensate in reverse order
                log.append(f"UNDO  {d['name']}: {d['compensation']}")
            return "saga aborted, compensated"
        log.append(f"OK    {s['name']}: {s['action']}")
        done.append(s)
    return "saga completed"

checkout = [
    step("inventory", "reserve 2 x lamp", "release 2 x lamp"),
    step("payment", "charge 80.00", "refund 80.00"),
    step("shipping", "book courier", "cancel courier", fail=True),   # no courier available
]
print(run_saga(checkout))
for line in log:
    print(" ", line)
saga aborted, compensated
  OK    inventory: reserve 2 x lamp
  OK    payment: charge 80.00
  FAIL  shipping: book courier
  UNDO  payment: refund 80.00
  UNDO  inventory: release 2 x lamp

Sagas never hold locks across services, so they scale and stay available. The price is no isolation: between "charge" and "refund", other parts of the system can see the intermediate state (a charged order without a shipment). Designs mitigate this with semantic locks (an order status of PENDING), by putting the riskiest, most likely to fail step first, and by making compensations idempotent so they can be retried.

Orchestration vs choreography

Orchestration Choreography
Who drives the saga A central orchestrator (a workflow engine such as Temporal, AWS Step Functions, Camunda) Each service reacts to the previous service's event
Visibility One place shows the saga's state The flow is spread over many services
Coupling Orchestrator knows all steps Services only know events
Good for Long, complex flows with many branches Short flows with few steps
python · try it yourself
# Choreography: each service listens for an event and emits the next one
handlers = {
    "OrderCreated":      ("inventory", "StockReserved"),
    "StockReserved":     ("payment", "PaymentFailed"),        # the card is declined
    "PaymentFailed":     ("inventory", "StockReleased"),      # compensation
    "StockReleased":     ("orders", "OrderCancelled"),
}

event = "OrderCreated"
while event in handlers:
    service, next_event = handlers[event]
    print(f"{event:<14} -> handled by {service:<9} -> emits {next_event}")
    event = next_event
print("final event:", event)
OrderCreated   -> handled by inventory -> emits StockReserved
StockReserved  -> handled by payment   -> emits PaymentFailed
PaymentFailed  -> handled by inventory -> emits StockReleased
StockReleased  -> handled by orders    -> emits OrderCancelled
final event: OrderCancelled

Choosing

  • Inside one database: use its transactions. Design service boundaries so most transactions stay local.
  • Inside one distributed database (Spanner, CockroachDB): it does 2PC + consensus for you.
  • Across services: sagas, with an orchestrator for anything beyond three or four steps, plus the outbox pattern so each local commit reliably emits its event.

Tip: Some steps can't be compensated (an email was sent, a parcel left the warehouse). Put those last, after every step that might still fail.

Test yourself

In 2PC, when does the coordinator decide to commit?

  1. When at least one participant votes YES
  2. When all participants vote YES in the prepare phase
  3. Immediately, without voting
  4. When a majority votes YES

What is the main weakness of 2PC?

  1. It can't roll back
  2. Participants may block holding locks if the coordinator fails after they voted
  3. It only works with NoSQL
  4. It needs compensating actions

In the saga example, shipping failed. What happened next?

  1. Everything was retried forever
  2. Payment was refunded, then the stock was released (reverse order)
  3. Only shipping was rolled back
  4. The saga ignored the failure