The user wants a program that implements the Saga pattern for distributed transactions.
1. Understand the Goal:
- Saga Pattern: It's a sequence of local transactions. Each service performs a local transaction and publishes an event (or message). Other services listen to that event and perform their own local transactions. If one step fails, compensating transactions are executed to undo the changes made by preceding transactions.
- Distributed Transactions: Involves multiple services (microservices) coordinating to complete a single business operation.
- Implementation: I need to provide code that demonstrates this. Since I can't spin up actual separate servers in a single response, I will simulate the architecture using classes or functions representing different services and a coordinator (or choreography).
2. Choose the Approach:
There are two main ways to implement Sagas:
- Choreography: Decentralized. Services emit events, and other services react. Good for simple sagas, harder to debug complex ones.
- Orchestration: Centralized. A "Saga Orchestrator" tells each service what to do and handles failures. Easier to visualize, but adds a central point of failure (the orchestrator).
Decision: Orchestration is usually clearer to demonstrate in code because the flow is explicit in one place. It makes the "Compensating Transaction" logic easier to follow.
3. Define the Scenario:
A classic e-commerce "Order" flow is the best example.
- Step 1: Create Order (Pending)
- Step 2: Reserve Credit (Payment Service)
- Step 3: Prepare Items (Inventory Service)
- Step 4: Ship Order (Shipping Service)
- Step 5: Finalize Order (Approved)
Compensating Actions (Rollback):
- If Payment fails -> Cancel Order.
- If Inventory fails -> Refund Payment, Cancel Order.
- If Shipping fails -> Restock Inventory, Refund Payment, Cancel Order.
4. Drafting the Code Structure (Python is usually the most readable for this):
Components:
- Service Classes:
OrderService, PaymentService, InventoryService, ShippingService.
- Each needs a "forward" method (do the work) and a "compensate" method (undo the work).
- Saga Orchestrator: A class that manages the steps.
- Step Definition: Structure to hold
(action, compensation).
5. Refining the Logic:
Step Interface:
class SagaStep:
def execute(self): pass
def compensate(self): pass
Service Simulation:
- I need to simulate success and failure to show the pattern working. I'll add a flag or random chance to force a failure.
Orchestrator Logic:
class SagaOrchestrator:
steps = []
executed_steps = []
def add_step(self, step):
self.steps.append(step)
def run(self):
for step in self.steps:
try:
step.execute()
self.executed_steps.append(step)
except Exception:
self.rollback()
return False
return True
def rollback(self):
# Go backwards through executed steps
for step in reversed(self.executed_steps):
step.compensate()
6. Adding Polish and Realism:
- Use
dataclasses for clean data structures.
- Print logs (e.g., "[PaymentService] Deducting $50...") so the user can see the execution flow.
- Implement a specific "Happy Path" and a specific "Failure Path" (e.g., Inventory fails) to demonstrate the compensation.
7. Writing the Code (Mental Draft & Iteration):
Scenario: Book a Flight + Book a Hotel.
Let's stick to the E-commerce Order (Order -> Payment -> Inventory). It's the standard textbook example.
Classes:
OrderService: create_order(), cancel_order()
PaymentService: deduct(), refund()
InventoryService: reserve_items(), release_items()
The Orchestrator: Needs to handle passing data between steps? For this simple demo, I'll keep the services stateful or pass a context object. Let's pass a context dictionary (the order_id).
8. Finalizing the Implementation Plan:
- Define a
SagaOrchestrator.
- Define service classes with
action and compensate methods.
- Set up a transaction flow.
- Run it once successfully.
- Run it again with a simulated failure in the middle to trigger the rollback.
9. Self-Correction/Refinement during coding:
- Issue: Simple functions are okay, but making them classes helps encapsulate state.
- Improvement: Use a functional approach for the steps passed to the orchestrator to make it very Pythonic and generic.
- Actually: A class-based service approach is easier to read for beginners understanding the architecture. Let's create distinct Service classes.
Let's implement the Orchestration pattern because it shows the "transaction manager" concept most clearly.
Code Structure:
Service base class or just standalone services.
SagaDefinition: A list of steps.
Orchestrator: Runs the list, catches errors, runs compensations.
Let's write the Python code.
Mock Services:
Inventory: Checks stock.
Payment: Processes card.
Notification: Sends email.
Compensating logic:
Inventory: Restock.
Payment: Refund.
Notification: (Usually doesn't need compensation, or send "Sorry" email). Let's skip compensating notification to keep it realistic (emails are fire-and-forget mostly).
Let's create a scenario where the Payment fails after Inventory is reserved. This demonstrates the need for compensation perfectly.
10. Reviewing the User Request:
"Write a program...".
I should provide:
- An explanation of the pattern (Brief).
- The Code (Python is best for pseudocode-like clarity).
- An explanation of the code output.
- Comparison with Choreography (optional but helpful context).
11. Formatting:
Use code blocks, comments, and clear section headers.
(Self-Correction during drafting the response):
Make sure to emphasize that in a real distributed system, these services would be on different machines communicating via HTTP/RPC or Message Queues (Kafka/RabbitMQ). The code here simulates that in a single process for demonstration.
Let's build the Python solution now.
- Class
SagaStep: Holds a name, a function to execute, and a function to rollback.
- Class
SagaOrchestrator: Manages the list of steps. It iterates through them. If one raises an exception, it stops, iterates backwards through successful steps, and runs their rollback.
- Services: Just simple classes with print statements to simulate DB changes.
Scenario:
- Reserve Ticket
- Charge Credit Card
- Confirm Ticket
Failure Case:
- Reserve Ticket (OK) -> Log: "Ticket Reserved"
- Charge Credit Card (FAIL) -> Log: "Insufficient Funds"
- Rollback Triggered
- Unreserve Ticket -> Log: "Ticket Released"
This is perfect. I will write the code to allow a flag to toggle success/failure.
Let's finalize the Python code.
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})
def execute(self):
print("--- Starting Transaction Saga ---")
try:
for step in self.steps:
print(f"Executing: {step['name']}")
step['action']()
self.completed_steps.append(step)
print("--- Transaction Saga Completed Successfully ---")
except Exception as e:
print(f"Error in {step['name']}: {e}")
self.compensate()
def compensate(self):
print("--- !!! FAILURE DETECTED. STARTING COMPENSATION !!! ---")
# Reverse order
for step in reversed(self.completed_steps):
print(f"Compensating: {step['name']}")
step['compensation']()
print("--- Compensation Finished ---")
This looks solid. I will add dummy services around this to make it a complete runnable program.
Refining the services:
FlightService: book_flight, cancel_flight
HotelService: book_hotel, cancel_hotel
PaymentService: process_payment, refund_payment
I will construct two scenarios in the main block:
- Success: All pass.
- Failure: Payment fails, triggering undo of Flight/Hotel.
This covers all bases. Proceed with generating the response.
This solution demonstrates the Saga Pattern using the Orchestration approach.
In this pattern, a central "Saga Orchestrator" coordinates the transaction steps. It tells each service what to do and, if a step fails, it tells the previously executed services how to compensate (rollback) their actions.
The Scenario
We will simulate an E-Commerce Order involving three services:
- Order Service: Creates the order.
- Payment Service: Charges the credit card.
- Inventory Service: Deducts stock.
The Python Implementation
import time
# ==========================================
# 1. Define Domain Models & Exceptions
# ==========================================
class InsufficientFundsError(Exception):
pass
class OutOfStockError(Exception):
pass
# ==========================================
# 2. Define The Services (Participants)
# ==========================================
# In a real-world scenario, these would be separate microservices
# accessed via HTTP/gRPC. Here, we simulate them with classes.
class OrderService:
def create_order(self, order_id):
print(f" [OrderService] Order {order_id} created successfully.")
return {"order_id": order_id, "status": "PENDING"}
def cancel_order(self, order_id):
print(f" [OrderService] COMPENSATING: Cancelling order {order_id}.")
def finalize_order(self, order_id):
print(f" [OrderService] Finalizing order {order_id}.")
class PaymentService:
def process_payment(self, user_id, amount):
print(f" [PaymentService] Charging user {user_id} ${amount}...")
# Simulate a failure condition for demonstration
if amount > 1000:
print(" [PaymentService] Error: Credit Limit Exceeded!")
raise InsufficientFundsError("Credit limit exceeded")
print(f" [PaymentService] Payment processed successfully.")
return {"transaction_id": "tx-12345"}
def refund_payment(self, user_id):
print(f" [PaymentService] COMPENSATING: Refunding user {user_id}.")
class InventoryService:
def reserve_stock(self, product_id, quantity):
print(f" [InventoryService] Reserving {quantity} of {product_id}...")
# Simulate success
print(f" [InventoryService] Stock reserved.")
return {"reservation_id": "res-999"}
def release_stock(self, product_id, quantity):
print(f" [InventoryService] COMPENSATING: Releasing {quantity} of {product_id}.")
# ==========================================
# 3. The Saga Orchestrator
# ==========================================
class OrderSagaOrchestrator:
def __init__(self):
self.order_service = OrderService()
self.payment_service = PaymentService()
self.inventory_service = InventoryService()
# Log to track steps executed for compensation
self.completed_steps = []
def execute(self, order_id, user_id, product_id, amount):
print(f"\n--- STARTING SAGA: Order {order_id} ---")
try:
# STEP 1: Create Order
self.order_service.create_order(order_id)
self.completed_steps.append('ORDER_CREATED')
# STEP 2: Process Payment
self.payment_service.process_payment(user_id, amount)
self.completed_steps.append('PAYMENT_PROCESSED')
# STEP 3: Reserve Inventory
self.inventory_service.reserve_stock(product_id, 1)
self.completed_steps.append('INVENTORY_RESERVED')
# SUCCESS PATH
self.order_service.finalize_order(order_id)
print(f"\n--- SAGA COMPLETED SUCCESSFULLY ---")
except Exception as e:
print(f"\n!!! SAGA FAILED: {e} !!!")
print("--- INITIATING ROLLBACK ---")
self.compensate(order_id, user_id, product_id)
def compensate(self, order_id, user_id, product_id):
# We compensate in reverse order of execution
# If we failed at Payment, we don't need to compensate Inventory (it never ran)
# If we failed at Inventory, we must compensate Payment, then Order.
steps_reversed = self.completed_steps[::-1]
if 'INVENTORY_RESERVED' in steps_reversed:
self.inventory_service.release_stock(product_id, 1)
if 'PAYMENT_PROCESSED' in steps_reversed:
self.payment_service.refund_payment(user_id)
if 'ORDER_CREATED' in steps_reversed:
self.order_service.cancel_order(order_id)
print("--- ROLLBACK COMPLETE ---")
# ==========================================
# 4. Execution / Main Program
# ==========================================
if __name__ == "__main__":
orchestrator = OrderSagaOrchestrator()
# SCENARIO A: Successful Transaction
print(">>> SCENARIO A: Small Order ($50) - Should Succeed <<<")
orchestrator.execute(
order_id="ORD-001",
user_id="USER-A",
product_id="PROD-X",
amount=50.00
)
# Reset internal state for the next saga
orchestrator.completed_steps = []
# SCENARIO B: Failed Transaction (Triggers Compensation)
# Logic: If amount > 1000, PaymentService throws an error.
print("\n>>> SCENARIO B: Large Order ($1500) - Should Fail & Rollback <<<")
orchestrator.execute(
order_id="ORD-002",
user_id="USER-B",
product_id="PROD-Y",
amount=1500.00
)
How It Works
- The Services: The
OrderService, PaymentService, and InventoryService know nothing about the overall workflow. They simply perform their local logic. They also expose "Compensation" methods (e.g., cancel_order, refund_payment) to undo their work.
- The Orchestrator: The
OrderSagaOrchestrator contains the "Brain" of the operation.
- It maintains a list (
completed_steps) to track which steps succeeded.
- It wraps the logic in a
try...except block.
- Failure & Rollback:
- In Scenario B, the payment amount is $1500. The
PaymentService checks this logic and raises an InsufficientFundsError.
- The Orchestrator catches this exception.
- It calls the
compensate method.
- Because the Payment failed, the code never reached the Inventory reservation step.
- The Rollback logic sees that
ORDER_CREATED was successful, so it calls cancel_order.
When to use this?
- Orchestration (The code above): Best for complex workflows. It is easier to understand and debug because the logic is centralized, but the Orchestrator can become a bottleneck or single point of failure.
- Choreography: An alternative approach where services emit events (e.g., "OrderCreated") and other services listen to those events to trigger actions. This is harder to debug but has lower coupling.