SteelReed

Search

Search posts, questions…

7. System Design

Distributed transactions: 2PC, TCC, saga, pivot transactions and the transactional outbox

Why cross-service transactions never give true strong consistency, the consistency ladder from 2PC, AT, TCC and 2-phase messages down to saga, orchestration vs choreography, pivot transactions, countermeasures for a saga's missing isolation, and two myths: distributed transactions raise TPS, and the outbox solves distributed transactions.

18 Nov 20269 min readSenior

–

1. The problem

Placing an order must decrement stock in Inventory, charge in Payment and create the order in Order: three databases, no shared BEGIN ... COMMIT. The first version saves the order and then calls kafka.send: the broker fails 2 seconds after commit, and 340 saved orders never reach inventory to reserve stock.

2. Key idea

Across services we only try to keep atomicity (all or nothing). Each step commits locally right away, so other sagas see half-done state: isolation is gone. Fewer global locks mean better scaling, but the application does more work.

Model How Use when Don't use when
2PC / XA a coordinator, prepare then commit, locks held throughout few participants, all XA-capable, low load Kafka, Redis, partner APIs (no XA)
TCC Try reserves, Confirm uses, Cancel releases money, stock, seats resources that can't be reserved
Saga local transactions, compensating backwards on failure many steps and services, eventual consistency is fine you need immediate cross-service consistency
Outbox the message goes into an outbox table in the same transaction, a relay publishes it writing the DB and emitting events treating it as a way to commit several services together

2.1 How should saga steps be ordered?

  • Pivot: make the step most likely to fail (payment) the pivot, or put it early.
  • Hard-to-undo steps (emails, irreversible partner calls) go after the pivot and retry until done.
  • Compensation isn't rollback: a refund is a new transaction that can fail and must be idempotent.
  • Countermeasures for missing isolation: semantic locks (APPROVAL_PENDING), versioned updates, value-adding steps (loyalty points) after the pivot.
  • 2–3 linear steps: choreography (each service listens to events). From 4–5 steps, with branches, timeouts or money to audit: orchestration (Temporal, Camunda). Put a saga_id on every event.

3. In Java

JAVA
@Transactional
public Order place(PlaceOrder cmd) {
    Order order = orders.save(Order.pending(cmd));                      // semantic lock: PENDING
    outbox.save(new OutboxEvent(order.id(), "OrderPlaced", toJson(order)));  // same transaction
    return order;                                                       // no kafka.send here
}
 
@Scheduled(fixedDelay = 500)
void relay() {
    for (OutboxEvent e : outbox.findUnsent(100)) {                       // FOR UPDATE SKIP LOCKED
        kafka.send("orders", e.aggregateId(), e.payload()).join();       // at least once
        outbox.markSent(e.id());
    }
}
 
@KafkaListener(topics = "orders")
@Transactional
void onOrderPlaced(OrderPlaced evt) {
    if (!processed.insertIfAbsent(evt.eventId())) return;                // idempotent consumer
    inventory.reserve(evt.items());
}

The relay can send duplicates if it dies after send and before markSent, so consumers must be idempotent. Debezium reading the WAL/binlog replaces a hand-written relay. Other languages: the same pattern applies in Go and Node.js; Temporal has SDKs for Go, TypeScript and Java.

Where 2PC blocks, and the three TCC traps
  • 2PC: participants answer "yes" in prepare and then hold locks waiting for commit. If the coordinator dies now, they wait forever (blocking). Phase 2 doesn't happen at the same instant everywhere, so clients can still read inconsistent state between commits.
  • TCC trap 1, empty rollback: Cancel arrives before Try ran (Try timed out in transit). Cancel must notice and do nothing.
  • TCC trap 2, hanging: Try arrives after Cancel; it must be refused, or the resource stays reserved forever.
  • TCC trap 3, idempotency: Confirm and Cancel may be called repeatedly.
  • Distributed transactions don't make systems faster: the goal is correctness; TPS only rises when data is already split and contention is low.

4. Working with AI

Hand to AI: a table of saga steps with compensations, outbox setup with Debezium, tests for failures at each step.

Check yourself in AI-written code:

  • No save() followed by kafka.send() in one method without an outbox.
  • Every step before the pivot has a compensation; every step after it has retries.
  • All consumers and compensations are idempotent (a processed_event table).
  • Irreversible partner calls come after the pivot and carry an idempotency key.
  • Every event carries a saga_id and a trace id.

5. Exercises

Exercise 1: Review the AI's order placement

The AI says "consistency is guaranteed because of @Transactional". List the ways data can diverge and fix it.

JAVA
@Transactional
public Order place(PlaceOrder cmd) {
    Order order = orders.save(Order.create(cmd));
    kafka.send("orders", order.id(), toJson(order));
    paymentClient.charge(order.id(), order.total());   // HTTP
    return order;
}
Solution 1
  • kafka.send runs before commit: if commit fails the event is already out and inventory reserves stock for a nonexistent order. If commit succeeds and the broker fails, it's the reverse.
  • paymentClient.charge inside the transaction: payment succeeds and then commit fails means money taken with no order; slow HTTP holds the connection and locks.
  • Fix: save a PENDING order and an outbox row in one transaction; payment becomes a saga step (the pivot) run by an orchestrator or consumer with an idempotency key; the result comes back as an event that moves the order to CONFIRMED or triggers compensation.

Exercise 2: Design an order saga

Steps: create the order, reserve stock, charge, add loyalty points, create a shipment with a delivery partner (irreversible). Order them, mark the pivot and compensations, choose choreography or orchestration.

Solution 2
# Step Compensation Kind
1 Order: PENDING order (semantic lock) REJECTED compensable
2 Inventory: reserved += qty release the reservation compensable
3 Payment: charge pivot
4 Inventory: reserved → sold retry
5 Loyalty: add points (after the pivot, so they're never clawed back) retry
6 Shipping: create the shipment with an idempotency key retry
7 Order: CONFIRMED retry

Seven steps with money and an external partner: choose orchestration. A user cancelling before the pivot makes the orchestrator compensate 2 then 1; after the pivot it's a separate refund flow.

Summary

  • Across services only atomicity survives; isolation is lost.
  • 2PC holds locks through two phases and blocks when the coordinator dies.
  • Saga: local transactions + compensations; the pivot splits "compensable" from "retry until done".
  • Compensation is a new transaction and must be idempotent.
  • An outbox solves dual writes, not distributed transactions.

Further reading: Service boundaries.

Practice interview questions on this topic

All Microservices questions →All Messaging & Kafka questions →

Loading comments…
Next on the roadmapCommunication in system design, part 1: a message's journey, Protobuf, REST or gRPC