AlgoViz

Saga pattern

medium 30 min

A saga is a chain of local transactions, one per service, with an undo step for each.

See it run

Local transactions in order, compensations in reverse, and what happens when somebody crashes.

Operations

Success

The orchestrator drives three services to the end.

Step 1 of 7

Request arrives

Orchestratorsaga stateOrderspendingInventorypendingPaymentspending

Saga log

s1 STARTED

Saga s1 started

The orchestrator receives an order request and creates a saga record.

Step 1: Request arrives

def run(saga):    for step in steps:        log("STARTED", step)        if not step.execute():            return compensate(saga)        log("DONE", step)    log("COMPLETED")
Locks held
Local only
Others see
Pending order
Two-phase commit
locks everywhere until the decision

The order is PENDING until the end. That status is the semantic lock.

In the real world

The same saga pattern doing real jobs. Pick one and step through it.

Sagas are not isolated. A reservation protects the last item.

Step 1 of 4

One item left

commandOrchestratorsaga stateOrdersA: PENDINGInventoryfree: 0Paymentsidle

A holds the last item

Saga A reserves it.

Step 1: One item left

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Keeping saga state in memory

    critical

    A crash loses the place. Stock and money stay taken.

    Wrong
    done = []          # a fieldstep.execute()done.append(step)
    Right
    log.write("STARTED", step)step.execute(key=saga)log.write("DONE", step)
  • Swallowing a failed compensation

    critical

    The customer keeps the charge and nobody knows.

    Wrong
    try:    refund(order)except Exception:    print("oops")
    Right
    retry(refund, order)if still_failing:    mark_stuck(saga)    alert_operator(saga)
  • Steps that cannot be repeated

    critical

    Messages arrive twice, and recovery repeats calls.

    Wrong
    stock.free -= 1
    Right
    if key not in stock.held:    stock.held.add(key)    stock.free -= 1
  • An unfixable step too early

    major

    An email or a shipment cannot be undone when the payment fails later.

    Wrong
    steps = [order, email, stock, charge]
    Right
    steps = [order, stock, charge, confirm, email]

Interview tips

  • How to explain it

    • Local transactions in order.
    • Compensations in reverse.
    • Eventually consistent, not isolated.
  • Memory trick: SAGA

    • Sequence of local transactions.
    • Apologise (compensate) on failure.
    • Goes to a consistent end.
    • Autonomous services.
  • Always mention

    • Idempotency keys.
    • Durable saga state.
    • Timeouts and the outbox.
  • Avoid it when

    • One database can do it.
    • The work needs isolation.
    • Nothing can be undone.