Skip to main content

Two-Phase Commit (2PC)

Two-phase commit coordinates multiple resources to commit or abort atomically via a prepare phase and a commit phase. It guarantees distributed atomicity but blocks and holds locks, limiting scalability.

Type
Concurrency
When to Use
Distributed Atomic Commit, Multiple Resource Managers, Strong Consistency Required

Two-phase commit (2PC) is a consensus protocol that makes a transaction spanning multiple independent resources (databases, queues, services) commit all-or-nothing. A coordinator drives the participants through two phases so that either every participant commits or every participant aborts, preserving atomicity across the distributed transaction.

How It Works

  • Phase 1 — prepare (voting): the coordinator asks each participant to prepare. Each does the work, writes it durably to a state from which it can either commit or roll back, locks the affected data, and replies yes (ready) or no.
  • Phase 2 — commit/abort: if all voted yes, the coordinator records the commit decision durably and tells everyone to commit; if any voted no (or timed out), it tells everyone to abort. Participants act on the decision and release their locks, then acknowledge.

The coordinator's durable decision log lets it recover and resend the outcome after a crash. The XA standard and distributed transaction managers (JTA, MSDTC) implement 2PC across compliant resources.

When to Use It

Use 2PC when you genuinely need atomic commit across multiple transactional resources and strong consistency is non-negotiable: enterprise systems coordinating a database and a message broker, or multiple databases that must update together. It is most appropriate within a single trusted data center with reliable, low-latency links.

Trade-offs

2PC is a blocking protocol: if the coordinator fails after participants have prepared but before delivering the decision, participants stay locked and in doubt until it recovers, harming availability. It holds locks across network round trips, hurting throughput and scalability, and it scales poorly across high-latency or partition-prone links. These weaknesses make it a poor fit for microservices and the open internet, where the saga-pattern (a sequence of local transactions with compensations) is usually preferred despite offering only eventual, not atomic, consistency.

Related Patterns

The saga-pattern is the eventually-consistent alternative for distributed workflows; 2PC relies on pessimistic-locking at each participant, and recovery resends benefit from idempotent-writer handling.

Example

A banking transfer must debit account A in one database and credit account B in another. A transaction coordinator runs 2PC: both databases prepare and lock the rows, and only if both vote ready does the coordinator commit both. If either cannot prepare, both roll back, so money is never created or lost.