patternMajorpending
Pattern: Saga pattern for distributed transactions
Viewed 0 times
sagadistributed-transactioncompensating-actionmicroservicesconsistency
Problem
In microservices, a business operation spans multiple services. Traditional ACID transactions don't work across service boundaries.
Solution
Use the Saga pattern — a sequence of local transactions with compensating actions:
# Example: Order processing saga
class OrderSaga:
def execute(self, order):
try:
# Step 1: Reserve inventory
reservation = inventory_service.reserve(order.items)
# Step 2: Charge payment
try:
payment = payment_service.charge(order.total)
except PaymentError:
inventory_service.cancel_reservation(reservation.id) # Compensate step 1
raise
# Step 3: Create shipment
try:
shipment = shipping_service.create(order)
except ShippingError:
payment_service.refund(payment.id) # Compensate step 2
inventory_service.cancel_reservation(reservation.id) # Compensate step 1
raise
return OrderResult(reservation, payment, shipment)
except Exception as e:
order.status = 'failed'
raise
# Two saga styles:
# 1. Choreography: Each service listens to events and acts
# - Simpler, decoupled, harder to track overall flow
# 2. Orchestration: Central coordinator manages the flow
# - More control, easier to understand, single point of failure
Key rules:
# Example: Order processing saga
class OrderSaga:
def execute(self, order):
try:
# Step 1: Reserve inventory
reservation = inventory_service.reserve(order.items)
# Step 2: Charge payment
try:
payment = payment_service.charge(order.total)
except PaymentError:
inventory_service.cancel_reservation(reservation.id) # Compensate step 1
raise
# Step 3: Create shipment
try:
shipment = shipping_service.create(order)
except ShippingError:
payment_service.refund(payment.id) # Compensate step 2
inventory_service.cancel_reservation(reservation.id) # Compensate step 1
raise
return OrderResult(reservation, payment, shipment)
except Exception as e:
order.status = 'failed'
raise
# Two saga styles:
# 1. Choreography: Each service listens to events and acts
# - Simpler, decoupled, harder to track overall flow
# 2. Orchestration: Central coordinator manages the flow
# - More control, easier to understand, single point of failure
Key rules:
- Each step has a compensating action (undo)
- Compensating actions must be idempotent
- Log each step for recovery
- Consider eventual consistency timing
Why
Sagas provide consistency across services without distributed locks, using compensation instead of rollback.
Revisions (0)
No revisions yet.