Module 5 · Distributed systemsLesson 54 of 886 minAdvanced

Distributed transactions

When one action changes data in several services or databases, there's no single transaction to keep them in step.

Try it

Play "The problem" and see the services end up disagreeing when inventory fails after the order and payment succeeded.

Inside one database, transactions give you all-or-nothing for free. Microservices split data across many databases, so one business action, like placing an order, may need to:

  • create an order in the order service,
  • charge the card in the payment service,
  • reserve stock in the inventory service.

Each commits to its own database. If inventory fails after payment succeeded, the system is left half done: a charged card and no stock.

Your options

1. Two-phase commit (2PC): a coordinator asks every participant to prepare, then tells them all to commit or all to abort. True atomicity, but it's slow, holds locks, and gets stuck if the coordinator fails. Next lesson.

2. Sagas: run each step as a local transaction, and if a later step fails, run compensating steps to undo earlier ones (refund the card, cancel the order). No global locks, but there's a period where the system is visibly in between. Lesson after next.

3. Avoid it: put data that must change together in the same service and database. If "order" and "stock reservation" always change together, maybe they belong together.

4. Outbox pattern: when a service must update its database and publish an event, write the event into an outbox table in the same local transaction. A separate process publishes from the outbox. This avoids "saved the order but never told anyone", and is the building block of reliable sagas.

Which to choose

Most modern microservice systems use sagas with the outbox pattern for business workflows, and reserve 2PC for infrastructure inside a single system (like a distributed database coordinating its own shards).

Quick check

Why can't you wrap a call to the payment service and the inventory service in one database transaction?