Concept Simulators / Copies and agreement

Distributed transactions

Two-phase commit against a saga when a service fails or says no.

On the roadmap:Advanced · step 4: Distributed systems

Intermediateabout 10 to 15 min6 experiments
Experiments
New here? A few short steps show what happens, one at a time.

Settings

How the services agree

What goes wrong

A coordinator runs a prepare phase, then a commit or abort phase. Locks are held between the two.

Result

Committed everywhere

Steps with locks held

6

Steps where others saw it half-done

0

All three agreed, so the transaction committed everywhere. The cost was 6 steps with locks held across services, and a round trip of messages before any of it counted.

Step 8 of 8

Shipping commits and releases its locks.

Payment

committed

no locks

Inventory

committed

no locks

Shipping

committed

no locks

The same failure, both ways

ApproachResultSteps with locks heldSeen half-done
Two-phase commitCommitted everywhere60
SagaCommitted everywhere02

In plain words

When one business action touches several services, each with its own database, no single database transaction covers it. Two-phase commit makes every service agree before any commits. A saga lets each commit straight away, and undoes earlier steps with compensating actions if a later one fails.

Why it matters

Both are ways to keep several services consistent without a shared database, and they fail very differently. Two-phase commit never shows a half-finished result, but it can block. A saga never blocks, but other users can see it half done, and its undo is a new action rather than a rollback.

How real systems do it

The simulation is a simplified model. Here is what production systems add or do.

  • Two-phase commit is part of the XA standard, and databases such as PostgreSQL and MySQL support prepared transactions. Google Spanner uses two-phase commit across its groups of replicas.
  • Because a prepared participant must wait for the coordinator, long outages leave locks held. Coordinators therefore keep their decision in durable storage, and are usually replicated.
  • The saga pattern goes back to a 1987 paper by Hector Garcia-Molina and Kenneth Salem. Workflow tools such as Temporal and AWS Step Functions run sagas by saving each step's progress.
  • Every saga step and compensation should be idempotent, because a message can be delivered twice. A compensation is a new business action, such as a refund, and may not be able to restore things exactly.

Study: Distributed transactions

Once you have played with it, learn the same idea from people who build these systems. Watch first for the picture, then read for the detail.

Check yourself

1 of 4. Why can two-phase commit block?

Go deeper