When one business operation spans several databases or services (create the order, charge the card, reserve the stock), a local ACID transaction is no longer enough. You can either run an atomic commit protocol such as two-phase commit, which gives all-or-nothing semantics at the cost of blocking and tight coupling, or embrace eventual consistency with Sagas, the transactional outbox and Try-Confirm-Cancel. This lesson covers how each works, how each fails, and when to use which.
Think of it like
A wedding ceremony
The officiant (coordinator) asks each partner "Do you?" (prepare). Each "I do" is a binding promise: once said, you can't walk out. Only when both have said it does the officiant pronounce the marriage (commit). If one says no, the wedding is off (abort). And if the officiant faints right after both said "I do", everyone is stuck at the altar, unsure whether they're married, until the officiant wakes up. That last part is why two-phase commit is called blocking.
The problem
Placing an order touches the Orders database, the Payments service and the Inventory database. Each can commit locally, but nothing ties the three commits together. A crash between steps leaves a charged card with no order, or a reserved item nobody paid for.
- Partial failure: step 2 succeeds, step 3 fails. Something must undo step 2.
- Unknown outcome: a request times out. Did the remote side commit or not?
- Business rejection: inventory says "out of stock" after payment already succeeded.
- Dual writes: a service updates its database and publishes an event; either can fail independently.
Two-phase commit (2PC)
- 1
Phase 1: prepare
The coordinator sends
PREPAREto every participant. Each does its work, writes all changes plus a prepared record to its durable log, keeps its locks, and votes YES or NO. - 2
The promise
A YES vote is a promise: "I can commit no matter what, even if I crash and restart." After voting YES a participant can no longer abort on its own.
- 3
Decision
If every vote is YES, the coordinator force-writes
COMMITto its own log. This is the commit point. Any NO vote or timeout leads toABORTinstead. - 4
Phase 2: commit or abort
The coordinator sends the decision to every participant and retries until each acknowledges. Participants commit (or roll back) and release their locks.
Press play on each flow below, and use the simulation above to crash the coordinator or a participant at different moments.
Messages
4n
prepare, vote, decision, ack per participant
Round trips
2
before locks can be released
Forced log writes
2n + 1
prepare + commit per participant, decision at coordinator
Fault tolerance
Blocks
if the coordinator dies after votes
| Failure | What happens | Outcome |
|---|---|---|
| Participant crashes before voting | Coordinator times out waiting | Abort |
| Participant crashes after voting YES | On restart it finds its prepared record and asks the coordinator | Follows the coordinator's decision |
| Coordinator crashes before logging a decision | Prepared participants wait; on restart the coordinator presumes abort | Abort, after blocking |
| Coordinator crashes after logging COMMIT | On restart it resends COMMIT | Commit, after blocking |
| Network partition after a YES vote | Participant cannot learn the outcome | In-doubt until the link heals |
Three-phase commit (3PC)
3PC inserts a pre-commit phase between voting and committing: CanCommit? → PreCommit → DoCommit. No participant commits until all know that everyone voted YES, so if the coordinator dies, the survivors can elect a new one and finish without blocking. The catch: this only works if message delays are bounded and the network never partitions. With a partition, the two sides can reach different decisions. Real networks don't offer those bounds, so 3PC is rarely used.
XA transactions
XA (X/Open, 1991) is a standard interface between a transaction manager and resource managers such as databases and message brokers. Java's JTA uses it, MySQL exposes XA START / XA PREPARE / XA COMMIT, and PostgreSQL exposes the participant side directly.
BEGIN;
UPDATE accounts SET balance = balance - 30 WHERE id = 42;
PREPARE TRANSACTION 'order-981'; -- phase 1: durable, locks kept, survives a restart
-- ... the coordinator collects every participant's vote ...
COMMIT PREPARED 'order-981'; -- phase 2 (or: ROLLBACK PREPARED 'order-981')- The coordinator is often a library inside the application server. If that server dies, in-doubt transactions are orphaned until it comes back.
- Every participant must speak XA. HTTP APIs and most SaaS services don't, which rules XA out between microservices.
- There is no cross-system deadlock detection, and locks are held for the slowest participant.
- Forgotten prepared transactions hold locks and block cleanup indefinitely; monitor
pg_prepared_xacts.
Sagas
A saga (Garcia-Molina and Salem, 1987) replaces one big transaction with a sequence of local transactions T1, T2, ..., Tn, each with a compensating transaction C1, C2, ..., Cn that semantically undoes it. If Tk fails, the saga runs Ck-1, ..., C1 in reverse order. No locks are held across steps, so nothing blocks, but you give up isolation: other requests can see intermediate states.
| Step | Local transaction | Compensation |
|---|---|---|
| 1 | Order service: create order as PENDING | Mark order CANCELLED |
| 2 | Payment service: charge card | Refund the charge |
| 3 | Inventory service: reserve stock | Release the reservation |
| 4 | Shipping service: schedule shipment | Cancel the shipment |
| 5 | Order service: mark CONFIRMED | None needed: this is the last step |
Choreography
- Each service reacts to events and emits the next one
- No central coordinator; very loose coupling
- Hard to see the whole flow or answer "where is order 981?"
- Risk of cyclic event dependencies
- Good for short sagas with 2 to 4 steps
Orchestration
- A saga orchestrator (a persistent state machine) commands each step
- Flow, timeouts and compensations live in one place
- Easy to monitor, test and change
- One more component to run; risk of a "god service"
- Tools: Temporal, AWS Step Functions, Camunda, Netflix Conductor
The dual-write problem and the transactional outbox
Sagas and event-driven systems need each service to update its database and publish an event. Doing both directly is a dual write: commit then publish, and a crash in between loses the event; publish then commit, and a rollback leaves an event for something that never happened. The transactional outbox turns the publish into a database write.
BEGIN;
INSERT INTO orders (id, customer_id, total_cents, status)
VALUES ('o-981', 'c-7', 4999, 'PENDING');
INSERT INTO outbox (id, aggregate_id, event_type, payload)
VALUES (gen_random_uuid(), 'o-981', 'OrderCreated',
'{"orderId": "o-981", "totalCents": 4999}');
COMMIT; -- both rows or neitherWithout CDC, a simple polling relay works too: SELECT ... FROM outbox WHERE published_at IS NULL ORDER BY id LIMIT 100 FOR UPDATE SKIP LOCKED, publish, then mark the rows published. The same at-least-once caveat applies. More on this in Idempotency & Delivery Guarantees and Event-Driven Architecture, CQRS & Event Sourcing.
TCC: Try-Confirm-Cancel
TCC is a reservation-based protocol at the business level. Each participant exposes three operations: Try reserves resources tentatively (with an expiry), Confirm makes the reservation permanent, and Cancel releases it. A coordinator calls Try on everyone, then Confirm on everyone if all Trys succeeded, otherwise Cancel. It resembles 2PC, but no database locks are held: the "lock" is a visible business state such as "seat held for 10 minutes" or a card authorization hold.
- Confirm and Cancel must be idempotent, because the coordinator retries them until they succeed.
- Empty cancel: a Cancel can arrive for a Try that never arrived (it timed out in the network). Record the cancellation so it succeeds harmlessly.
- Hanging Try: a delayed Try can arrive after its Cancel. Reject it using that recorded cancellation, or the reservation leaks.
- Reservations must expire so a crashed coordinator can't hold resources forever.
- Examples: card authorize-then-capture, seat and hotel holds, Seata's TCC mode.
Choosing an approach
| Approach | Consistency | Isolation | Blocks on failure? | Coupling | Good for |
|---|---|---|---|---|---|
| 2PC / XA | Atomic | Yes (locks) | Yes, if the coordinator fails | Tight: same protocol, all participants up | Short transactions inside one database cluster or vendor |
| 2PC over consensus groups | Atomic | Yes | No (coordinator is replicated) | Inside one distributed database | Spanner, CockroachDB, YugabyteDB |
| Saga | Eventual | None (semantic locks) | No | Loose | Long-running business processes across services |
| TCC | Eventual, with reservations | Partial (held states) | No (reservations expire) | Medium: three APIs per service | Inventory, seats, payment holds |
| Outbox + events | Eventual | None | No | Loose | Reliably propagating state changes |
Idempotency is mandatory
Every message in these protocols can be delivered twice: a command retried after a timeout, a compensation retried after a crash, an outbox event republished. Each handler must therefore be idempotent. The usual tools are idempotency keys, a table of processed message IDs written in the same transaction as the effect, and guarded state transitions.
-- Only the first attempt changes anything; retries update 0 rows
UPDATE orders SET status = 'CANCELLED'
WHERE id = 'o-981' AND status = 'PENDING';Implementation
Runs steps in order; on failure, compensates completed steps in reverse. A production orchestrator also persists progress after every step.
import time
from dataclasses import dataclass
from typing import Callable, Generic, TypeVar
C = TypeVar("C")
@dataclass
class Step(Generic[C]):
name: str
action: Callable[[C], None]
compensate: Callable[[C], None]
def retry_forever(fn: Callable[[], None], base_delay: float = 0.2) -> None:
attempt = 0
while True:
try:
fn()
return
except Exception:
time.sleep(min(base_delay * 2 ** attempt, 30.0)) # exponential backoff
attempt += 1
def run_saga(steps: list[Step[C]], ctx: C) -> None:
done: list[Step[C]] = []
for step in steps:
try:
step.action(ctx)
done.append(step)
except Exception as err:
# Compensate in reverse order; compensations must be idempotent
for s in reversed(done):
retry_forever(lambda s=s: s.compensate(ctx))
raise RuntimeError(f"saga aborted at {step.name!r}") from errKey takeaways
- Local ACID doesn't span services; you choose between atomic commit (2PC) and eventual consistency (sagas, outbox, TCC).
- 2PC: prepare then commit. A YES vote is a binding promise, and the coordinator's logged decision is the commit point.
- 2PC blocks if the coordinator fails after votes; replicating the coordinator with consensus removes the blocking.
- Sagas chain local transactions with compensations; they never block but expose intermediate states.
- The transactional outbox (plus CDC or a poller) eliminates dual writes; consumers must still deduplicate.
- Every step, compensation and confirmation must be idempotent because retries are inevitable.
Common pitfalls
- Publishing an event and writing to the database as two separate operations (dual write).
- Writing compensations that aren't idempotent, so a retried refund pays out twice.
- Assuming a saga gives isolation, and letting other flows act on PENDING data as if it were final.
- Leaving orphaned prepared transactions that hold locks indefinitely.
- Using 3PC and believing it is safe under network partitions.
Interview tips
- Walk through the 2PC coordinator-crash scenario and explain precisely why participants can't decide on their own.
- Compare choreography and orchestration, then pick one for the problem and justify it.
- Mention the outbox whenever your design both writes to a database and publishes an event.
Real-world applications
- Distributed SQL databases (Spanner, CockroachDB) committing multi-shard transactions with 2PC over Raft or Paxos groups.
- E-commerce order pipelines implemented as orchestrated sagas (Temporal, Step Functions).
- Card payments using authorize/capture/void, a real-world TCC.
- Event-driven microservices publishing domain events through an outbox and Debezium.
Test yourself
Why is two-phase commit called a blocking protocol?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.