EMZETT.
Login

Distributed transactions: two-phase commit and saga

In short: When an action touches several databases or services, you need procedures that make all confirm or all roll back: two-phase commit (strict, blocking) or saga (loose, with compensating actions).

In more detail: In 2PC a coordinator asks all participants whether they are ready (prepare) and then releases the commit. If the coordinator fails after the prepare phase, participants block. A saga splits the action into local transactions; if a step fails, compensations run for the steps already done.

In Depth

  • 2PC: Atomic, but blocking and slow; locks are held longer.
  • Saga: Scales in microservices; intermediate states are visible.
  • Choreography vs. orchestration: Services react to events or a coordinator steers.
  • Compensation: For example refund a payment if shipping fails. Must be idempotent.
  • Outbox pattern: Store event and data change in one local transaction, then send reliably.
  • Rule of thumb: Keep transaction boundaries as small as possible.

See also: Sharding and partitioning, Event sourcing and CQRS