# Two-phase commit

## What it is

Two-phase commit is a protocol for making a single commit decision across
several transactional participants. Each participant may own a different set of
records and use its own transaction log. A coordinator collects their votes and
records the decision they will all have to follow. The protocol is used when the
operation's contract calls for committing all of its participating effects
together or rolling them all back.

In the first phase, the coordinator asks each participant to prepare. A
participant that votes yes records enough durable state to carry out a later
commit after a restart. Its local work is prepared and its final outcome is
still pending. The coordinator can decide to commit once every participant has
prepared successfully. A participant can refuse to prepare, which gives the
coordinator a reason to decide to abort the operation.

In the second phase, the coordinator communicates the recorded decision. If a
reply is lost, recovery has to distinguish uncertainty about delivery from
uncertainty about what was decided. Once the durable decision is commit, the
system can keep sending that decision or recover it from durable records. A
participant that prepared should follow the shared outcome even after its
original connection has closed. PostgreSQL exposes this prepared state through
explicit transaction commands. A transaction manager typically supplies the
coordination around them.

## Why it matters

Consider a transfer with entries in two separate ledgers. Each ledger could
commit its own update and return success independently. If the connection to the
second ledger fails around that commit, an operator needs to know which entries
are durable and which request may safely be repeated. A shared outcome changes
the recovery task. Both ledgers agree to accept the durable decision before the
coordinator reports the transfer as committed.

The resulting guarantee depends on the participating systems. Every participant
must implement prepare and later resolve the same transaction consistently. An
ordinary HTTP callback or payment request often gives no such prepared state to
the caller. Pick the operation boundary by listing which effects actually have a
compatible durable protocol. If an effect belongs to a system outside the
transaction, give it a separate identity and recovery path.

There is an operating cost in addition to the extra messages. A prepared
transaction can hold locks while waiting for the coordinator to resume or for an
operator to recover the decision. In PostgreSQL, a long-lived prepared
transaction can also interfere with cleanup of old data versions. The risk
becomes more visible when a participant is slow, a deployment interrupts a
coordinator, or a human has to investigate during an outage. An organisation
that adopts the protocol needs a way to find each outstanding operation and
resolve it safely.

## What it looks like in practice

An illustrative transfer uses three durable records. The coordinator holds a
transaction identifier that is shared by both participants. Each participant
associates it with its prepared update. The coordinator records the final
decision before it tells any participant to finish. A useful test pauses the
system after both sides prepare, after the coordinator records commit, and after
one side receives that decision. Restart the coordinator at each point and make
the expected next step explicit.

Measure the reader's experience as well as the records. During a delay, a
request status might show that the transfer is pending. Once recovery completes,
the client can look up the transfer using the original operation identifier.
Progress logs should connect the coordinator's durable decision and each
participant's result. An alert can identify prepared operations that are older
than an agreed threshold and direct an operator to the system that owns their
outcome.

Engineer's
[engineering note on limited-stock checkout](/notes/selling-limited-stock-without-overselling/)
compares this decision with a checkout spanning stock, order and payment
services. The article points out that payment providers in the proposed workflow
do not join a shared prepared transaction. It describes a sequence of local
steps, including an expiring stock hold and a payment authorisation. That
example helps identify a practical boundary before considering the protocol.
List each participant and ask what durable decision it can actually honour.

## Where it goes wrong

A prepared transaction is easy to mistake for an ordinary connection that timed
out. An operator may see that the client which issued the prepare command is
gone and think it is safe to discard the work. The prepared record exists
independently of that session. Recover the decision first, identify the
corresponding transaction on each system, and use the established policy for an
operation whose outcome is still unknown. Ad hoc cleanup can break the agreement
the protocol was chosen to preserve.

A failed request can also look different from a failed operation. When a server
confirms commit but the reply disappears, another attempt with a fresh
identifier can create a second update. Treat the operation's identity as part of
the durable record, and make it possible to query the current outcome. Test lost
acknowledgements at the prepare and commit stages separately. The first affects
whether the coordinator can safely choose commit. The second can occur after the
decision is already fixed.

Watch for long periods when others are blocked behind prepared work. Measure the
duration from prepare to resolution and rehearse a coordinator restart while
traffic is active. Make recovery instructions name the correct source of the
decision and the consequences for each participant. A two-phase commit supports
a particular form of agreement. Availability under a disconnected participant,
graceful client responses and the cost of holding locks still need explicit
design choices.

## Further reading

- [PostgreSQL two-phase transactions](https://www.postgresql.org/docs/18/two-phase.html).
  Explains the database commands that participate in external coordination.
- [PostgreSQL PREPARE TRANSACTION](https://www.postgresql.org/docs/18/sql-prepare-transaction.html).
  Describes prepared state, durability and operational effects.
- [The PostgreSQL pg_prepared_xacts view](https://www.postgresql.org/docs/18/view-pg-prepared-xacts.html).
  Shows how to identify transactions awaiting resolution.

<https://engineer.company/glossary/two-phase-commit/>
