Distributed transactions (Sagas)

Coordinating a workflow across multiple independent microservices.

The idea

In a monolith, placing an order (deducting stock, charging card) happens in one Database Transaction. If anything fails, it rolls back instantly. In microservices, every service has its own database. You can't just "roll back" an HTTP call.

Instead of locking all databases (2-Phase Commit, which is slow and blocks), we use a Saga Pattern. It breaks the transaction into a sequence of local steps. If Step 3 fails, the system executes Compensating Actions for Step 2 and Step 1 in reverse order (e.g. "Refund Card", "Restock Item") to undo the work.

Order Pending Payment Pending Inventory Pending
Ready to process an order.

How it works (Saga Compensation)

# Orchestrator running the Saga:

def place_order_saga(order):
    try:
        OrderService.create(order)        # Step 1
        PaymentService.charge(order)      # Step 2
        InventoryService.reserve(order)   # Step 3
        
        OrderService.mark_complete(order)
    except PaymentFailed:
        OrderService.cancel(order)        # Undo Step 1
    except InventoryFailed:
        PaymentService.refund(order)      # Undo Step 2
        OrderService.cancel(order)        # Undo Step 1