# Sagas: Choreography and Orchestration — Event-Driven Architecture & CQRS

Source: https://www.skillbyai.com/en/event-driven-architecture/r-sagas

> Coordinate a multi-service business process with compensating actions.

## Long transactions without distributed locks

A business process like *place order → reserve stock → charge payment → arrange shipping* spans several services, each with its own database. Two-phase commit across them is rarely practical. A **saga** is a sequence of **local transactions**, each publishing an event or message that triggers the next step; if a step fails, earlier steps are undone by **compensating actions** (release the stock, refund the payment). Compensations are business operations, not database rollbacks, and must themselves be idempotent. In **choreography**, services react to each other's events with no central coordinator: simple for short flows, but the overall process is implicit and hard to follow. In **orchestration**, an **orchestrator** (a dedicated service or a workflow engine such as Temporal, AWS Step Functions or Azure Durable Functions) tells each participant what to do and tracks state: easier to understand, monitor and change, at the cost of a central component.

## An orchestrated order saga

Each step either succeeds or triggers compensations for the steps already done.

```python
def order_saga(order_id):
    done = []
    try:
        inventory.reserve(order_id);     done.append("reserved")
        payments.charge(order_id);       done.append("charged")
        shipping.schedule(order_id);     done.append("scheduled")
        orders.mark_confirmed(order_id)
    except StepFailed as failure:
        if "charged" in done:
            payments.refund(order_id)        # compensation
        if "reserved" in done:
            inventory.release(order_id)      # compensation
        orders.mark_cancelled(order_id, reason=str(failure))

# in production the orchestrator persists its state after every step
# (a workflow engine does this for you) so it can resume after a crash
```

## Planning a group trip

Choreography is a group chat where everyone books their own part after seeing the previous message. Orchestration is one friend with a checklist who books each item and, if the hotel falls through, cancels the train tickets.

**Quiz:** In a saga, what is a compensating action?

- [ ] A database rollback across services
- [x] A business operation that semantically undoes an earlier completed step, such as a refund
- [ ] A retry of the same step
- [ ] A schema migration

*Answer:* A business operation that semantically undoes an earlier completed step, such as a refund. Each local transaction already committed, so it is undone by a new business action.
