The user wants a program that implements the Saga pattern for distributed transactions.
1. Understand the Goal:
- Saga Pattern: A sequence of local transactions where each transaction updates a single service/database and publishes an event/message to trigger the next step. If one step fails, compensating transactions are executed to undo the changes made by the preceding steps.
- Distributed Transactions: The context implies multiple services working together to complete a single business operation (e.g., Order -> Payment -> Inventory -> Shipping).
- Language: Python is usually the most accessible for conceptual demonstrations, but Go or Java are also common in microservices. I'll stick to Python for clarity and use a simple in-memory approach or a lightweight message broker simulation (like a simple queue or
asyncio) to keep the code runnable without external dependencies (like Kafka or RabbitMQ).
2. Key Components of a Saga:
- Orchestrator (Orchestration-based Saga): A central coordinator tells participants what to do and handles failures/compensation. This is usually easier to understand and implement for a demo than Choreography.
- Participants (Services): Each service needs:
- A method to execute the action (Forward action).
- A method to compensate the action (Undo action).
- State Management: Tracking the current state of the saga.
3. Scenario:
Let's use the classic "E-Commerce Order" scenario:
- Create Order (Pending)
- Process Payment
- Reserve Inventory
- Ship Order
Compensating actions:
- Cancel Order
- Refund Payment
- Release Inventory
- (Cancel Shipment - though usually not needed if the previous steps fail, but good to have for completeness).
4. Design the Code Structure:
Approach: Orchestration
SagaStep: A class holding the action and the compensation.
SagaOrchestrator: Executes steps in order. If a step fails, it runs compensations for completed steps in reverse order.
Service: Mock classes simulating external services (OrderService, PaymentService, InventoryService).
5. Draft Implementation Steps (Mental or Scratchpad):
-
Define the Services:
OrderService: create_order(), cancel_order()
PaymentService: deduct_payment(), refund_payment()
InventoryService: reduce_stock(), add_stock()
-
Define the Saga Logic:
- A list of steps.
- A loop to iterate through steps.
try-except block inside the loop.
- If
try fails, trigger the rollback loop.
6. Refining the Code (Adding "Realism"):
- Use
asyncio to simulate asynchronous behavior (network calls).
- Add a way to simulate failure to demonstrate the compensation logic.
7. Writing the Code (Iterative Refinement):
-
Step 1: Basic Structure
class SagaOrchestrator:
def __init__(self):
self.steps = []
self.completed_steps = []
def add_step(self, name, action, compensation):
self.steps.append({'name': name, 'action': action, 'compensation': compensation})
async def execute(self):
# Execute forward
for step in self.steps:
try:
await step['action']()
self.completed_steps.append(step)
except Exception as e:
# Start Compensation
await self.compensate()
raise e
async def compensate(self):
# Reverse order
for step in reversed(self.completed_steps):
await step['compensation']()
-
Step 2: The Services
Need to simulate state changes.
class Service:
def __init__(self, name):
self.name = name
async def execute(self): ...
async def compensate(self): ...
-
Step 3: The Main Program
- Setup services.
- Configure the Saga.
- Run it twice: once successfully, once with a simulated failure.
8. Handling Complexity:
- The user might want to see the flow clearly. I should add print statements like
[Saga] Executing Step 1... and [Saga] Compensating Step 1....
- I should explain the difference between Choreography and Orchestration briefly in the text, but implement Orchestration as it's cleaner to demonstrate in a single program.
9. Code Polish:
- Add type hinting.
- Use Python's
dataclasses or simple dictionaries for clarity.
- Make the simulation of failure configurable (e.g., a flag).
10. Final Review of the Solution:
- Does it define actions? Yes.
- Does it define compensations? Yes.
- Does it handle failure? Yes.
- Is it runnable? Yes, standard Python library only.
(Self-Correction during drafting): Should I use a message queue like RabbitMQ?
Decision: No, setting up RabbitMQ is too complex for a "write a program" prompt. It shifts focus from the pattern logic to infrastructure config. Stick to in-memory asyncio to represent the distributed nature (latency/concurrency) without the overhead.
11. Constructing the Explanation:
- Start with a high-level explanation of the Saga Pattern.
- Explain the Orchestration approach used in the code.
- Provide the Python code.
- Show the output.
- Briefly explain the Choreography alternative.
12. Executing the plan:
(Proceed to generate the Python code based on the logic above.)
A Saga manages distributed transactions by breaking them into a sequence of local transactions. If one step fails, it executes "compensating transactions" to undo the changes made by previous steps.
Below is a complete, runnable Python implementation demonstrating the Orchestration pattern.
The Scenario
We will simulate an E-Commerce Order flow involving three services:
- Order Service: Creates the order.
- Payment Service: Deducts money.
- Inventory Service: Deducts stock.
If Inventory fails (e.g., out of stock), the Saga Orchestrator will automatically trigger compensating actions (Refund Payment, Cancel Order).
Python Implementation
You can save this code into a file named saga_pattern.py and run it.
import asyncio
import random
from enum import Enum
from typing import Callable, List, Optional
# ==========================================
# 1. Domain Models & Mock Services
# ==========================================
class SagaStatus(Enum):
STARTED = 1
COMPLETED = 2
FAILED = 3
COMPENSATED = 4
class SagaStep:
"""
Represents a single step in the saga.
Contains the forward action (transaction) and the backward action (compensation).
"""
def __init__(self, name: str, action: Callable, compensation: Callable):
self.name = name
self.action = action
self.compensation = compensation
# Mock Service States (Simulating separate databases)
class SystemState:
def __init__(self):
self.orders = {} # order_id: status
self.payments = {} # order_id: amount
self.inventory = {"item_123": 10} # item_id: count
state = SystemState()
# --- Service Implementations ---
async def create_order(order_id):
print(f" [OrderService] Creating order {order_id}...")
await asyncio.sleep(0.5)
state.orders[order_id] = "CREATED"
print(f" [OrderService] Order {order_id} CREATED.")
async def cancel_order(order_id):
print(f" [OrderService] COMPENSATING: Cancelling order {order_id}...")
await asyncio.sleep(0.5)
if order_id in state.orders:
state.orders[order_id] = "CANCELLED"
print(f" [OrderService] Order {order_id} CANCELLED.")
async def process_payment(order_id, amount):
print(f" [PaymentService] Processing payment of ${amount} for {order_id}...")
await asyncio.sleep(0.5)
state.payments[order_id] = amount
print(f" [PaymentService] Payment processed successfully.")
async def refund_payment(order_id):
print(f" [PaymentService] COMPENSATING: Refunding payment for {order_id}...")
await asyncio.sleep(0.5)
if order_id in state.payments:
del state.payments[order_id]
print(f" [PaymentService] Payment refunded.")
async def deduct_inventory(order_id, item_id, quantity, should_fail=False):
print(f" [InventoryService] Deducting {quantity} of {item_id}...")
await asyncio.sleep(0.5)
# SIMULATE FAILURE LOGIC
if should_fail:
raise Exception("Inventory Service Error: Out of Stock!")
if state.inventory.get(item_id, 0) >= quantity:
state.inventory[item_id] -= quantity
print(f" [InventoryService] Stock deducted. Remaining: {state.inventory[item_id]}")
else:
raise Exception("Inventory Service Error: Insufficient Stock")
async def restore_inventory(order_id, item_id, quantity):
print(f" [InventoryService] COMPENSATING: Restoring {quantity} stock for {item_id}...")
await asyncio.sleep(0.5)
state.inventory[item_id] += quantity
print(f" [InventoryService] Stock restored. New Total: {state.inventory[item_id]}")
# ==========================================
# 2. The Saga Orchestrator
# ==========================================
class SagaOrchestrator:
def __init__(self):
self.steps: List[SagaStep] = []
self.completed_steps: List[SagaStep] = []
self.status = SagaStatus.STARTED
def add_step(self, step: SagaStep):
self.steps.append(step)
async def execute(self):
print(f"\n--- Starting Saga Transaction ---")
# 1. Execute Forward Transactions
for step in self.steps:
try:
print(f"\n> executing step: {step.name}")
await step.action()
self.completed_steps.append(step)
except Exception as e:
print(f"\n!!! FAILURE at step '{step.name}': {e} !!!")
self.status = SagaStatus.FAILED
await self.compensate()
return
self.status = SagaStatus.COMPLETED
print(f"\n--- Saga Completed Successfully ---")
async def compensate(self):
print(f"\n>>> Initiating Rollback (Compensation)...")
# 2. Execute Compensations in Reverse Order
# We pop from the stack of successfully completed steps
while self.completed_steps:
step = self.completed_steps.pop()
print(f"\n> compensating step: {step.name}")
try:
await step.compensation()
except Exception as e:
# In a real system, you might retry or alert a human here
print(f"Critical error during compensation of {step.name}: {e}")
self.status = SagaStatus.COMPENSATED
print(f"\n--- Saga Rollback Finished ---")
# ==========================================
# 3. Execution / Main Program
# ==========================================
async def main():
# Scenario 1: Successful Transaction
print("========= SCENARIO 1: SUCCESS =========")
saga1 = SagaOrchestrator()
# Define the workflow
saga1.add_step(SagaStep(
name="Create Order",
action=lambda: create_order("order_1"),
compensation=lambda: cancel_order("order_1")
))
saga1.add_step(SagaStep(
name="Process Payment",
action=lambda: process_payment("order_1", 100),
compensation=lambda: refund_payment("order_1")
))
saga1.add_step(SagaStep(
name="Deduct Inventory",
action=lambda: deduct_inventory("order_1", "item_123", 1, should_fail=False),
compensation=lambda: restore_inventory("order_1", "item_123", 1)
))
await saga1.execute()
# Scenario 2: Failed Transaction (Requires Rollback)
print("\n\n========= SCENARIO 2: FAILURE & ROLLBACK =========")
saga2 = SagaOrchestrator()
saga2.add_step(SagaStep(
name="Create Order",
action=lambda: create_order("order_2"),
compensation=lambda: cancel_order("order_2")
))
saga2.add_step(SagaStep(
name="Process Payment",
action=lambda: process_payment("order_2", 200),
compensation=lambda: refund_payment("order_2")
))
# We pass should_fail=True here to simulate the crash
saga2.add_step(SagaStep(
name="Deduct Inventory",
action=lambda: deduct_inventory("order_2", "item_123", 1, should_fail=True),
compensation=lambda: restore_inventory("order_2", "item_123", 1)
))
await saga2.execute()
# Verify final state
print("\n\n========= FINAL SYSTEM STATE =========")
print(f"Orders: {state.orders}")
print(f"Payments: {state.payments}")
print(f"Inventory: {state.inventory}")
if __name__ == "__main__":
asyncio.run(main())
How it Works
- The
SagaOrchestrator Class: This acts as the central brain. It maintains a list of steps to execute.
- The
SagaStep Class: Every step is defined as an object containing two functions:
- Action: The operation to perform (e.g.,
process_payment).
- Compensation: The logic to undo that specific operation (e.g.,
refund_payment).
- Execution Flow:
- The orchestrator loops through the steps.
- If a step succeeds, it is added to the
completed_steps stack.
- If a step throws an Exception, the orchestrator catches it, stops processing new steps, and enters the
compensate() method.
- Compensation Logic:
- The orchestrator iterates backward through the
completed_steps.
- It executes the compensation function for every step that previously succeeded, effectively rolling back the entire transaction.
When to use this?
- Use Orchestration (shown above) when you have a clear central authority (like an "Order Service") managing the flow. It is easier to debug and understand.
- Use Choreography (Event-based) when you want services to be completely decoupled. (e.g., Payment Service listens for "OrderCreated" events and emits "PaymentProcessed" events). This reduces coupling but is much harder to debug and track visually.