Managing Distributed Transactions

1. Two-Phase Commit Pattern

PhaseAction
1. PrepareCoordinator asks all participants to prepare; each votes commit/abort
2. Commit/AbortIf all voted commit → coordinator says commit; else abort
ProsStrong ACID across resources
ConsBlocks on coordinator failure; poor scalability; not internet-friendly
Warning: Avoid 2PC across microservices — prefer Saga. 2PC is acceptable only within a single trusted infrastructure (e.g., XA across DBs in same DC).

2. Three-Phase Commit Pattern

PhaseAction
1. CanCommitVote phase
2. PreCommitAcknowledge readiness; participants prepare locally
3. DoCommitFinal commit
ImprovementReduces blocking on coordinator failure
CostMore messages; still assumes synchronous network

3. Try-Confirm-Cancel Pattern

PhaseAction
TryReserve resources (e.g., hold inventory, freeze funds)
ConfirmApply the change atomically using reservation
CancelRelease reservation if any participant fails

Example: TCC Inventory

// Try
ReservationId r = inventory.reserve(productId, qty, ttl=30s);
// Confirm
inventory.confirm(r);
// or Cancel (auto-expires after TTL)
inventory.cancel(r);

4. Reservation Pattern

AspectDetail
DefinitionTentatively hold resource; commit or release later
TTLAuto-release after expiry to avoid leaks
ExamplesHotel room hold, seat selection, OAuth authorization code

5. Saga Pattern vs 2PC

2PC (XA)

  • Strong ACID across services
  • Blocking; coordinator SPOF
  • Tight coupling; sync only
  • Poor cloud/internet fit

Saga

  • Eventual consistency, no global lock
  • Async, non-blocking, scalable
  • Loose coupling; works over WAN
  • Compensations & isolation work needed
ChooseWhen
2PCSingle trust boundary; ACID essential; small participant count
SagaMicroservices; high scale; tolerant of eventual consistency

6. Compensating Transaction Pattern

RuleDetail
Inverse EffectSemantically undoes a committed step
RecordedLogged for audit and replay
IdempotentSafe to retry
Best-EffortSide-effects (emails) may be irreversible

7. Outbox Pattern

AspectDetail
PurposeAtomically commit business state + intent to publish event
MechanismInsert into outbox table in same DB tx
RelayPolling publisher OR CDC tail forwards to broker
SolvesDual-write problem (DB + broker)

8. Transaction Coordinator Pattern

ResponsibilityDetail
Tracks Tx StateDurable record of in-flight tx
Drives PhasesPrepare/commit (2PC) or saga steps
RecoveryOn crash, reads log and resumes
ExamplesAtomikos, Bitronix (XA); Temporal, Camunda (saga)

9. Distributed Lock Pattern

PropertyRequirement
Mutual ExclusionOnly one holder at a time
Lease/TTLAuto-release if holder dies
Fencing TokenMonotonic ID to prevent stale-lock writes
ToolsRedis Redlock, ZooKeeper, etcd, Consul

Example: Redis Lock

// SET key value NX PX 30000
String token = UUID.randomUUID().toString();
boolean acquired = redis.set("lock:order:123", token, "NX", "PX", 30000);
try {
    if (acquired) doWork();
} finally {
    // Release only if we still own it (Lua script)
    redis.eval("if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('del',KEYS[1]) end",
               1, "lock:order:123", token);
}

10. Fencing Token Pattern

AspectDetail
DefinitionMonotonically increasing token issued with each lock acquisition
UseResource server rejects writes with stale (smaller) token
SolvesGC pause / network delay causing stale lock holder to write

Fencing Token Flow

Client A: lock → token=33 → (GC pause)
Client B: lock → token=34 → write(token=34) → STORAGE
Client A: write(token=33) → REJECTED (33 < 34)