System design concepts · Data That Doesn't Break

2PC vs Saga vs Outbox Pattern: Distributed Transactions Explained

The moment an operation spans two databases, "just use a transaction" stops working. These patterns are how real systems keep money, inventory and orders consistent anyway.

What you'll be able to explain
  • Explain two-phase commit and why it's rarely used across services
  • Design a saga with compensating actions
  • Choose choreography vs orchestration
  • Solve the dual-write problem with a transactional outbox
  • Make consumers idempotent

The problem

Placing an order touches the Orders DB, the Payments ledger and the Inventory DB, each owned by a different service. If payment succeeds but inventory fails, what then?

Two-phase commit (2PC)

A coordinator asks every participant to prepare (lock resources, promise to commit), then tells everyone to commit if all said yes, or abort otherwise.

CoordinatorOrders DBInventory DB1PREPARE2PREPARE3YES (locked)4YES (locked)5COMMIT6COMMIT
Two-phase commit. If the coordinator dies after "prepare", participants hold locks and wait.

2PC gives atomicity, but it's blocking: if the coordinator fails mid-protocol, participants keep locks until it recovers. It needs all participants to support the protocol, and it couples their availability. It's used inside databases (Spanner, CockroachDB) and in some enterprise systems, but rarely between microservices.

Sagas: a sequence of local transactions

A saga breaks the operation into steps, each a local transaction in one service. If a step fails, previous steps are undone by compensating actions.

1 · Create orderstatus = PENDING (compensation: mark CANCELLED)2 · Reserve stockhold items (compensation: release hold)3 · Charge paymentfails: card declined↩ · Compensaterelease stock hold → cancel order → notify user
Order saga: forward steps, and compensations if step 3 fails.

Important properties:

  • Compensations are semantic undo, not rollbacks: a refund, not erasing the charge.
  • Intermediate states are visible (the order is "PENDING"). Design the UI and APIs for that.
  • Order steps so the hardest-to-undo step (charging money, sending an email) comes last.

Choreography vs orchestration

Choreography Orchestration
How Services react to each other's events A central orchestrator tells each service what to do
Pros Loose coupling, no central component Flow visible in one place, easier to change and debug
Cons Flow is implicit; cycles; hard to trace Orchestrator is another service to build and keep available
Fit 2–4 steps, simple flows Complex flows, many steps, timeouts, human tasks

Workflow engines such as Temporal, Cadence, AWS Step Functions and Camunda implement durable orchestration.

The dual-write problem

A service updates its database and publishes an event. If it does both separately, a crash between them leaves the two out of sync: an order saved with no event, or an event about an order that was never saved.