Distributed Transactions: 2PC, TCC, Saga
- Explain two-phase commit, why it blocks when the coordinator fails, and why 3PC did not fix it in practice
- Describe XA and when database-level distributed transactions are still reasonable
- Design a TCC flow including idempotency, empty rollback and hanging-try handling
- Design a Saga (orchestrated or choreographed) with compensations, semantic locks and a pivot step
- Choose the right approach for an internal money transfer, an interbank transfer and an e-commerce checkout
TL;DR
- First choice: don't distribute the transaction. If both accounts live in the same ledger database, a local ACID transaction is simpler and safer than any protocol below. Draw service boundaries so that invariants live inside one database.
- 2PC gives atomic commit across resources: prepare (vote), then commit/abort. Its flaw is blocking: a participant that voted yes must hold locks until it hears the decision, so a coordinator failure can freeze resources. 3PC adds a phase but is unsafe under partitions and is rarely used.
- XA is the standard API for 2PC between a transaction manager and databases/brokers. Workable inside one trust boundary; a poor fit for microservices over HTTP.
- TCC (Try-Confirm-Cancel) is 2PC at the business level: Try reserves (freeze $200), Confirm uses the reservation, Cancel releases it. No database locks are held between phases, but every operation must be idempotent and handle out-of-order Cancel/Try.
- Saga: a sequence of local transactions, each with a compensating transaction that semantically undoes it. No isolation — other requests can see intermediate state — so you add semantic locks (PENDING status) and order steps around a pivot (point of no return).
- Orchestration (a central, persisted state machine) is easier to reason about and audit; choreography (services reacting to events) is looser but harder to follow beyond three or four steps.
- Every approach depends on idempotency and reliable messaging (outbox).
Why it matters
A customer transfers $500 from their savings account (core banking system) to their e-wallet (a separate wallet service with its own database). If the debit commits and the credit fails, money has vanished from the customer's point of view. If the credit commits and the debit fails, the bank has created money. Neither is acceptable, and "we'll fix it in reconciliation" is an incident, not a design.
E-commerce has the same shape with more participants: checkout must create the order, reserve stock, authorize the card and maybe redeem a voucher and loyalty points. During a flash sale, any participant can be slow or down. A design that holds database locks across all of them for the duration of a card authorization will collapse under load; a design with no coordination will oversell or charge customers for orders that never exist.
Interviewers at banks and marketplaces almost always ask some version of "how do you keep these two services consistent?" They want to hear you reject naive dual writes, know why 2PC is rarely used across microservices, and design a saga with real compensations and failure handling.
Core concepts
Two-phase commit (2PC)
One coordinator and several participants (databases, queues).
- Prepare. The coordinator asks each participant to prepare. A participant that can commit writes everything (including a prepare record) durably, keeps its locks, and votes yes. Once it votes yes, it has given up the right to abort on its own.
- Decide. If all vote yes, the coordinator durably logs commit and tells everyone to commit; if any votes no or times out, it logs abort and tells everyone to roll back. Participants acknowledge; the coordinator can then forget the transaction.
Why it blocks. A participant in the prepared state does not know the outcome. Committing on its own could contradict an abort; aborting could contradict a commit. So it waits — holding row locks — until the coordinator recovers. Other transactions touching those rows (other transfers on the same account) queue behind them. Operators can force a heuristic commit or rollback, risking a mixed outcome that needs manual repair.
Other costs: at least two round trips plus multiple forced log writes per transaction; latency of the slowest participant; locks held across the network; and every participant must support the protocol.
When 2PC works well: when the coordinator and participants are themselves replicated with consensus. Spanner and CockroachDB run 2PC across Raft/Paxos groups; because the "coordinator" is a replicated group, a single machine failure does not block. That is why distributed SQL can offer multi-shard ACID transactions — at the cost of latency.
The same idea under TCC and sagas. The Ch 12 · Digital Wallet design shards accounts across Raft groups. A reverse proxy in front of each group holds a command open until the result is pushed back, so each group answers synchronously and a TCC or saga coordinator can drive it like an ordinary participant. A node crash then costs an election, not the participant's state; the coordinator's status table still needs the same durability.
Three-phase commit (3PC), briefly
3PC inserts a pre-commit phase so participants learn that everyone voted yes before anyone commits; with that knowledge, a recovery protocol can decide without the coordinator. It assumes bounded network delay and no partitions. Under a partition, two sides can decide differently, so it trades blocking for potential inconsistency. It is a classic exam topic and almost never used in production.
XA
The X/Open XA specification defines the interface between a transaction manager (coordinator) and resource managers (databases, some message brokers). Java's JTA builds on it. PostgreSQL exposes the participant side as PREPARE TRANSACTION / COMMIT PREPARED (disabled unless max_prepared_transactions is set above zero); MySQL has XA START ... XA PREPARE ... XA COMMIT.
XA can be reasonable inside a single application talking to two databases it owns. Across microservices it is a poor fit: services expose HTTP/gRPC APIs, not XA resources; many managed databases and most streaming systems (Kafka included) are not XA participants; and orphaned prepared transactions hold locks and, in PostgreSQL, block vacuum from cleaning up old row versions.
TCC: Try-Confirm-Cancel
TCC moves the two phases into business APIs. Each participant exposes three operations:
- Try: check and reserve. For the savings account: verify balance, move $500 from
availabletofrozen. For the wallet: create a pending credit. - Confirm: consume the reservation (remove the frozen amount, make the credit available). Must be idempotent and must not fail for business reasons — Try already validated.
- Cancel: release the reservation. Must be idempotent.
If any Try fails or times out, the coordinator moves to CANCELLING and calls Cancel on all participants, retrying until each acknowledges. Two edge cases bite every TCC implementation:
- Empty rollback: Try timed out and never actually executed, but Cancel arrives. The participant must record "T1 cancelled" and return success, rather than error out.
- Hanging (suspended) Try: the delayed Try arrives after the Cancel. Because the participant recorded the cancel, it must reject this Try; otherwise it freezes funds that will never be released.
A participant-side record per global transaction ID handles both:
CREATE TABLE tcc_branch (
global_tx_id text NOT NULL,
branch text NOT NULL, -- 'freeze_savings'
state text NOT NULL, -- TRIED, CONFIRMED, CANCELLED
amount_minor bigint NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (global_tx_id, branch)
);
Try inserts TRIED (fails if a CANCELLED row exists); Cancel upserts CANCELLED and releases funds only if the previous state was TRIED; Confirm moves TRIED → CONFIRMED, and is a no-op if already CONFIRMED. Each runs in the same local transaction as the balance change. Frameworks such as Seata (Java) and DTM (Go) implement the coordinator and these barrier checks.
TCC suits money because the reservation is visible and intentional: the customer sees "$500 pending", other transfers cannot spend the frozen amount, and no database lock spans the network.
What goes in Try, and where the status lives
For a $100 transfer from A to C, Try could touch A, C or both. Only one arrangement is safe:
| What Try does | Safe? | Why |
|---|---|---|
| Debit or freeze A; nothing on C until Confirm | Yes | The money is out of reach before anyone can spend it. Cancel just returns it to A, which cannot fail for lack of funds. |
| Credit C; debit A later | No | C can spend the $100 before A's leg fails, so Cancel may find nothing to take back. |
| Debit A and credit C at once | No | If the credit lands and the debit fails, you are back in the row above. |
The rule is take before you give, and it holds for saga step order too. The real danger is spendable money: the savings-to-wallet example above is safe because its wallet Try creates only a pending credit that nobody can use until Confirm.
Status table placement. The coordinator persists each global transaction: every participant's Try status, the chosen second phase (Confirm or Cancel) and its progress. The wallet design in System Design Interview Vol. 2 keeps this table in the database of the account being debited. That lets the coordinator record the transfer and run the debit leg in one local transaction, so a crash can never leave money taken from A with no record of why.
Saga
A saga (Garcia-Molina & Salem, 1987) is a sequence of local transactions T1 … Tn. If Tk fails, the saga runs compensating transactions Ck-1 … C1 in reverse. Each local transaction commits immediately, so there are no distributed locks — and no isolation.
Compensation is semantic, not a rollback. You cannot un-send an email or un-charge a card; you send a correction or issue a refund. Some compensations cost money (refund fees) or are visible (an SMS saying the order was cancelled), which influences step order.
Step types (terminology from Chris Richardson's Microservices Patterns):
- Compensatable — can be undone (reserve stock → release stock).
- Pivot — the go/no-go point. If it succeeds, the saga will run to completion; if it fails, compensate everything before it.
- Retriable — after the pivot; guaranteed to succeed eventually with retries (idempotent), so they never need compensation.
Order steps as: compensatable steps first, then the pivot, then retriable steps.
Orchestration vs choreography
Orchestration: a saga orchestrator owns a persisted state machine and sends commands to each service.
Choreography: no central controller; each service reacts to events and emits its own.
Orchestration makes the flow explicit, gives one place to see "where is order 9876 stuck?", and centralizes timeouts and retries — at the cost of a component that knows every step. Choreography decouples services but scatters the flow across subscriptions; beyond a few steps it becomes hard to answer "what happens if X fails after Y?" Workflow engines (Temporal, Camunda, AWS Step Functions) are orchestration with durable state built in.
Isolation problems and countermeasures
Because each step commits, other requests can observe or interfere with a half-finished saga:
- Dirty read: a fraud check reads stock reserved by a saga that later compensates.
- Lost update: saga A reserves the last unit, saga B's compensation overwrites the count.
- Fuzzy read: a step re-reads data another saga changed in between.
Countermeasures:
- Semantic lock: mark records with a status (
order.status = PENDING,funds.frozen) that other operations respect — reject, wait, or treat as unavailable. This is the most common one. - Commutative updates: design operations so order doesn't matter (increment/decrement instead of set; ledger entries instead of balance overwrites).
- Pessimistic view: reorder steps so the riskiest updates happen in retriable steps (e.g., award loyalty points after the pivot, not before).
- Reread value: before updating, verify the record hasn't changed (optimistic version check), and abort/restart if it has.
- By value: choose the mechanism per request based on risk — a $20 order can run as a loose saga; a $50,000 transfer goes through a stricter flow.
Choosing for money transfer and checkout
Internal transfer, same ledger: one transaction inserting balanced entries — see Double-Entry Ledger Design.
Internal transfer across ledgers (savings → wallet): TCC with a freeze, or an orchestrated saga through a transit (suspense) account — debit savings to transit (local tx), credit wallet from transit (local tx), and if the credit ultimately fails, reverse the first leg. The transit account's balance is a live measure of in-flight money and must return to zero; reconciliation alerts if it doesn't. Every step carries the transfer ID as an idempotency key and is published via the outbox.
Interbank transfer: there is no transaction across banks. You send a payment message (for example an ISO 20022 credit transfer), mark the transfer SENT, handle status reports asynchronously, query status on timeout, and reconcile against settlement — see Bank Transfer System and Reconciliation & Settlement.
TCC or saga by latency budget. A saga runs its steps one after another, so its latency is roughly the sum of the steps. TCC sends all Tries in parallel, then all Confirms, so it costs about two rounds of the slowest participant. For a two-party transfer either is fine; with many participants and a tight latency budget, TCC wins.
Checkout: orchestrated saga.
| Step | Type | Compensation |
|---|---|---|
Create order PENDING (semantic lock) | Compensatable | Mark CANCELLED |
| Reserve stock (with TTL) | Compensatable | Release reservation |
| Apply voucher | Compensatable | Un-redeem voucher |
| Authorize payment | Compensatable | Void authorization |
| Confirm order | Pivot | — |
| Capture payment, award points, notify, hand to fulfilment | Retriable | — (retry until success, alert if stuck) |
Authorizing before confirming means the expensive-to-undo step (capture) happens only after the pivot; voiding an authorization is cheaper and less visible than refunding a capture. See Cart & Checkout and Order Management & State Machines.
Trade-offs
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| Local ACID transaction | Atomic, isolated, simplest | Requires data in one database | Always, if you can draw boundaries this way |
| 2PC / XA | Atomic across resources; familiar semantics | Blocking on coordinator failure; locks across network; limited support | Few resources inside one trust boundary; distributed SQL internals |
| 2PC over consensus (Spanner, CockroachDB) | ACID across shards without single-node blocking | Higher write latency; vendor-specific | You want a distributed database to handle it |
| TCC | Explicit reservations; no long DB locks; good for money | Three APIs per participant; empty-rollback and hanging-try handling; coordinator needed | Funds or quota that must be visibly held before commit |
| Orchestrated saga | Explicit, auditable flow; central timeouts and retries | Orchestrator is a dependency; no isolation without countermeasures | Multi-step business flows: checkout, onboarding, cross-ledger transfers |
| Choreographed saga | Loose coupling; no central component | Hard to trace and change; cyclic event chains | Short flows (2–3 steps) owned by few teams |
In practice
A minimal orchestrator in Go — persist state after every step, compensate in reverse on failure:
package saga
import (
"context"
"errors"
"fmt"
)
type Step struct {
Name string
Action func(ctx context.Context, sagaID string) error
Compensate func(ctx context.Context, sagaID string) error // nil for pivot and retriable steps
}
type Store interface {
MarkDone(ctx context.Context, sagaID, step string) error
MarkCompensated(ctx context.Context, sagaID, step string) error
SetStatus(ctx context.Context, sagaID, status string) error
}
var ErrCompensationFailed = errors.New("saga: compensation failed, manual action required")
// Run executes steps in order. Actions and compensations must be idempotent:
// after a crash, a recovery worker re-runs Run from the persisted position.
func Run(ctx context.Context, st Store, sagaID string, steps []Step) error {
for i, s := range steps {
if err := s.Action(ctx, sagaID); err != nil {
if cerr := compensate(ctx, st, sagaID, steps[:i]); cerr != nil {
return errors.Join(err, cerr)
}
_ = st.SetStatus(ctx, sagaID, "COMPENSATED")
return fmt.Errorf("step %s: %w", s.Name, err)
}
if err := st.MarkDone(ctx, sagaID, s.Name); err != nil {
return fmt.Errorf("persist %s: %w", s.Name, err)
}
}
return st.SetStatus(ctx, sagaID, "COMPLETED")
}
func compensate(ctx context.Context, st Store, sagaID string, done []Step) error {
for i := len(done) - 1; i >= 0; i-- {
s := done[i]
if s.Compensate == nil {
continue
}
if err := s.Compensate(ctx, sagaID); err != nil {
_ = st.SetStatus(ctx, sagaID, "COMPENSATION_FAILED")
return fmt.Errorf("%w: %s: %v", ErrCompensationFailed, s.Name, err)
}
_ = st.MarkCompensated(ctx, sagaID, s.Name)
}
return nil
}
Real systems add: retries with backoff per step, a step timeout, a recovery worker that resumes sagas stuck in a non-terminal state, and a manual-intervention queue for COMPENSATION_FAILED. This is exactly what Temporal or a similar workflow engine gives you, which is why many teams adopt one instead of hand-rolling.
Operational knobs:
- Deadlines per saga. A checkout saga stuck in
PENDINGfor more than ≈ 15 minutes (pick a business number) should time out and compensate; stock reservations should carry their own TTL as a backstop. - Observability: emit an event per step with the saga ID; dashboards for sagas by state and age; alert on
COMPENSATION_FAILEDand on transit-account balance not returning to zero. - Audit: the persisted saga log is also your evidence of what happened to the customer's money — keep it as long as the transaction records.
Common pitfalls
- Dual writes disguised as a saga. Updating the database and then calling another service with no outbox or retry: a crash between them leaves the saga half-done with nobody to resume it. Symptom: orders stuck
PENDINGforever. - Non-idempotent steps or compensations. Retries after timeouts debit twice or release stock twice. Symptom: negative reservations, double refunds.
- Compensations that can fail for business reasons. "Refund" fails because the card is closed. Compensations must be retriable or have a fallback (credit to wallet, manual payout).
- No semantic lock. Other flows read reserved stock or frozen funds as available. Symptom: oversell or overdraft while sagas are in flight.
- Capturing before the pivot. Refunding a captured payment costs fees and customer trust compared to voiding an authorization.
- Choreography sprawl. Ten services reacting to each other's events with no owner. Symptom: nobody can explain why an order was cancelled; event cycles.
- Orphaned XA/prepared transactions. Symptom: rows locked for hours, PostgreSQL table bloat because vacuum cannot advance.
Interview angle
- Typical prompt: "Transfer money between two services with separate databases" or "design checkout across order, inventory and payment".
- Strong answer: first question whether the data can live in one ledger; if not, explain why 2PC is avoided across microservices (blocking, coupling, support); propose TCC or an orchestrated saga; define each step's compensation and type (pivot!); add idempotency keys, outbox, timeouts, semantic locks, reconciliation and a manual-intervention path; describe what the customer sees at each state.
- Follow-ups to expect: "What if the compensation fails?" "What if the orchestrator crashes mid-saga?" "How do other requests see a half-finished transfer?" "Why not just use Kafka transactions?" (they cover Kafka-internal read-process-write, not your databases or external PSPs.)
- Red flags: "use 2PC across the microservices"; compensations that "delete the row"; no mention of idempotency; a saga without timeouts; treating an interbank transfer as if it could be atomic.
Self-check
1. Why does 2PC block, and what exactly is blocked?
After voting yes, a participant has promised to commit if asked and cannot abort on its own, but it doesn't know the decision until the coordinator tells it. If the coordinator fails after collecting votes, prepared participants keep their transaction open, holding locks on the affected rows, until the coordinator recovers. Other transactions on those rows wait behind them.
2. How do Spanner and CockroachDB use 2PC without the classic blocking problem?
The coordinator and each participant are replicated groups (Paxos/Raft), not single machines. The commit decision is written to a replicated log, so if a node fails another replica of the group takes over and completes the protocol. Blocking only happens if a whole group loses its majority.
3. Explain empty rollback and hanging Try in TCC, and how a participant handles both.
Empty rollback: Cancel arrives for a Try that never executed (it timed out before arriving). Hanging Try: that delayed Try arrives after the Cancel. The participant keeps a per-global-transaction record: Cancel writes CANCELLED even if no Try happened and returns success; Try checks for an existing CANCELLED record and refuses. Both run in the same local transaction as the business change.
4. What is a pivot transaction, and how does it shape step order?
It is the step whose success commits the saga to completing: steps before it are compensatable, steps after it are retriable and will be retried until they succeed. You place cheap, invisible, easily undone steps before the pivot and expensive or customer-visible ones (capture, notifications, points) after it.
5. Scenario: checkout's payment authorization succeeds but the orchestrator crashes before recording it. What happens on recovery?
The recovery worker resumes the saga from its last persisted step and re-sends the authorize command with the same idempotency key. The payment service recognizes the key and returns the original authorization result rather than authorizing again. The orchestrator records the step and continues to the pivot. Without the idempotency key, the customer would have two authorizations.
6. Orchestration or choreography for a 7-step loan disbursement? Justify.
Orchestration. With seven steps, compensations and regulatory audit requirements, you need one place that holds the state machine, enforces timeouts, decides compensations and answers "where is application 123?" Choreography would scatter that logic across seven services' event handlers and make change and incident analysis hard.
7. Name three saga isolation countermeasures and give a banking example of one.
Semantic lock, commutative updates, pessimistic view (also reread value and by value). Semantic lock example: the transfer saga moves $500 into a frozen bucket with status PENDING; balance checks for other payments use available = balance − frozen, so the in-flight amount cannot be spent twice.
8. In a TCC transfer from A to C, why does Try debit or freeze A instead of crediting C?
If C is credited first and A's leg then fails, Cancel must take the money back from C, who may already have spent it. Debiting or freezing A first keeps the money out of everyone's reach, and Cancel just returns it to A, which always succeeds. A credit in Try is acceptable only as a pending entry that Confirm makes spendable.
Exercise
Design and implement the savings-to-wallet transfer:
- Model two PostgreSQL databases (savings, wallet). Write the schema for accounts, frozen funds and a
tcc_branchtable. - Implement Try/Confirm/Cancel endpoints for each service in Go with idempotency, empty-rollback and hanging-try handling.
- Implement a coordinator that persists the global transaction state and retries Confirm/Cancel with backoff.
- Fault-inject: kill the coordinator after Try succeeds on both; delay the savings Try past its timeout so Cancel arrives first; return 500 from wallet Confirm three times.
- Then sketch the same flow as an orchestrated saga with a transit account and compare: what does the customer see, and what does reconciliation check?
Done when: after 1,000 randomized runs with faults, the sum of all balances (including frozen and transit) is unchanged and no funds remain frozen for completed or cancelled transfers.
Further reading
- Hector Garcia-Molina & Kenneth Salem, "Sagas" (SIGMOD 1987).
- Chris Richardson, Microservices Patterns (Manning), ch. 4 "Managing transactions with sagas".
- Martin Kleppmann, Designing Data-Intensive Applications, ch. 9 (atomic commit and 2PC).
- Jim Gray & Andreas Reuter, Transaction Processing: Concepts and Techniques.
- Pat Helland, "Life beyond Distributed Transactions: an Apostate's Opinion" (CIDR 2007).
- Caitie McCaffrey, "Distributed Sagas: A Protocol for Coordinating Microservices" (talk).
- PostgreSQL documentation:
PREPARE TRANSACTION. - Temporal documentation: saga pattern and durable execution.
Related
- Transactional Outbox & CDC — reliable step-to-step messaging.
- Idempotency & Exactly-Once — required by every step and compensation.
- Microservices Patterns — sagas among other service patterns.
- Double-Entry Ledger Design — local atomic transfers and transit accounts.
- Cart & Checkout — the checkout saga in context.
- Bank Transfer System — end-to-end transfer design.
- Ch 11 · Payment System — book notes on payment consistency.
- Ch 12 · Digital Wallet — TC/C and saga across Raft-replicated, event-sourced shards.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).