Columns › 4. Reliability › Part 18
Choosing a Distributed Transaction: 2PC, 3PC, TCC and Saga
分散式交易怎麼選:2PC、3PC、TCC 與 Saga
One order changes three services’ databases, and without a distributed transaction you are left with stock reserved but no payment. Starting from local transactions and the consistency spectrum, this article walks through 2PC, 3PC, TCC and sagas: flow, guarantees, cost, failure cases and where each fits, with a Go TCC participant that handles empty rollbacks and suspension, a comparison table and a decision flow.
In this article
- What this article solves
- Step 1: Local and distributed transactions
- Step 2: The consistency spectrum and CAP
- Step 3: Two-phase commit (2PC)
- Step 4: Three-phase commit (3PC)
- Step 5: The TCC model
- Step 6: TCC’s three classic problems: idempotency, empty rollback, suspension
- Step 7: A TCC participant in Go
- Step 8: Sagas: long flows and external systems
- Step 9: Two ways to avoid a distributed transaction
- Step 10: Comparing and choosing
- Common pitfalls
- Key takeaways
- References
- Next
The previous article, “Kafka: Core Concepts and What to Watch Out For”, delivered events reliably to downstream services; but delivery is only half of the story. When one order has to change the order, inventory and payment databases at once, who guarantees that they either all succeed or are all undone? This article is a decision guide: it first explains why distributed transactions are needed at all, then compares 2PC, 3PC, TCC and sagas one by one: which scenario each fits, why, and when not to use it at all. The next article then implements the most common of them, the saga together with the outbox, in Go.
What this article solves
The shop's ordering flow looks like this: api-gateway passes the request to order, order creates the order, inventory reserves the items, and payment charges the customer through an external payment provider. Following the rule that each service owns its data, the three services each have their own PostgreSQL database, and amounts are always stored as int64 minor units.
Without any coordination, every step is a local transaction committed on its own, and a failure anywhere in between leaves a half-done state:
Figure: T1 and T2 have already committed in their own databases, and T3, the charge, failed or timed out; the three databases know nothing of each other’s state, and nobody is responsible for undoing the first two steps.
Two things are worth noticing in this diagram. First, “committed” in the two boxes on the left really means written to disk: it is too late for ROLLBACK, and the only way to undo it is to make another change. Second, the worst case on the right is not a failure but a timeout: the payment service may already have taken the money from the provider and only the reply was lost. The table lists the usual half-done states:
| Failure happens | State left behind | What customers or the business see |
|---|---|---|
| After reserving stock, before charge | Stock reserved, order neither paid nor cancelled | The item shows as sold out but was never sold |
| Charge succeeds, reply is lost | Provider charged, order still pending | The customer paid, but the order shows as unpaid |
| After charge, before confirming | Money taken, order cancelled by a timeout job | Manual refunds and a busy support line |
| Retries without idempotency | Stock reserved twice, customer charged twice | Overselling and double charges |
A “distributed transaction” is exactly this: one business action has to change several independent data sources (different databases, different services, even systems outside the company), and we still want some degree of “all or nothing”. This article answers:
- How local and distributed transactions differ, and which levels of consistency you can choose from.
- The flow of two-phase commit (2PC), XA support in databases, and why it blocks.
- What three-phase commit (3PC) tries to fix, and why almost nobody uses it in practice.
- TCC’s Try/Confirm/Cancel, resource reservation, and the three classic problems of idempotency, empty rollback and suspension, with a Go implementation and tests.
- Saga compensation, orchestration versus choreography, and the isolation sagas lack.
- Two ways to avoid distributed transactions: the transactional outbox, and redrawing service boundaries.
- One big comparison table and a decision flow, mapped to real cases in the shop.
Step 1: Local and distributed transactions
Inside a single database, the database takes care of ACID on its own: atomicity comes from the transaction log (WAL), which lets a group of changes commit or be discarded together; isolation comes from locks or multi-version concurrency control, so other transactions cannot see uncommitted changes; durability comes from writing the log before replying. In “database/sql, Transactions and Connection Pools in Go”, BeginTx/Commit/Rollback gave us all of this because there was one participant, one log and one lock manager.
Once data is spread across several databases, none of those three things is shared any more:
- No common log: the inventory database may have committed while the payment database has not; the two commits are separate events, and any failure can happen between them.
- No common locks: a lock released by the inventory service is invisible to the payment service; other requests can read “half” of the work between the two commits.
- The network makes outcomes unknown: a timeout does not mean failure; the other side may have finished and only the reply was lost. This is the most fundamental difficulty in distributed systems, as “Timeouts, Retries and Circuit Breakers” discussed.
So every distributed transaction scheme is essentially answering the same question: without a common log and common locks, what do we use instead, and what price are we willing to pay?
One thing to clear up first: two schemas in the same PostgreSQL database (say orders and billing) do not need a distributed transaction; one local transaction can write to both schemas. A PostgreSQL transaction cannot span databases (another database in the same cluster), and only then do you meet a distributed transaction.
Step 2: The consistency spectrum and CAP
“Consistent” means different strengths in different contexts, so before choosing a scheme, decide which level the business needs. The diagram puts the schemes in this article on one axis:
Figure: the further left, the stronger the consistency, but the lower the availability and the more it is confined to databases you run yourself; the further right, the more it tolerates failures and external systems, at the cost of intermediate states being visible.
Reading from left to right, each step gives up some guarantees in exchange for some flexibility: 2PC uses locks so that nobody sees an intermediate state; TCC does not lock rows but “reserves” resources for the transaction; a saga does not even require a reservation, it acts first and compensates on failure; the outbox does not need anyone else to succeed together with it, only that the notification eventually arrives. The same levels as a table:
| Level | Meaning | Typical schemes |
|---|---|---|
| Atomic commit | All participants commit or roll back together; no intermediate state is visible | Local transactions, 2PC/XA |
| Reservation-based | Hold the resources first (nobody else can use them), take effect on confirm | TCC |
| Eventual consistency | Intermediate states are visible; consistency is reached after time and compensations | Sagas, outbox plus events |
| Best effort | Failures are left alone and fixed by hand or by reconciliation | No coordination (not recommended for payments) |
The CAP theorem says that when the network is partitioned, a system can only choose between consistency and availability. Partitions will happen sooner or later in a distributed system, so this trade-off has to be faced:
- 2PC chooses consistency: when the coordinator or a participant is unreachable, the transaction stops and waits; it would rather be unavailable than inconsistent.
- Sagas and the outbox choose availability: each service completes its own part, and the unreachable part is caught up later, at the price of inconsistency for a while.
- TCC sits in between: the Try phase needs every participant online, but after the reservation, Confirm/Cancel can be retried at leisure.
This is often framed as ACID versus BASE (Basically Available, Soft state, Eventually consistent). The point is not which is better, but which data cannot tolerate any window of inconsistency, and which can tolerate seconds or hours.
Step 3: Two-phase commit (2PC)
2PC is the closest thing to “moving a local transaction onto several databases”. It introduces a coordinator (the transaction manager) and splits the commit into two phases:
Figure: in phase 1 every participant prepares and votes; only after the coordinator has written its decision to its log does phase 2 tell everyone to commit. The bars show how long participants hold their locks.
- Prepare (vote): the coordinator sends PREPARE to every participant. A participant performs all its changes, makes them durable in its log, keeps all its locks and answers “yes”; if it cannot, it answers “no” and rolls back on its own. Having answered yes, the participant loses the right to decide by itself: it has promised that it will be able to commit whenever the coordinator says so.
- Commit: if everyone says yes, the coordinator first writes the “COMMIT” decision to its own durable log, then tells every participant to commit; if anyone says no or times out, it tells everyone to roll back.
Guarantees: genuine atomicity and isolation. Locks are held from prepare to commit, so nobody else sees an intermediate state.
Cost: at least two network round trips plus two forced log writes; lock hold time grows from “one local transaction” to “the slowest participant plus two round trips”.
The failure cases are where 2PC really hurts:
| When the failure happens | Result |
|---|---|
| A participant fails before preparing | The coordinator gets no vote, times out and rolls everyone back: safe |
| The coordinator crashes after a participant voted yes | The participant is in doubt: it can neither commit nor roll back, and waits holding locks |
| The coordinator crashes after logging the decision, before sending it | On recovery it reads its log and resends the decision; until then participants are stuck |
| A participant is briefly unreachable in phase 2 | The coordinator keeps resending until it is back; the others have committed: brief inconsistency |
The second row is what is meant by blocking: a stuck transaction keeps the affected rows locked, and every later request touching those rows queues up behind it. If the coordinator is a single point, the availability of the whole system is tied to it.
XA support in databases: XA is the distributed transaction interface defined by X/Open. MySQL supports it with statements such as XA START, XA END, XA PREPARE and XA COMMIT; PostgreSQL provides the participant-side commands:
-- postgresql.conf: max_prepared_transactions defaults to 0 (disabled); raise it and restart to use this
BEGIN;
UPDATE accounts SET balance = balance - 50000 WHERE id = 'ops-adjust';
PREPARE TRANSACTION 'adj-20261120-0042-payments';
-- from here the transaction is detached from the connection: if the connection drops
-- or the server restarts, it still exists and still holds its locks
-- after the coordinator decides (may run from another connection):
COMMIT PREPARED 'adj-20261120-0042-payments';
-- or ROLLBACK PREPARED 'adj-20261120-0042-payments';
-- find stuck prepared transactions
SELECT gid, prepared, database FROM pg_prepared_xacts ORDER BY prepared;The PostgreSQL documentation stresses that PREPARE TRANSACTION is meant for external transaction managers, not for applications to call directly; a forgotten prepared transaction keeps holding its locks and also prevents VACUUM from reclaiming space. Go’s standard library has no XA transaction manager: the coordinator, its decision log and recovery are yours to write or to hand to a framework.
Where it fits:
- All participants are databases you run yourself that support XA, the transactions are short and few, and the business requires that no inconsistency is ever visible.
- For example the shop’s manual back-office adjustments: support moves an amount from a suspense account to a customer’s store credit, which must change both the
paymentsdatabase and the finance team’s separateledgerdatabase. There are a few dozen of these a day, each touching two or three rows, and strong consistency matters more than throughput. - Brief dual writes during a data migration: the old and new databases must be updated together, and the arrangement is removed once the migration is done.
Where it does not fit: the cross-service ordering flow (high volume, and lock time stretched by the slowest service), any flow that includes an external system (a third-party payment provider will never take part in your 2PC), message queues and most NoSQL stores (no XA). And before choosing 2PC, ask one question: could these two databases be merged into one? If so, a local transaction solves the problem.
Step 4: Three-phase commit (3PC)
3PC, proposed in the early 1980s, is an attempt to remove 2PC’s blocking. It inserts a PreCommit phase between voting and committing, and lets participants decide on their own after a timeout:
Figure: CanCommit asks, PreCommit prepares to commit, DoCommit commits; a participant that has received PreCommit but times out waiting for DoCommit commits on its own.
- CanCommit: the coordinator asks whether the participants can commit; they only check and answer Yes or No.
- PreCommit: if all say Yes, the coordinator sends PreCommit; participants get ready to commit and reply ACK. The point of this step is that every participant now knows “everyone agreed”.
- DoCommit: the coordinator sends the actual commit.
The key is the timeout rule: a participant that loses the coordinator before receiving PreCommit aborts on its own; one that has received PreCommit knows that everyone voted Yes, so after a timeout it commits on its own. That way participants do not wait forever when the coordinator crashes.
Why it is rarely used:
- It is unsafe under network partitions. Suppose the network splits in two after the coordinator has sent PreCommit: the side that received PreCommit commits after its timeout, the side that did not aborts after its timeout, and the data is inconsistent. 3PC’s non-blocking property rests on the assumption that network delay is bounded and that nodes only stop rather than get cut off, and real networks do not satisfy it.
- One more round trip: higher latency than 2PC, and locks are held even longer.
- No mainstream implementation: common databases and transaction managers implement 2PC (XA), not 3PC.
In practice, the way to make 2PC non-blocking is different: use a consensus algorithm (Paxos, Raft) to replicate the coordinator and each participant into highly available groups, so that when one node fails, another in its group takes over. Google Spanner runs 2PC on top of Paxos groups. For an ordinary shop, 3PC is worth understanding for its idea and its limits, but it will not appear on the list of options.
Step 5: The TCC model
TCC moves 2PC’s two phases from the database layer up to the business layer: each participant exposes three operations, called by a TCC transaction manager (usually the service that starts the flow).
- Try: check the business rules and reserve resources. Stock is not deducted directly; the quantity moves from “available” to “reserved”. Store credit is not deducted directly; it is “frozen”. When Try ends, its local transaction has committed and no database locks are held.
- Confirm: turn the reservation into the real effect. It only uses what Try reserved and runs no further business checks, so in business terms it should not fail; if it fails technically (network, crash), it is retried.
- Cancel: release the reservation and give the resources back.
Figure: the order service starts a global transaction, sends Try to the inventory and payment services to reserve, and only once all succeed sends Confirm; if any Try fails or times out, it sends Cancel to every participant.
Compare this diagram with the 2PC one: the shape is almost identical, “ask everyone, then confirm together”, and the difference lies in what the bars stand for. In 2PC the bars are database locks, and any other transaction touching those rows has to queue; in TCC the bars merely mean “the stock table has 2 more reserved items, and the wallet has one more frozen amount”. When Try ends, its local transaction has already committed, and other orders can still buy the remaining stock.
Guarantees: once Try succeeds, the resources belong exclusively to this transaction (others already see less available stock), so Confirm always has something to confirm, and you never get the saga situation of “deducted, found it was not enough, compensated back”. This is business-level isolation: the reservation is visible to others, but they cannot use it.
Cost:
- Highly invasive: every participant has to be reworked to expose three operations, and its tables need extra columns such as “reserved quantity” or “frozen amount”, plus a branch record table.
- The transaction manager must persist its state: the global transaction ID (xid), its branches and the current phase must be written to a database, and after a crash it must carry on sending Confirm or Cancel. This is the same thing as the 2PC coordinator’s log.
- The Try phase needs every participant online, so availability is lower than with a saga; but since no database locks are held, a slow Confirm/Cancel only delays releasing the reservation and blocks nobody.
How it differs from a saga: each saga step “really does it”, and failures are offset by compensations; TCC’s Try only “holds it”, and the real effect waits for Confirm. So TCC never shows others data that was “deducted and later added back”, and never has a non-compensable step like “the email has already been sent”.
Where it fits:
- Limited resources that must never be oversold or overused and must be held before confirming: stock in a limited sale, a single-use coupon, store credit or a wallet balance.
- For example the shop’s limited-edition orders: the order service acts as the transaction manager, sends Try to the inventory service to reserve the SKU, Try to the payment service to freeze store credit, and Try for the right to use the coupon; only if all succeed does it Confirm. If any one fails, the other reservations are released immediately, and you never end up with “stock deducted but the coupon unusable”.
- All participants are internal services your team can change, and the flow is short (seconds).
Where it does not fit: participants are external systems you cannot change (a third-party payment provider has no Try operation for you), flows are long (waiting for a user to pay may take tens of minutes, and reservations cannot be held that long), or the business has no natural notion of a “reservation”. Note that many card payment providers offer “authorise first, capture later”: authorisation holds the amount, capture actually takes it, and voiding the authorisation releases it. Semantically this is a Try/Confirm/Cancel offered by an external system; whether you can use it depends on which operations your provider supports.
Step 6: TCC’s three classic problems: idempotency, empty rollback, suspension
The TCC flow looks simple; the real difficulty is the uncertainty of the network: messages are resent, delayed and reordered. Every participant has to handle three situations:
Figure: a Try is delayed in the network, and the transaction manager times out and sends Cancel first; the participant has no Try record, performs an empty rollback and records the cancellation; when the late Try arrives, it sees that record and is rejected.
- Idempotency: the transaction manager resends whenever it gets no reply, so Try, Confirm and Cancel for the same xid can all arrive twice. A repeated Confirm must not deduct twice, and a repeated Cancel must not give back twice. The solution is to record the branch state keyed by xid and check it first on every request.
- Empty rollback: the Try has not arrived yet (network delay, or the participant was just restarting) when the transaction manager times out and sends Cancel. The participant finds no Try record, and Cancel must then report success; otherwise the transaction manager keeps retrying a Cancel that can never succeed. Some frameworks call this “allowing empty compensation”.
- Suspension: after the empty rollback, the delayed Try finally arrives. If the participant reserved as usual, nobody would ever Confirm or Cancel that reservation (the global transaction is already over), and the stock would be held forever. So an empty rollback must leave a “cancelled” record, and Try must check for it first and refuse when it is there.
Put together as a state table, each participant operation only looks at “the current branch state of this xid”:
| Current state | Try arrives | Confirm arrives | Cancel arrives |
|---|---|---|---|
| No record | Reserve, record tried | Error (should not happen) | Empty rollback: record cancelled, succeed |
| tried | Succeed (idempotent) | Deduct the reservation, record confirmed | Release the reservation, record cancelled |
| confirmed | Succeed (idempotent) | Succeed (idempotent) | Error (should not happen) |
| cancelled | Reject (no suspension) | Error (should not happen) | Succeed (idempotent) |
The “should not happen” cells mean a bug in the transaction manager or corrupted data; log them and raise an alert instead of quietly handling them. Seata in the Java ecosystem and DTM in the Go ecosystem both build these checks in (DTM calls it a branch barrier). If you implement it yourself you must have them too, and the branch record must be written in the same local transaction as the business change, or you are back to the dual write problem.
Step 7: A TCC participant in Go
Below is the inventory service’s TCC participant, in internal/inventory/tcc/. To keep the logic directly runnable and testable, it simulates the two tables with in-memory maps; with PostgreSQL, each method becomes one local transaction and the structure stays the same.
// Package tcc shows the inventory service as a TCC participant: Try reserves, Confirm deducts, Cancel releases.
package tcc
import (
"errors"
"sync"
)
// State is the state of a branch transaction (the part of a global transaction that runs in this service)
type State int
const (
Tried State = iota + 1
Confirmed
Cancelled
)
var (
ErrBadQty = errors.New("quantity must be greater than 0")
ErrInsufficient = errors.New("insufficient stock")
ErrRejected = errors.New("already cancelled, late Try rejected") // prevents suspension
ErrNotTried = errors.New("no Try record, cannot Confirm")
ErrConflict = errors.New("state conflict")
)
type branch struct {
SKU string
Qty int64
State State
}
// Inventory simulates two tables in memory: stock (available and reserved) and branch records.
// In practice each method is one local transaction: read the branch record by its xid primary key
// (SELECT ... FOR UPDATE), check its state, then update stock and the branch record in the same transaction.
type Inventory struct {
mu sync.Mutex
available map[string]int64
reserved map[string]int64
branches map[string]*branch // key: global transaction ID (xid)
}
func NewInventory(stock map[string]int64) *Inventory {
inv := &Inventory{
available: map[string]int64{},
reserved: map[string]int64{},
branches: map[string]*branch{},
}
for sku, n := range stock {
inv.available[sku] = n
}
return inv
}
// Try checks and reserves stock. A repeated Try simply succeeds; an xid that was already cancelled is always rejected (prevents suspension).
func (inv *Inventory) Try(xid, sku string, qty int64) error {
if qty <= 0 {
return ErrBadQty
}
inv.mu.Lock()
defer inv.mu.Unlock()
if b, ok := inv.branches[xid]; ok {
if b.State == Cancelled {
return ErrRejected
}
return nil // already tried or confirmed: idempotent
}
if inv.available[sku] < qty {
return ErrInsufficient
}
inv.available[sku] -= qty
inv.reserved[sku] += qty
inv.branches[xid] = &branch{SKU: sku, Qty: qty, State: Tried}
return nil
}
// Confirm deducts the reserved quantity for good. It only uses what Try reserved and runs no further business checks.
func (inv *Inventory) Confirm(xid string) error {
inv.mu.Lock()
defer inv.mu.Unlock()
b, ok := inv.branches[xid]
switch {
case !ok:
return ErrNotTried
case b.State == Confirmed:
return nil // repeated Confirm: idempotent
case b.State == Cancelled:
return ErrConflict
}
inv.reserved[b.SKU] -= b.Qty
b.State = Confirmed
return nil
}
// Cancel releases the reservation. With no Try record it is an empty rollback: record Cancelled and report success.
func (inv *Inventory) Cancel(xid string) error {
inv.mu.Lock()
defer inv.mu.Unlock()
b, ok := inv.branches[xid]
if !ok {
inv.branches[xid] = &branch{State: Cancelled} // empty rollback; the record makes a late Try fail
return nil
}
switch b.State {
case Cancelled:
return nil // repeated Cancel: idempotent
case Confirmed:
return ErrConflict
}
inv.available[b.SKU] += b.Qty
inv.reserved[b.SKU] -= b.Qty
b.State = Cancelled
return nil
}
// Stock returns the available and reserved quantity of a SKU
func (inv *Inventory) Stock(sku string) (available, reserved int64) {
inv.mu.Lock()
defer inv.mu.Unlock()
return inv.available[sku], inv.reserved[sku]
}A few design points:
- Every decision is based on the branch record, not guessed from stock numbers. Idempotency, empty rollback and suspension protection for Try, Confirm and Cancel all live in the few lines at the top of each method that look up the branch record.
- Confirm does not check stock: the resources were reserved in Try, and Confirm only turns “reserved” into “deducted”, so it cannot fail in business terms.
- An empty rollback still writes a record: when
Cancelfinds no branch, it inserts aCancelledone, and that single line handles both the empty rollback and suspension.
The tests run each case once, including 50 concurrent Try calls competing for 10 items:
package tcc
import (
"errors"
"fmt"
"sync"
"testing"
)
func assertStock(t *testing.T, inv *Inventory, wantAvail, wantRes int64) {
t.Helper()
if a, r := inv.Stock("SKU-1"); a != wantAvail || r != wantRes {
t.Fatalf("available %d, reserved %d; want %d, %d", a, r, wantAvail, wantRes)
}
}
func TestTryConfirmIsIdempotent(t *testing.T) {
inv := NewInventory(map[string]int64{"SKU-1": 10})
for range 2 { // a resent Try does not reserve twice
if err := inv.Try("x1", "SKU-1", 3); err != nil {
t.Fatal(err)
}
}
assertStock(t, inv, 7, 3)
for range 2 { // a resent Confirm does not deduct twice
if err := inv.Confirm("x1"); err != nil {
t.Fatal(err)
}
}
assertStock(t, inv, 7, 0)
if err := inv.Cancel("x1"); !errors.Is(err, ErrConflict) {
t.Fatalf("Cancel after Confirm should be ErrConflict, got %v", err)
}
}
func TestTryCancelReleases(t *testing.T) {
inv := NewInventory(map[string]int64{"SKU-1": 10})
if err := inv.Try("x1", "SKU-1", 3); err != nil {
t.Fatal(err)
}
for range 2 {
if err := inv.Cancel("x1"); err != nil {
t.Fatal(err)
}
}
assertStock(t, inv, 10, 0)
}
func TestEmptyRollbackThenLateTry(t *testing.T) {
inv := NewInventory(map[string]int64{"SKU-1": 10})
// Try is still in flight; the coordinator timed out and sent Cancel first: the empty rollback must succeed
if err := inv.Cancel("x1"); err != nil {
t.Fatalf("empty rollback should succeed, got %v", err)
}
// the late Try must be rejected, or its reservation would never be released (suspension)
if err := inv.Try("x1", "SKU-1", 3); !errors.Is(err, ErrRejected) {
t.Fatalf("got %v, want ErrRejected", err)
}
assertStock(t, inv, 10, 0)
if err := inv.Confirm("x2"); !errors.Is(err, ErrNotTried) {
t.Fatalf("got %v, want ErrNotTried", err)
}
}
func TestTryNeverOversells(t *testing.T) {
inv := NewInventory(map[string]int64{"SKU-1": 10})
var wg sync.WaitGroup
var mu sync.Mutex
ok := 0
for i := range 50 {
wg.Add(1)
go func() {
defer wg.Done()
if inv.Try(fmt.Sprintf("x%d", i), "SKU-1", 1) == nil {
mu.Lock()
ok++
mu.Unlock()
}
}()
}
wg.Wait()
if ok != 10 {
t.Fatalf("%d reservations succeeded, want 10", ok)
}
assertStock(t, inv, 0, 10)
}$ go test -race ./internal/inventory/tcc/
ok example.com/shop/internal/inventory/tcc 1.273sWith PostgreSQL, the branch record is a table keyed by xid. The primary key conflict itself handles concurrent Try and Cancel: whichever arrives first inserts successfully, and the later one waits for the first to commit and then gets the conflict.
CREATE TABLE tcc_branch (
xid text PRIMARY KEY,
sku text, -- empty-rollback records have no sku or qty
qty bigint,
state text NOT NULL, -- tried / confirmed / cancelled
updated_at timestamptz NOT NULL DEFAULT now()
);
-- Try (one transaction)
BEGIN;
INSERT INTO tcc_branch (xid, sku, qty, state) VALUES ($1, $2, $3, 'tried')
ON CONFLICT (xid) DO NOTHING;
-- 0 rows affected: a record exists; ROLLBACK and answer from its state (reject if cancelled, else a repeated success)
UPDATE inventory SET reserved = reserved + $3
WHERE sku = $2 AND stock - reserved >= $3;
-- 0 rows affected: insufficient stock; ROLLBACK, and the branch record disappears with it
COMMIT;
-- Cancel (one transaction): first try to write the empty-rollback record; only release an existing reservation
BEGIN;
INSERT INTO tcc_branch (xid, state) VALUES ($1, 'cancelled')
ON CONFLICT (xid) DO NOTHING;
SELECT sku, qty, state FROM tcc_branch WHERE xid = $1 FOR UPDATE;
-- run the next two lines only when state = 'tried'
UPDATE inventory SET reserved = reserved - $qty WHERE sku = $sku;
UPDATE tcc_branch SET state = 'cancelled', updated_at = now() WHERE xid = $1;
COMMIT;This reuses the inventory model from “Distributed Transactions: Sagas and the Outbox Pattern”: stock is the physical stock, reserved is the reserved quantity, and the sellable quantity is the difference; Confirm subtracts qty from both stock and reserved. The external interface can be three gRPC methods, each carrying the xid; the xid itself is the idempotency key, the same concept as the idempotency keys in “Idempotency and Distributed Locks”.
Step 8: Sagas: long flows and external systems
A saga gives up atomicity and isolation across services in exchange for availability and flexibility: a chain of local transactions T1 … Tn, each of which really commits; when a step fails, the compensations of the earlier steps, Cn-1 … C1, run in reverse order.
Figure: after the external provider declines the authorisation, the orchestrator first releases the stock and then marks the order cancelled; while the bar lasts, other requests can see the reserved stock and the pending order.
Read the diagram from top to bottom: T1 and T2 have already committed in their own databases; T3 goes through the payment service to the external provider, is declined, and the failure travels back to the orchestrator; the orchestrator enters compensation and, in reverse, first runs C2 to release the stock and then C1 to cancel the order. Compared with the TCC diagram, there is no Confirm step here: each step takes effect as soon as it is done, and undoing it is only possible through a compensation.
There are two ways to organise one: in orchestration, a coordinator issues commands in order and remembers how far the saga has got; in choreography, there is no centre, and each service decides the next step when it hears the previous step’s event. Core transactional flows usually use orchestration, because the compensation order is clear and “where is this order stuck” is answered by one state table; peripheral reactions (notifications, points, reports) use choreography. The detailed comparison and the Go implementation are in the next article.
Guarantees: as long as every compensation eventually succeeds, the system ends up in one of two states, “all done” or “all undone”. It does not guarantee isolation: after T2 and before C2, other requests can see the reserved stock and the pending order.
Cost:
- Every step needs a compensation, and a compensation is a new business action (a refund is a new payment record, not the deletion of the charge); it must be idempotent and retried until it succeeds.
- Non-compensable actions (sending an email, shipping) must be placed after the pivot step, and only run once there is no way back.
- You must deal with the lack of isolation: use a semantic lock such as
pendingto tell other flows “not settled yet”, use increments rather than overwrites, and reread to confirm before the critical step. - The orchestrator must persist saga state, handle steps whose outcome is unknown, and give the whole saga a deadline.
Failure cases: a compensation itself fails (retry, alert, and eventually hand over to a human); the outcome is unknown (a charge timed out: first query with the idempotency key and compensate only once you are sure nothing was taken); two sagas see each other’s intermediate states and act on them wrongly (for example, a return is requested for an order that is still pending).
Where it fits:
- Long flows across several services that include external systems: the shop’s normal ordering flow is the classic case. The payment provider is a third party, and the user may have to complete 3-D Secure or go and pay at a convenience store, so the whole flow takes anything from seconds to hours. It cannot be locked with 2PC, nor is it a good fit for TCC holding stock until hours later (although “reserve stock” inside the saga is itself a kind of reservation, it has a deadline, and on expiry a compensation releases it automatically).
- Many teams are involved, services evolve independently, and you do not want them all to be online at the same moment.
- The business can accept brief intermediate states, and every step has a sensible reverse action.
Where it does not fit: flows where an intermediate state causes harm as soon as anyone sees it and cannot be fenced off with a status field; steps that can neither be compensated nor moved later; or flows that really only “write one database and tell the others”, where the outbox is enough.
Step 9: Two ways to avoid a distributed transaction
Many requirements that look like they need a distributed transaction stop needing one after a change of design. Before choosing 2PC, TCC or a saga, check these two routes.
Route one: the transactional outbox. If the requirement is only “change my own data and let others know”, there is no second participant that has to commit together, only the dual write problem between the database and the message. Write the event to an outbox table in the same database, commit it in the same local transaction as the business data, let a relay send it, and the event is guaranteed to be delivered at least once; consumers remove duplicates with an inbox or another idempotency mechanism. For example, after an order is paid, the points service must be told to add points: points arriving a few seconds late do not matter, and they do not need to live or die with the order. The full approach is in “Distributed Transactions: Sagas and the Outbox Pattern”, and the commands and replies between saga steps travel through an outbox anyway.
Route two: redraw the boundaries. If two pieces of data always change together and cannot tolerate any window of inconsistency, that is often a sign the boundary is in the wrong place: they belong to the same service and the same database. As “When to Split: Service Boundaries and Decomposition Strategies” discussed, service boundaries should follow consistency boundaries. Examples:
- If the record of “which order used this coupon” lives in the order database with
UNIQUE (coupon_id), one local transaction guarantees a coupon is used only once; the coupon service remains responsible for defining and issuing coupons. - A wallet’s balance and its transaction history always live in the same database and are updated in the same transaction; do not split them into two services.
- Being able to “reserve” stock is itself a design that splits one big transaction into small ones: placing an order only needs the local “reserve” transaction inside the inventory service.
A third, often overlooked option is reconciliation. Even with a saga or TCC, payments still need regular comparison of your own records with the provider’s and the bank’s, to catch the differences that slipped past every mechanism. “Payment Pitfalls: Double Charges, Callbacks and Reconciliation” covers this in detail.
Step 10: Comparing and choosing
The four schemes and the outbox side by side:
| Aspect | 2PC/XA | 3PC | TCC | Saga | Outbox plus local transaction |
|---|---|---|---|---|---|
| Consistency | Strong (atomic commit) | Aims to be non-blocking; may diverge under partitions | Eventual, but resources reserved before confirming | Eventual | Eventual (one-way notification) |
| Isolation | Yes, locks held until commit | As 2PC | Business level: reservations unusable by others, state visible | None, intermediate states visible | None |
| Latency | Two round trips; lock time set by the slowest | Three round trips | Two business calls (Try, Confirm) | One call per step; flows may take hours | Local transaction plus async delivery |
| Availability | All participants must be online; a coordinator crash blocks | Less blocking, but no mainstream implementation | All online for Try; Confirm/Cancel can retry | High; downstream can catch up later | High; writes work while the broker is down |
| Complexity | Simple business code; operations must handle in-doubt transactions | High | High: three operations plus idempotency, empty rollback, suspension | Medium: compensations, state machine, deadlines | Low |
| Intrusiveness | Low, but needs XA support | High | High: every participant changes | Medium: every step needs a compensation | Low |
| External systems | No | No | Only if they offer something similar (authorise/capture) | Yes | Yes (as an event source) |
| Typical use | Few, short, strongly consistent operations on internal databases | Understand the idea only | Reserving limited stock, coupons, balances | Long cross-service flows with external payments | Write data and notify other services |
When choosing, ask the questions below in order; the first “yes” is your answer:
Figure: first see whether redrawing boundaries allows a local transaction, then whether an outbox is all you need, then consider 2PC and TCC in turn; everything else uses a saga.
Mapped to the shop:
| Scenario | Choice | Why |
|---|---|---|
| Order, order lines and status history | Local transaction | Same service, same database: do not split |
| Telling points and reporting that an order was paid | Outbox plus idempotent consumers | One-way notification; a few seconds late does not matter |
| Manual back-office adjustments (payments and ledger) | 2PC, or first consider merging the databases | Few, short, internal PostgreSQL, no window of inconsistency allowed |
| Limited editions: stock plus coupon plus store credit | TCC | No overselling, no coupon reuse, all participants internal, flow in seconds |
| Normal orders: order, stock, external payment, shipping | Orchestrated saga | External systems, flows that may take hours; failures handled by compensations and deadlines |
Using several schemes in the same system is normal: the unit of choice is one business flow, not the whole system.
Common pitfalls
- Treating two schemas in the same database as a distributed transaction. One local transaction can span schemas; bringing in 2PC or a saga only adds complexity.
- Using 2PC for the cross-service main flow. Lock time is stretched by the slowest service, a coordinator crash freezes every affected row, and an external payment provider cannot take part anyway.
- Leaving prepared transactions unattended. PostgreSQL prepared transactions survive restarts, keep holding locks and get in VACUUM’s way; monitor
pg_prepared_xactsfor entries that have been there too long. - Believing 3PC solves blocking. Under a network partition it lets the two sides reach opposite decisions; if you need a highly available coordinator, replicate it with a consensus algorithm instead of switching to 3PC.
- Returning an error when a TCC Cancel finds no Try. The transaction manager will retry a Cancel that can never succeed, forever; an empty rollback must report success.
- Not recording empty rollbacks. A late Try then reserves successfully, and nobody ever releases that reservation (suspension).
- Writing the branch record and the business change in two transactions. A crash in between gives you “stock reserved, no record”, and every idempotency check stops working.
- Running business checks again in Confirm. Confirm should only use what Try reserved; discovering in Confirm that there is not enough defeats the purpose of TCC.
- Treating saga compensations as database rollbacks. A compensation is a new business action that leaves a record and can fail; it must be idempotent and retried until it succeeds.
- Ignoring that sagas have no isolation. Other flows read a
pendingorder and act on it; use status fields to state clearly that it is not settled yet. - Compensating straight away when the outcome is unknown. A charge timing out does not mean nothing was charged; query with the idempotency key first, or you may end up shipping nothing while keeping the money.
- Using a saga or TCC just to publish an event. For one-way notification, an outbox is enough.
Key takeaways
- The root problem of distributed transactions is the lack of a common log and common locks, plus a network that can leave outcomes “unknown”; every scheme is a different substitute with a different price.
- Decide first which level of consistency the business needs: atomic commit, reservation-based, or eventual; under a network partition you can only choose between consistency and availability.
- 2PC/XA provides atomicity and isolation at the cost of blocking and availability; it only suits few, short operations on databases you run yourself.
- 3PC reduces blocking with PreCommit and timeout rules, but is unsafe under network partitions and has no mainstream implementation; in practice the coordinator is replicated with a consensus algorithm instead.
- TCC moves the two phases to the business layer: Try reserves, Confirm confirms, Cancel releases; it suits short flows that must not oversell and whose participants can all be changed; idempotency, empty rollback and suspension must all be solved in the branch record table.
- A saga really commits each step and compensates in reverse on failure, without isolation; it suits long cross-service flows that include external systems.
- Consider avoiding distributed transactions first: use an outbox for one-way notification, keep data that always changes together in one service, and back payments up with reconciliation.
References
- PREPARE TRANSACTION (PostgreSQL documentation): prepared transactions are meant for external transaction managers, and leftover ones hold locks and block VACUUM, used in step 3.
- SAGAS (Garcia-Molina and Salem, 1987): a saga is a sequence of local transactions, each with a compensating transaction, used in step 8.
- Pattern: Saga (microservices.io): orchestrated and choreographed sagas and their lack of isolation, used in step 8.
- Saga Design Pattern (Azure Architecture Center): pivot transactions, compensation, and countermeasures for missing isolation such as semantic locks and commutative updates, used in step 8.
- Seata TCC Mode (Apache Seata documentation): the Try, Confirm and Cancel model and the idempotence, empty rollback and hanging problems, used in steps 5 and 6.
- Exceptions and subtransaction barriers (DTM documentation): the subtransaction barrier for duplicate requests, empty rollbacks and hanging, used in step 6.
- Pattern: Transactional outbox (microservices.io): writing business data and the event in one local transaction, used in step 9.
- Perspectives on the CAP Theorem (Gilbert and Lynch): the trade-off between consistency and availability under network partitions, used in step 2.
Next
Once a scheme is chosen, it has to be made reliable. The next article, “Distributed Transactions: Sagas and the Outbox Pattern”, takes the shop’s most common ordering flow and implements an orchestrated saga with compensations in Go, then uses a transactional outbox and a relay to make data and events succeed together, and finally an inbox so that consumers can handle duplicates safely.