Lab 02: Distributed Transactions

Time: 50 minutes | Level: Architect | DB: MySQL 8.0 (XA), Python3 Saga


🎯 Objective

Master distributed transaction patterns: Two-Phase Commit (2PC) with its failure modes, Saga pattern (choreography vs orchestration), and XA transactions in MySQL. Build a Python3 Saga orchestrator with compensating transactions.


πŸ“š Background

Distributed transactions span multiple databases/services. Two main approaches:

Two-Phase Commit (2PC)

Phase 1 β€” PREPARE:
  Coordinator β†’ all participants: "Can you commit?"
  Participants: lock resources, write to WAL, reply YES/NO

Phase 2 β€” COMMIT/ROLLBACK:
  If all YES β†’ Coordinator: "COMMIT"
  If any NO  β†’ Coordinator: "ROLLBACK"

2PC Problems:

  • Blocking problem: If coordinator fails after PREPARE, participants hold locks indefinitely

  • Single point of failure: Coordinator crash = all participants stuck

  • Performance: Two round trips + fsync on each participant

Saga Pattern

Instead of distributed lock, break transaction into local transactions + compensating transactions:

Property
2PC
Saga

Consistency

Strong (ACID)

Eventual (BASE)

Isolation

Full

None (dirty reads possible)

Failure recovery

Automatic rollback

Compensating transactions

Coupling

Tight

Loose

Performance

Slow (locks)

Fast (no distributed locks)

Use case

Financial, inventory

Order flow, microservices


Step 1: Start MySQL for XA Demo

πŸ“Έ Verified Output:


Step 2: XA Transaction β€” Success Path

πŸ“Έ Verified Output:

πŸ“Έ Verified Output:


Step 3: XA Transaction β€” Rollback Path

πŸ“Έ Verified Output:


Step 4: 2PC Failure Mode Simulation

πŸ“Έ Verified Output:


Step 5: Saga Pattern β€” Orchestration

πŸ“Έ Verified Output:


Step 6: Saga Choreography Pattern

πŸ“Έ Verified Output:


Step 7: XA Transactions β€” Recovery

πŸ“Έ Verified Output:


Step 8: Capstone β€” Pattern Selection Framework

πŸ“Έ Verified Output:


Summary

Concept
Key Takeaway

2PC Phase 1

PREPARE: participants lock resources and vote YES/NO

2PC Phase 2

COMMIT or ROLLBACK based on unanimous YES

2PC Blocking Problem

Coordinator crash after prepare = participants stuck with locks

MySQL XA

XA START β†’ XA END β†’ XA PREPARE β†’ XA COMMIT/ROLLBACK

XA RECOVER

Shows prepared but uncommitted transactions (orphan detection)

Saga Orchestration

Central coordinator + compensating transactions on failure

Saga Choreography

Event-driven, services react to each other's events

Compensating Transactions

Business-level undo (e.g., refund) not database-level rollback

Idempotency

Saga steps must be safe to retry; use idempotency keys

πŸ’‘ Architect's insight: Most microservice systems use Sagas, not 2PC. The key is designing compensating transactions that are themselves idempotent and always succeed.

Last updated