The Saga Pattern: Distributed Transactions & Compensations
Because 2PC locks tables and kills availability, modern microservices use the Saga Pattern. Sagas break distributed operations into local transactions paired with explicit compensating actions that execute in reverse order if a downstream step crashes 📜🔙.
class SagaStep:
def __init__(self, name, action, compensate):
self.name = name
self.action = action
self.compensate = compensate
executed_steps = []
trace = []
def book_flight(): trace.append("FLIGHT_BOOKED")
def cancel_flight(): trace.append("FLIGHT_CANCELLED")
def book_hotel(): raise RuntimeError("Hotel fully booked! 🛑")
def cancel_hotel(): pass
saga = [
SagaStep("Flight", book_flight, cancel_flight),
SagaStep("Hotel", book_hotel, cancel_hotel)
]
for step in saga:
try:
step.action()
executed_steps.append(step)
except Exception:
for done in reversed(executed_steps):
done.compensate()
break
print(f"Saga Compensation Trace: {trace} 🛡️")
# 39. The Saga Pattern: Distributed Transactions & Compensations Holding database locks across HTTP microservices is an anti-pattern. If the payment gateway takes 8 seconds to respond while holding a row lock in your inventory database, your entire checkout system grinds to a dead halt 🛑. ```python # The Saga Flow: # Step 1: Charge Card -> SUCCESS # Step 2: Reserve Seat -> SUCCESS # Step 3: Book Hotel -> OUT OF CAPACITY (FAIL) # Compensate Step 2: Unreserve Seat # Compensate Step 1: Refund Card ``` ### Saga Architecture Principles 1. **Eventual Consistency**: Instead of global ACID atomicity, Sagas embrace eventual consistency. Each service commits locally to its private database immediately. 2. **Compensating Actions**: A compensation is not a raw database rollback. It is a new forward business transaction that semantically reverses previous work (e.g. issuing a credit memo or sending an apology email) 🔙. 3. **Orchestration vs Choreography**: - **Orchestrated Saga**: A central coordinator process triggers each service step and manages the failure state machine. - **Choreographed Saga**: Services emit and listen to event bus topics (e.g. Kafka) without a central conductor 🚀. --- ### Interactive Pop-Quiz 🧠 #### What is the primary operational difference between 2PC and the Saga Pattern for distributed transactions? - [ ] Sagas commit local transactions immediately and rely on compensating actions to undo them rather than holding long global locks 📜 - [ ] Sagas run exclusively on single Redis nodes without network communication - [ ] 2PC cannot handle more than 2 database servers simultaneously - [ ] Sagas require specialized hardware cryptographic chips to sign payloads --- ### Practical Challenge 🎯 Implement a saga execution runner `execute_saga(steps)` where each step has `action()` and `compensate()`. Create 3 steps: Step 1 (charge $50), Step 2 (reserve inventory), Step 3 (generate shipping label, which raises RuntimeError). Steps append `'CHARGE'`, `'RESERVE'`, `'UNRESERVE'`, `'REFUND'` to an audit log. Run the saga and print the resulting audit log. <details> <summary>Solution</summary> ```python class SagaStep: def __init__(self, action, compensate): self.action = action self.compensate = compensate def execute_saga(steps): executed = [] for step in steps: try: step.action() executed.append(step) except Exception: for s in reversed(executed): s.compensate() return "FAILED" return "SUCCESS" audit = [] s1 = SagaStep(lambda: audit.append("CHARGE"), lambda: audit.append("REFUND")) s2 = SagaStep(lambda: audit.append("RESERVE"), lambda: audit.append("UNRESERVE")) def fail_ship(): raise RuntimeError("Out of stock") s3 = SagaStep(fail_ship, lambda: audit.append("CANCEL_SHIP")) execute_saga([s1, s2, s3]) print(audit) ``` </details>