Topic 11.13
Saga
In one line
A distributed transaction as a sequence of local transactions with compensating actions — the industry answer.
Think of it like this
Planning a trip with flights, hotel, and a rental car booked separately. If the flight gets cancelled, you don't have magic 'undo everything at once' — you manually cancel the hotel and the car too. That manual 'undo the earlier steps' is exactly what a saga automates.
Key ideas
- 01
Choreographed saga: each service listens to events and acts + publishes the next — decentralized, hard to read overall flow.
- 02
Orchestrated saga: a saga coordinator calls each service, tracks state, and triggers compensation on failure — readable, single owner.
- 03
Compensation: each step ships an undo (reserve → release; charge → refund) — idempotent and safe to re-run.
- 04
Example: checkout = reserve inventory → charge payment → reserve delivery; charge fails → release inventory compensation.
- 05
When 2PC > saga: true invariables across DBs with instant-consistency mandates — rare; you usually want to narrow scope instead.
- 06
Interview: 'orchestrated saga with a state store, idempotent steps, and compensating actions on failure'.
Java / Spring map
- →
Orchestrator service with a saga state table (ledger of steps); each step @Transactional idempotent; temp outbox for events.
Code & diagrams
No global lock, no coordinator holding everyone hostage — just a chain of local transactions, with an undo plan for each.
Explain without notes
Poll: when does the payment succeed but inventory fail — walk the choreographed compensation chain end to end.
Practice
Design the sagas for checkout and for refund — step tables, compensation actions, and the idempotency of each.
Trade-offs
- ↔
Orchestration = central + readable but one more service to run; choreography = distributed + harder to trace.
Run it in production
You've designed it. Now build, operate, and break the same idea hands-on in the DevOps courses:
Completion checklist
I can draw a saga with compensations and state exactly where eventual consistency is accepted.