Marcelo Pastorino, Software Developer

Two-Phase Commit

A protocol that coordinates a single atomic transaction across multiple participants using a prepare phase and a commit phase.

Two-phase commit (2PC) is a distributed transaction protocol that makes several participants commit or abort as one atomic unit. A coordinator first asks every participant to prepare. If all participants vote yes, the coordinator tells everyone to commit. If any participant votes no, everyone aborts.

2PC tries to preserve atomicity across multiple resources. It pays for that guarantee with blocking, lock duration, and coordinator dependency.

Protocol flow

Two-phase commit sequence

During prepare, each participant must guarantee that it can commit later. That usually means writing a transaction log entry and holding locks until the final decision arrives.

Why it is hard in practice

  • Participants can hold locks while waiting for the coordinator.
  • A coordinator crash can leave prepared participants blocked.
  • Network partitions make it unclear whether the final decision was sent or received.
  • Every participant must implement compatible transaction coordination.
  • Latency grows with the slowest participant.

These costs are why many service architectures avoid 2PC across service boundaries.

Alternatives

The outbox pattern commits local state and publish intent in one database transaction, then relays the event asynchronously. The saga pattern coordinates a workflow through local transactions and compensating actions. Both accept eventual consistency instead of trying to make the whole workflow atomic.

When it still fits

2PC can make sense inside a controlled platform where participants are few, latency is acceptable, and transaction managers are a normal part of the stack. It is less attractive across independently owned services, external APIs, or cloud resources with different failure and retry models.

Trade-offs

2PC gives a clean mental model at the business level, but the implementation pushes complexity into coordination. If the business process can tolerate compensation, reconciliation, or temporary inconsistency, local transactions plus asynchronous patterns are usually easier to operate.

See also

  • Outbox Pattern, Reliably publishing events by committing them in the same transaction as state changes.
  • Saga Pattern, Managing distributed transactions across services with a sequence of local transactions and compensating actions.
  • Eventual Consistency, A consistency model where replicas converge to the same state over time, allowing temporary divergence after a write.

On Wikipedia