AlgoViz

Saga pattern

medium 30 min

A saga is a chain of local transactions, one per service, with an undo step for each.

When it comes up

The moments this idea belongs in a design interview, and the moments it does not.

Signals

When to bring it up

You hearSayBecause
Order, stock and payment are separate servicesA saga with an orchestratorNo transaction spans them
A process lasts minutes or daysA saga, never held locksLocks must be short
"What if payment fails?"Release the stock, cancel the orderName the compensation for each step
Two or three services, simple flowEvents may be enoughA coordinator is extra work
All rows fit in one databaseOne local transactionSimplest correct answer

Options

Compare your moves

An order touches three services. How do you keep them consistent?

BreaksCall all three and hope
How
Call each service in turn. Return an error if one fails.
Limit
Stock stays reserved and cards stay charged after a failure or a crash.
Choose when
Never for money or stock.
WorksTwo-phase commit
How
Prepare in all databases, then commit.
Limit
Locks are held across services, and a lost coordinator blocks everyone.
Choose when
A few databases that support it, short work, one data centre.
StrongA saga with durable state
How
Local transactions, idempotent steps, compensations, an outbox, timeouts and alerts.
Limit
No isolation. Pending states are visible, and undo code must be designed.
Choose when
Separate services and a business that can live with pending.