Saga pattern
medium 30 minA 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
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
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
criticalA crash loses the place. Stock and money stay taken.
Wrongdone = [] # a fieldstep.execute()done.append(step)Rightlog.write("STARTED", step)step.execute(key=saga)log.write("DONE", step)Swallowing a failed compensation
criticalThe customer keeps the charge and nobody knows.
Wrongtry: refund(order)except Exception: print("oops")Rightretry(refund, order)if still_failing: mark_stuck(saga) alert_operator(saga)Steps that cannot be repeated
criticalMessages arrive twice, and recovery repeats calls.
Wrongstock.free -= 1Rightif key not in stock.held: stock.held.add(key) stock.free -= 1An unfixable step too early
majorAn email or a shipment cannot be undone when the payment fails later.
Wrongsteps = [order, email, stock, charge]Rightsteps = [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.