Isolation Levels & Distributed Sagas
How distributed systems maintain data integrity without locking the world. Master ACID Isolation Levels (Dirty Reads to Serializable), 2-Phase Commit (2PC) locking bottlenecks, and the Distributed Saga Pattern (Choreography vs Orchestration).
โ๏ธ 1. The Core Intuition: The Vacation Booking Dilemma
Imagine booking a holiday package touching 3 independent companies:
1. Airline Service: Charges $500 for the flight.
2. Hotel Service: Charges $400 for the resort room.
3. Rental Car Service: Fails because all cars are sold out!
In a monolithic SQL database, you would simply type ROLLBACK; and everything resets instantly. But in microservices, the Airline and Hotel are separate third-party services with their own databases! What do you do?
Lock the airline seat, hotel room, and car simultaneously. If the car company's network stalls, all seats and rooms stay locked forever!
๐จ The Flaw: Blocking synchronous locks kill performance and cause cascading timeouts.Execute each local transaction sequentially. When the car rental fails, automatically trigger Compensating Transactions ($C_2$: Refund Hotel, $C_1$: Refund Airline) in reverse!
๐ก๏ธ The Advantage: Non-blocking, highly available, and resilient across distributed microservices.๐ 2. Single-Node ACID Isolation Levels & Concurrency Anomalies
Before solving distributed transactions, we must understand the 4 ANSI SQL isolation levels on a single database:
| Isolation Level | Dirty Read | Non-Repeatable Read | Phantom Read | Mechanism |
|---|---|---|---|---|
| Read Uncommitted | โ ๏ธ Allowed | โ ๏ธ Allowed | โ ๏ธ Allowed | No read locks. Reads uncommitted writes that may abort. |
| Read Committed | โ Prevented | โ ๏ธ Allowed | โ ๏ธ Allowed | Reads only committed data (PostgreSQL/Oracle default). |
| Repeatable Read | โ Prevented | โ Prevented | โ ๏ธ Allowed | Snapshot Isolation using Multi-Version Concurrency (MVCC) (MySQL default). |
| Serializable | โ Prevented | โ Prevented | โ Prevented | Two-Phase Locking (2PL) or Serializable Snapshot Isolation (SSI). |
๐ญ 3. Saga Architecture: Choreography vs Orchestration
Microservices emit and listen to Kafka events without a central coordinator. Service A emits OrderCreated $\implies$ Service B reacts and emits PaymentAuthorized.
A dedicated Saga Orchestrator (e.g. Temporal.io, AWS Step Functions) coordinates every step via RPC, tracking execution state in a durable database.
๐ป 4. Production Saga Orchestrator Implementation (Multi-Language)
Here is the production implementation of a resilient Saga Orchestrator with automated compensating rollback across 5 languages:
# Python Async Saga Orchestrator with Compensations class OrderSagaOrchestrator: def __init__(self): self.compensations = [] async def execute(self, order_id: str, amount: float): try: # Step 1: Create Order await order_service.create(order_id, amount) self.compensations.append(lambda: order_service.cancel(order_id)) # Step 2: Authorize Payment payment_id = await payment_service.charge(order_id, amount) self.compensations.append(lambda: payment_service.refund(payment_id)) # Step 3: Reserve Inventory (May Fail!) await inventory_service.reserve(order_id) self.compensations.append(lambda: inventory_service.release(order_id)) return "SAGA_COMPLETED" except Exception as e: # Rollback in reverse order for compensate in reversed(self.compensations): await compensate() raise Exception(f"Saga Failed, rolled back: {e}")
๐งช 5. Interactive Lab: Live 4-Step Distributed Saga Simulator
E-Commerce Saga Orchestrator Lab
๐ฏ 6. Test Your Understanding
You are architecting an 8-step banking loan approval system with complex business rules, human approvals, and 24-hour timeouts. Should you use Saga Choreography (Kafka events) or Saga Orchestration (Temporal)?
Why do high-throughput cloud microservices avoid 2-Phase Commit (2PC) in favor of Sagas?