Module 6 - Distributed Systems

Distributed Transactions

Coordinating atomic operations across multiple services or databases.

1The Wedding Ceremony Analogy

Simple Analogy
A wedding requires both parties to say "I do." If one says no, no marriage happens. The officiant coordinates: asks both, waits for both answers, then declares the outcome. That's Two-Phase Commit (2PC).

A distributed transaction spans multiple nodes/services. The challenge: ensuring all participants commit or all abort-atomicity across network boundaries.

2Two-Phase Commit (2PC)

The Classic Approach

P1
Prepare
Coordinator asks all participants: 'Can you commit?' Each votes YES or NO.
P2
Commit/Abort
If all vote YES, coordinator sends COMMIT. If any votes NO, coordinator sends ABORT.
Pros
  • ✓ Strong consistency (ACID)
  • ✓ All-or-nothing guarantee
Cons
  • ✗ Blocking-holds locks during prepare
  • ✗ Coordinator is single point of failure
  • ✗ Doesn't scale well

3Real-World Dry Run: Order + Payment + Inventory

Scenario: E-commerce checkout with 2PC

1
Coordinator: PREPARE
Ask Order Service, Payment Service, Inventory Service
2
Order Service: YES
Order record created, locked
3
Payment Service: YES
Payment authorized, locked
4
Inventory Service: NO
Out of stock!
5
Coordinator: ABORT
All services rollback. Order deleted, payment released.

Problem: If coordinator crashes between PREPARE and COMMIT, participants are stuck waiting with locks held.

4Alternatives to 2PC

Saga Pattern

Sequence of local transactions with compensating actions. No global locks.

Use case: Long-running business processes

Learn more →

TCC (Try-Confirm-Cancel)

Try reserves, Confirm commits, Cancel releases. Business-level locking.

Use case: Reservation systems

Outbox Pattern

Write to DB + outbox in one transaction. Separate process publishes events.

Use case: Event-driven microservices

Event Sourcing

Store events, derive state. Natural audit trail and replay.

Use case: Financial systems

Learn more →

5Key Takeaways

1Distributed transactions ensure atomicity across services
22PC: strong consistency but blocking and doesn't scale
3Saga: eventual consistency with compensating actions
4Most microservices avoid 2PC-use Saga or TCC
5Choose based on consistency requirements vs latency

?Quiz

1. 2PC coordinator crashes after PREPARE. What happens to participants?

2. Microservices checkout: order, payment, shipping. Best approach?