Saga pattern (distributed transactions)

A Saga is a sequence of local transactions across services; if a later step fails, earlier steps are undone via compensating transactions (e.g. cancel reservation, refund payment). There is no single ACID transaction across services — consistency is eventual and achieved by compensation.

Choreography: each service reacts and emits events

sequenceDiagram participant O as Order participant P as Payment participant I as Inventory O->>P: Reserve payment P-->>O: PaymentReserved O->>I: Reserve stock I-->>O: StockReserved O->>O: Confirm order alt Inventory fails I-->>O: Failed O->>P: Compensate: release payment end

Orchestration: central coordinator calls services

flowchart LR Saga[Saga Orchestrator] --> S1[Step 1: Payment] S1 --> S2[Step 2: Inventory] S2 --> S3[Step 3: Ship] S3 -->|Fail| Comp[Run compensations in reverse]
StyleHowTrade-off
ChoreographyServices react to events; no central coordinatorHarder to reason; no single place for flow
OrchestrationCentral saga runner calls services and runs compensationsClear flow; orchestrator is a single point

Sagas guarantee “all steps complete or compensating actions run” but not atomicity: between steps, state can be partially updated. Design compensations to be idempotent and handle already-compensated or failed steps.