Distributed Transactions — System Design

A distributed transaction changes data in several databases or services as one unit. Two-phase commit (2PC) uses a coordinator: in phase 1, the coordinator…

The rule for buying concert tickets with four friends: everyone joins, or nobody does. You're the coordinator and ask each one: "Ready to pay?" Whoever says ready must set the money aside and not spend it on anything else. Once everyone is ready, you say "pay now!".

Now your phone dies right after everyone said ready. Your friends wait with their money held: they can't pay on their own (maybe someone backed out), and they can't spend it (maybe you already told the others to pay). That's two-phase commit, weakness included. It's one way to run a distributed transaction: one transaction that changes data in more than one database or service, and must either succeed everywhere or be cancelled everywhere.

Why one transaction isn't enough

In one database, a transaction is ACID: every statement between BEGIN and COMMIT succeeds together or is cancelled together (the Transactions & Isolation Levels lesson in the Database track). The trouble is that TicketTune is now microservices, and each service has its own database:

Budi books seats A-12 and A-13 for Archipelago Concert (event #42), order #1001, $150. Two changes, two databases. A BEGIN in db-ticket can't see db-payment. If the seats are marked sold and then the charge fails, or the card is charged and then the seat update fails, the data is half done. A distributed transaction tries to make the two databases behave like one.

Two-phase commit, step by step

Two-phase commit (2PC) is a protocol with one coordinator (here the order service) and several participants (db-ticket and db-payment). PostgreSQL has its own commands for it:

Step Coordinator (order) db-ticket db-payment
1. Work sends the statements BEGIN; UPDATE seats ... → UPDATE 2, seats A-12 and A-13 locked BEGIN; INSERT INTO charges ... → INSERT 0 1
2. Phase 1: prepare asks "ready to commit?" PREPARE TRANSACTION 'ord-1001': votes YES PREPARE TRANSACTION 'ord-1001': votes YES
3. Decision writes ord-1001: COMMIT to its log waits, still holding the locks waits
4. Phase 2: commit sends "commit!" COMMIT PREPARED 'ord-1001', locks released COMMIT PREPARED 'ord-1001'

Here is the coordinator in JavaScript:

// order as the coordinator: phase 1, the decision, phase 2
async function twoPhaseCommit(gid, participants) {
  const votes = [];
  for (const p of participants) votes.push(await p.prepare(gid)); // "YES" or "NO"
  const result = votes.every((s) => s === "YES") ? "COMMIT" : "ABORT";
  await decisionLog.write(gid, result); // stored durably BEFORE it is sent
  for (const p of participants) {
    if (result === "COMMIT") await p.commit(gid); // COMMIT PREPARED 'ord-1001'
    else await p.rollback(gid); // ROLLBACK PREPARED 'ord-1001'
  }
  return result;
}

The coordinator crashes: everyone waits

Now order crashes after both voted YES, before writing a decision. The Lab's example model:

Time What happens
10:00:00 db-ticket and db-payment vote YES. Seats A-12 and A-13 are locked.
10:00:00 order crashes. There's no decision in its log.
10:00:30 Siti tries to buy A-12: ERROR: canceling statement due to lock timeout
10:05:00 order comes back, finds no decision, and sends ROLLBACK PREPARED. The seats are released.

Seat A-12 ends up locked, neither sold nor free, for 5 minutes, in the middle of the ticket war. db-ticket may not decide on its own. If it rolls back, maybe the coordinator already decided COMMIT and db-payment already charged Budi's card: money taken, seat released. If it commits, maybe db-payment had said NO. A participant that voted YES can only wait. That's why 2PC is called a blocking protocol: one dead coordinator freezes all its participants.

When it comes back, the coordinator reads its log. A COMMIT in the log? Send COMMIT PREPARED. No decision? Treat it as cancelled (presumed abort) and send ROLLBACK PREPARED. In PostgreSQL, transactions left hanging like this show up in the pg_prepared_xacts view.

Why most systems avoid 2PC

2PC is still used in controlled places, for example inside one distributed database or between two databases owned by one team, at low volume. Across microservices, the choice is almost always the next one.

The alternative: Saga

A Saga trades one big transaction for a sequence of local transactions, each committing right away in its own database. If one step fails, the steps already done are undone with a compensating transaction:

  1. ticket marks A-12 and A-13 sold (a local commit).
  2. payment charges the card. Declined? Run step 1's compensation: ticket releases the seats again.

No lock is held across the network, so nothing freezes. The price: there is a short moment when the seats are recorded as sold while the payment is still unclear (eventual consistency), and every step needs its own compensation. There are two ways to run the sequence:

How it works, compensations that are safe to repeat, and when to pick which are taken apart in the next lesson, Saga Pattern.

⚠️ Frozen locks and a card charged with no seat

TL;DR: A distributed transaction changes data in several databases or services as one unit. Two-phase commit (2PC) uses a coordinator: in phase 1, the coordinator asks every participant to vote (PREPARE TRANSACTION; YES is a promise it can surely commit, and the locks stay held); in phase 2, if all said YES the coordinator orders a commit (COMMIT PREPARED), and if even one said NO everyone rolls back (ROLLBACK PREPARED). The decision is written to the coordinator's log before it is sent. The main weakness: 2PC is a blocking protocol. If the coordinator crashes between the two phases, participants that voted YES stay locked until it comes back (in the Lab: seat A-12 locked for 5 minutes, Siti hits a lock timeout). Because of that, plus locks held longer and participants that often don't support prepare, most systems avoid 2PC across services and use a Saga: a sequence of local transactions with compensating transactions. In a choreography Saga, each service listens to the previous service's events and reacts; in orchestration, one orchestrator commands the sequence.

⚡ One action, two databases

Meaning: ticket owns the seats table in db-ticket, payment owns the charges table in db-payment. A BEGIN in db-ticket can't see db-payment, so if one step fails, the data is half done. A distributed transaction tries to make the two databases behave like one.

⚡ Two phases

Write:

for (const p of participants) votes.push(await p.prepare(gid)); // "YES" or "NO"
const result = votes.every((s) => s === "YES") ? "COMMIT" : "ABORT";
await decisionLog.write(gid, result); // stored durably BEFORE it is sent

Meaning: Phase 1: each participant answers PREPARE TRANSACTION. YES is a promise it can surely commit, and its locks stay held. Phase 2: if everyone said YES, the coordinator orders a commit. A single NO, and everyone rolls back. The decision is logged before it is sent.

⚡ The coordinator crashes, everyone waits

Guess first: order crashes after db-ticket and db-payment answered YES, before logging a decision. May db-ticket decide on its own?

No. Maybe the coordinator already decided COMMIT and Budi's card is already charged. So it can only wait, and seat A-12 stays locked for 5 minutes.

Meaning: That's why 2PC is called a blocking protocol: one dead coordinator freezes all its participants.

⚡ The alternative: Saga

Meaning: A Saga trades one big transaction for a sequence of local transactions that commit right away in their own databases. If one step fails, the steps already done are undone with a compensating transaction. No lock is held across the network.

What you will learn