Distributed Transactions: 2PC, XA and the Alternatives

Why ACID across services is hard: how two-phase commit and XA work, why they rarely fit microservices, distributed SQL as an alternative, and the toolkit that replaces them: local transactions, outbox, idempotency, sagas, TCC and reservations.

On this page

Simple definition#

A distributed transaction is an all-or-nothing update that spans more than one database or resource, for example debiting an account in one service and creating a shipment in another.

The problem#

Inside one database, ACID transactions are cheap and reliable. Microservices use database per service, and integrations add brokers and external APIs. Code like this:

@Transactional
public void placeOrder(Order o) {
  orderRepo.save(o);                 // DB 1
  paymentClient.charge(o);           // remote service, DB 2
  kafkaTemplate.send("orders", o);   // broker
}

…is not atomic. The charge may succeed while the DB commit fails, or the event may be sent for an order that rolls back. This is the dual-write problem.

Two-phase commit (2PC)#

Two-phase commit
sequenceDiagram
    participant TC as Coordinator
    participant A as Resource A
    participant B as Resource B
    TC->>A: PREPARE
    TC->>B: PREPARE
    A-->>TC: YES (locks held, durable)
    B-->>TC: YES
    TC->>TC: log COMMIT decision
    TC->>A: COMMIT
    TC->>B: COMMIT
  1. Prepare: each participant does the work, makes it durable, keeps its locks and votes yes or no.
  2. Commit or abort: the coordinator logs the decision and tells everyone.

XA is the standard API for 2PC across databases and message brokers (JTA in Java).

Why 2PC rarely fits microservices#

Issue Effect
Blocking If the coordinator dies after prepare, participants hold locks until it recovers (“in doubt”)
Latency Extra round trips and fsyncs on every transaction
Availability Every participant must be up, so availability multiplies down
Coupling All services must share a transaction manager and support XA
Support Many modern stores, cloud services, Kafka (for XA) and every REST API do not participate

2PC still has a place inside one platform: databases use it internally across shards, and some mainframe and messaging estates use XA. But do not stretch it across service boundaries.

Option 1: avoid the distributed transaction#

Often the best design is to redraw the boundary:

  • If two pieces of data must always change together, they probably belong in one service, one aggregate and one database.
  • Use a distributed SQL database (Google Spanner, CockroachDB, YugabyteDB, TiDB). It gives serializable ACID transactions across shards and regions using consensus plus 2PC internally, managed for you. You pay in write latency across regions.

Option 2: local transaction + reliable event (outbox)#

Commit the state change and the event in one local transaction, and publish the event asynchronously. Consumers react idempotently. See Outbox, CDC and idempotency.

Option 3: saga#

Split the business transaction into local transactions, each with a compensating action, coordinated by events (choreography) or by an orchestrator. See Saga pattern.

Option 4: TCC and reservations#

Try–Confirm–Cancel (TCC) reserves resources first and then confirms or cancels them:

Try–Confirm–Cancel
flowchart LR
    T["TRY<br/>reserve funds, hold seat<br/>(with expiry)"] -->|"all tries OK"| C["CONFIRM<br/>capture, ticket"]
    T -->|"any try fails or timeout"| X["CANCEL<br/>release holds"]
  • Card payments already work this way: authorise (hold) and later capture or void.
  • Reservations expire automatically, so a crashed coordinator does not lock resources forever.
  • Confirm and cancel must be idempotent, and cancel must handle “try never arrived” (an empty cancel).

Comparison#

Approach Consistency Coupling Availability Complexity Best for
2PC / XA Atomic High Lower Infrastructure Legacy estates, single platform
Distributed SQL Serializable Shared DB High (consensus) Low for apps Data that truly belongs together
Outbox + events Eventual Low High Medium Propagating state changes
Saga Eventual, with compensation Low–medium High Medium–high Multi-step business processes
TCC Eventual, with reservations Medium High High Inventory, seats, funds holds

Designing for failure#

  • Every remote call can succeed, fail or time out (unknown). Design the unknown case: query status, use idempotency keys, and reconcile.
  • Make every step idempotent and retriable.
  • Keep an audit log of steps and decisions.
  • Run reconciliation jobs that compare systems and fix or flag drift. In finance this is mandatory, not optional.

Common mistakes#

Quick check#

What is the dual-write problem? Writing to two systems (for example a DB and a broker) without a shared transaction, so one write can succeed while the other fails.

Why does 2PC block? Participants that voted yes must hold locks until they learn the decision. If the coordinator fails, they wait.

What is TCC? Try–Confirm–Cancel: reserve resources tentatively (with expiry), then confirm all or cancel all.

When is distributed SQL a good alternative? When the data truly belongs together and needs serializable transactions, and you can accept cross-region write latency.

What three outcomes must every remote call handle? Success, failure and unknown (timeout).

Summary#

  • ACID does not span services. The dual-write problem is the root issue.
  • 2PC and XA work but block, couple services and reduce availability, so avoid them across services.
  • Prefer better boundaries, distributed SQL, the outbox, sagas or TCC reservations.
  • Design for the unknown outcome with idempotency, status queries and reconciliation.

References#