Why Long Transactions Are A Problem
A transaction that holds locks for a long time, or that spans several services, harms concurrency and cannot use a single atomic commit. The saga pattern replaces one long transaction with a sequence of small local transactions.
How A Saga Works
- The saga is an ordered list of steps, each a local transaction that commits on its own.
- Every step has a paired compensating action that semantically undoes it.
- If a step fails, the saga runs the compensations for all completed steps in reverse order, rolling the system back to a consistent state.
For example, booking a trip: reserve flight, reserve hotel, charge card. If charging fails, cancel the hotel and cancel the flight.
Atomicity Without Locks
A saga gives atomicity at the business level rather than database level. It does not provide isolation: intermediate states are visible to others, so designs must tolerate seeing a half completed saga.
Coordination Styles
- Orchestration: a central coordinator tells each service what to do next.
- Choreography: each service emits events that trigger the next step, with no central brain.
Key idea
A saga splits a long transaction into committed steps each with a compensating action, giving business level atomicity but no isolation.