Intermediate → Advanced22 min read· Topic 6.4

Distributed transactions

2PC, 3PC, Saga pattern, distributed locking, optimistic vs pessimistic concurrency

🔗Key Takeaways

  • 1
    2PC (Two-Phase Commit): coordinator asks all participants to prepare, then commit/abort — blocking if coordinator fails
  • 2
    3PC adds a pre-commit phase to reduce blocking, but doesn't solve network partitions
  • 3
    Saga pattern replaces 2PC with a chain of local transactions + compensating actions
  • 4
    In practice, avoid distributed transactions when possible — design for eventual consistency

Atomic Operations Across Services

In a monolith, database transactions are ACID. In microservices, an 'order' spans multiple services (order service, inventory, payment). How do you ensure either all succeed or all rollback? This is the distributed transaction problem.

Phase 1: Prepare

Coordinator sends PREPARE to all participants. Each participant executes the transaction locally, writes to a log, and responds VOTE_COMMIT or VOTE_ABORT.

If ANY participant votes ABORT, the coordinator sends ROLLBACK to all.

Distributed Transaction Approaches

ApproachConsistencyAvailabilityComplexityUse Case
2PCStrongLow (blocking)MediumTraditional databases (XA)
3PCStrongBetter than 2PCHighTheoretical, rarely used
Saga (Choreography)EventualHighMediumEvent-driven microservices
Saga (Orchestration)EventualHighMediumWorkflow-heavy systems
Eventual ConsistencyEventualHighestLowMost microservice systems

Advantages

  • 2PC provides strong consistency across nodes
  • Saga pattern works well for microservices
  • Well-understood failure modes

Disadvantages

  • 2PC blocks on coordinator failure
  • Saga compensating transactions are complex to implement
  • Distributed transactions are always slower than local ones

🧪 Test Your Understanding

Knowledge Check1/1

What is 2PC's biggest weakness?