Distributed Transactions

Atomic commits across multiple nodes or services — two-phase commit and its blocking problem, three-phase commit, consensus-backed commit (Spanner, CockroachDB), sagas with compensation, the outbox pattern, and idempotency.

Advanced 5 min readLesson 7 of 9 Interview Q&A

A transaction that touches data on several nodes — shards of one database, or databases owned by different services — must still be atomic: either every participant commits, or none does. With independent failures, that's hard.

Two-phase commit (2PC)

A coordinator drives the commit in two phases:

CoordinatorParticipant AParticipant BPREPAREPREPAREYES (locked, durably logged)YESwrite COMMIT decision to logCOMMITCOMMITackack
  1. Prepare (voting): the coordinator asks every participant whether it can commit. A participant that votes YES must durably record its changes and keep its locks — it promises to commit if told to, even after crashing and restarting.
  2. Commit (decision): if all vote YES, the coordinator logs COMMIT and tells everyone to commit; if any votes NO (or times out), it tells everyone to abort.

The blocking problem

After voting YES, a participant cannot decide on its own. If the coordinator crashes after collecting votes but before announcing the decision, participants are stuck in doubt: holding locks, unable to commit (maybe someone voted NO) or abort (maybe the coordinator logged COMMIT). They must wait until the coordinator recovers — possibly a long time, blocking other transactions on those rows.

Other drawbacks: at least two round trips plus forced disk writes per transaction, and every participant must be available (availability is the product of all participants').

XA is the standard API for 2PC across heterogeneous resources (a database and a message broker); it's rarely used across services today because of these costs.

Three-phase commit adds a pre-commit phase to avoid blocking, but it assumes bounded network delays and breaks under partitions — so it's mostly of theoretical interest.

Making 2PC fault-tolerant: consensus-backed commit

Modern distributed SQL databases remove the single-coordinator problem by making every participant and the coordinator state itself a Raft/Paxos group (Consensus). A "participant" never really disappears: if a node dies, another replica of its group takes over with the same durable state.

  • Spanner: 2PC over Paxos groups, with TrueTime timestamps for global ordering (Clocks).
  • CockroachDB: "parallel commits" — a transaction record and write intents in Raft groups, committing in roughly one round of consensus.
  • TiDB/TiKV: Percolator-style 2PC over Raft.

Inside one database system, this gives you real ACID transactions across shards, at the cost of extra latency for cross-shard (and especially cross-region) transactions.

Across services: sagas

Between microservices with separate databases, holding locks across services for the duration of a 2PC is rarely acceptable. Instead, use a saga: a sequence of local transactions, each publishing an event or triggering the next step, with a compensating transaction for each step to undo it if a later step fails (Microservices).

Step (T)Compensation (C)1234Create order (PENDING)Cancel orderReserve inventoryRelease inventoryCharge paymentRefund paymentMark order CONFIRMED—
If step 3 fails: run C2 then C1, in reverse order.
Coordination styleHowProsCons
OrchestrationA central orchestrator (often a workflow engine: Temporal, AWS Step Functions, Camunda) calls each step and compensationsFlow is explicit and observable; easy to changeThe orchestrator is another component
ChoreographyEach service reacts to the previous service's eventsLoose coupling, no central componentThe overall flow is implicit; hard to follow and debug

What sagas give up

Sagas provide ACD without I: intermediate states are visible to other transactions (another request might see the order PENDING, or inventory reserved before payment fails). Countermeasures:

  • Semantic locks: mark records as pending (status = PENDING) so other operations treat them carefully.
  • Commutative updates and reread-before-commit checks.
  • Order steps so the ones most likely to fail come first, and irreversible actions (sending an email, shipping) come last (pivot transactions).
  • Compensations must be idempotent and retryable — they can't "fail" permanently.

Reliable messaging between steps

Every saga step does "update my database and publish an event". Doing these as two separate operations risks a crash in between (the dual-write problem). Fixes:

  • Transactional outbox: write the event to an outbox table in the same local transaction; a relay process (or CDC with Debezium) publishes it to the broker. Delivery becomes at-least-once.
  • Idempotent consumers: dedupe by event ID so redelivered events have no extra effect (Message queues).
SQL
BEGIN;
UPDATE orders SET status = 'PAID' WHERE id = 42;
INSERT INTO outbox (id, aggregate_id, type, payload)
VALUES (gen_random_uuid(), 42, 'OrderPaid', '{"orderId": 42, "amount": 1999}');
COMMIT;
-- a relay reads new outbox rows and publishes them to Kafka, then marks them sent

Choosing

SituationUse
Multiple rows/shards inside one distributed databaseThe database's transactions (Spanner, CockroachDB, Vitess with care)
Across services you control, long-running business processesSaga with outbox + idempotent consumers, ideally on a workflow engine
Two systems that both support XA, low throughput, same data centre2PC can be acceptable
Avoidable?Often the best option: redesign boundaries so one service owns the data that must change atomically
Key takeaways
  • 2PC: prepare (vote) then commit; atomic but blocking if the coordinator fails after votes.
  • Distributed SQL makes 2PC fault-tolerant by running participants and coordinator on consensus groups.
  • Across services, sagas replace one big transaction with local transactions plus compensations.
  • Sagas lack isolation: use semantic locks, ordering of steps and idempotent compensations.
  • The transactional outbox and idempotent consumers make "update + publish" reliable.
Interview questions
QWhat is the main problem with two-phase commit?medium

It's blocking: once a participant votes yes it must wait for the coordinator's decision while holding locks. If the coordinator crashes after collecting votes, participants remain in doubt until it recovers. It also adds latency (two round trips and forced log writes) and reduces availability, since every participant must be up. Production systems mitigate this by replicating the coordinator and participants with consensus, or avoid it across services by using sagas.

QHow do you keep data consistent across microservices without distributed transactions?hard

Use a saga: break the operation into local transactions per service, each publishing an event (reliably, via a transactional outbox) that triggers the next step, with compensating actions to undo completed steps if a later one fails. Make consumers and compensations idempotent, use semantic locks such as pending states to handle the lack of isolation, and consider an orchestrator or workflow engine to make the flow explicit.