SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
  • The Problem with Distributed Transactions
  • Two-Phase Commit (2PC)
  • Three-Phase Commit (3PC)
  • SAGA Pattern
  • Try-Confirm-Cancel (TCC)
  • Compensating Transactions
  • Outbox Pattern
  • Exactly-Once Processing
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Distributed Systems/Distributed Transactions

SAGA Pattern

A chain of local transactions, with a 'compensating' step to undo each one if something fails.

⏱ 15 min readAdvancedMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A saga is a way to do one big job that spans many services, without a single big database transaction. It is a chain of small local transactions. If one step fails, the saga runs undo steps for the ones that already finished.

  • Each service saves its own change in its own database and then triggers the next step.
  • You cannot "roll back" a step that is already committed. So every step gets a matching compensating action (cancel order, refund money, release stock).
  • The result is eventual consistency: for a short time the system can be half-way done, and in the end it is either fully done or fully undone.

02Concept: What is it?

In a single database, a transaction is all-or-nothing. If anything fails, the database rolls back and it is as if nothing happened. With microservices, each service owns its own database. One order may touch the Order, Inventory, Payment and Shipping services, so there is no single transaction that covers all four.

A distributed lock-and-commit protocol such as two-phase commit can fix this, but it blocks, is slow, and many modern databases and message brokers do not support it. The saga pattern takes another road. It gives up instant all-or-nothing and accepts a short period where things are only partly done.

A saga is a sequence of local transactions: T1, T2, T3 and so on. Each one commits for real. For every step Ti there is a compensating transaction Ci that semantically undoes it. If T3 fails, the saga runs C2, then C1, in reverse order.

A saga that fails and undoes itself
🧾T1 Create order
→↓
πŸ“¦T2 Reserve stock
→↓
πŸ’³T3 Charge carddeclined
↩️C1 Cancel order
←then
↩️C2 Release stock
←first
⚠️Failure
Steps 1 and 2 committed. Step 3 failed. The saga now runs the undo for step 2, then step 1.
🧠Compensation is not rollback
A rollback makes the change vanish as if it never happened. A compensation is a new action that cancels the effect. The first charge and the refund both appear on the bank statement. Other people may even see the in-between state.

03Real-Life Example

🍡Planning a Trip with Many Bookings
You book a holiday with three separate companies: a flight, a hotel and a car. Each company takes your booking and your money on its own. You cannot ask all three to agree in one single click. So you do them one by one. If the car is not available after you already paid for the flight and the hotel, you do not pretend the first two never happened. You call each company and cancel, in reverse order, and ask for refunds. Cancelling a flight may even cost a small fee. That is a compensation: it fixes the situation, but it is not a perfect rewind.
Trip booking
Saga
Flight, hotel and car are separate companies
Separate services, each with its own database
Booking each one in order
A chain of local transactions
Cancelling the flight or the hotel
A compensating transaction
Cancelling in reverse order
Running compensations from the last finished step backwards
A cancellation fee
Compensation is not a perfect undo
Your travel agent who keeps the checklist
The saga orchestrator
Each company telling the next one β€œgo ahead”
Choreography with events
One order across four services
🧾Ordercreate PENDING
→↓
πŸ“¦Inventoryreserve stock
→↓
πŸ’³Paymentcharge card
→↓
🚚Shippingbook delivery

04Why Do We Need It?

🧩Each service owns its data
No shared database. Services stay independent and can use different databases.
🚫No global lock
Nothing is held locked while far-away services think. Throughput stays high.
🌐Works over messages
A saga needs only calls or events. It does not need special support from the database.
πŸ› οΈFailures are expected
The undo path is part of the design, not an afterthought.
πŸ“ˆScales well
Short local transactions are cheap. There is no coordinator holding locks across the network.
⏱️Long jobs are fine
A saga can wait hours for a human approval or a slow partner, which a locking transaction cannot do.
When one transaction cannot cover many services, chain small ones, and write an undo for each step.

05Where Do We Use It?

πŸ›’Checkout
Order, stock, payment and delivery in an online shop.
✈️Travel booking
Flight, hotel and car from different providers.
🏦Money transfers
Debit one account, credit another in a different system, with a reverse transfer on failure.
πŸš•Ride sharing
Match a driver, hold a fare, start the trip, charge the rider.
πŸ”Food delivery
Restaurant accepts, courier assigned, payment captured.
🏒Business workflows
Onboarding a customer, with checks that take days.

06Types / Parts / How It Works

Two ways to run a saga

Choreography and orchestration
Choreography (events)
🧾Order
→↓OrderCreated
πŸ“¦Stock
↓StockReserved
πŸ’³Payment
→↓PaymentDone
🚚Shipping
Orchestration (a conductor)
🎼Orchestratorknows the whole flow
↓commands
🧾Order
πŸ“¦Stock
πŸ’³Payment
🚚Shipping
Services react to events One place holds the flow
Same steps. The difference is who decides what happens next.
ChoreographyOrchestration
Who decides the next step?Each service, by reacting to eventsA central orchestrator, by sending commands
CouplingLoose, but services must know which events to listen toServices only know the orchestrator
Seeing the whole flowHard: it is spread over many servicesEasy: it is written in one place
RiskA hidden tangle of events and cycles as it growsThe orchestrator can become a busy, central piece
Best forShort sagas with 2 to 4 stepsLonger flows, branches and clear error handling

Kinds of steps in a saga

Step typeMeaningExample
CompensableCan be undone with a compensating actionReserve stock, release stock
PivotThe point of no return. After it succeeds, the saga goes forward onlyCharge card and ship the parcel
RetryableAfter the pivot. Must be retried until it worksSend the confirmation email
VisualizerRun an order saga and break itPick where the order fails, then step through. Compare a saga with compensations to plain local commits that never undo. Try the refund that fails once.
Where does it go wrong?
How is the failure handled?
🧾
Order
Order service
waiting
πŸ“¦
Stock
Inventory service
waiting
πŸ’³
Payment
Payment service
waiting
🚚
Shipping
Shipping service
waiting
Event log
  1. Nothing has happened yet.
Steps done
0
of 4
Compensated
0
undone steps
Customer charged
No
payment still held
State
running
0 of 5 events
Press Next or Play. Each service commits its own small local transaction, one after the other.

A simplified orchestrated saga. Real sagas also store their progress, so a crashed coordinator can carry on where it stopped.

07How to Use It / Steps / Implementation

Designing a saga

  1. 1
    List the steps
    Write the business flow as a sequence of local transactions, each in one service.
  2. 2
    Write a compensation for each
    For every step that can be undone, define the action that cancels its effect. Think about what the customer sees.
  3. 3
    Find the pivot
    Decide which step cannot be undone (an email sent, a parcel shipped). Put risky steps before it and steps that must succeed after it.
  4. 4
    Choose choreography or orchestration
    Few steps: events may be enough. Many steps or branches: use an orchestrator or a workflow engine.
  5. 5
    Make every step idempotent
    Messages can arrive twice. Use a saga ID or request ID, so a repeated step or a repeated undo does nothing the second time.
  6. 6
    Save the saga state
    Store which step the saga is on. After a crash, it must carry on and not start again.
  7. 7
    Send events reliably
    Save the change and the message in one local transaction, using the outbox pattern, so no step is lost.
  8. 8
    Handle the in-between state
    Show the order as PENDING. Use semantic locks or status flags, so other requests do not use half-finished data.
πŸ’‘Order the steps by risk
Put steps that are likely to fail, or hard to undo, first (or right before the pivot). A cheap, safe reservation is better than a charge you may have to refund.
⚠️Sagas are not isolated
There is no ACID "I" here. Another request can read your order while it is half done, or change the same stock. Plan for it with statuses (PENDING), reservations and checks on the data version.

08Key Terms to Know

TermMeaning in easy words
SagaA chain of local transactions with undo steps, used instead of one distributed transaction
Local transactionA normal ACID transaction inside one service and its own database
Compensating transactionA new action that cancels the effect of an earlier committed step
ChoreographyA saga style where services react to each other's events, with no central boss
OrchestrationA saga style where a central orchestrator tells each service what to do next
OrchestratorThe component that holds the saga flow and its current state
Pivot transactionThe step after which the saga can only move forward
Eventual consistencyThe data may disagree for a while but ends up correct
IdempotentDoing it twice has the same effect as doing it once
Semantic lockA status flag (such as PENDING) that warns others the record is mid-saga
Saga logStored record of the saga's progress, used to recover after a crash

09Pros, Cons and Trade-offs

βœ… Pros
  • No global locks, so higher throughput
  • Each service keeps its own database
  • Works with plain messages and APIs
  • Fits long-running business flows
  • Failure handling is explicit and testable
⚠️ Cons
  • Only eventual consistency, no isolation
  • Every step needs an undo, which is hard design work
  • Compensation is not always possible (an email cannot be unsent)
  • Harder to debug than one transaction
  • Choreography can become a tangle of events

Trade-offs

ChoiceWe gainWe lose
Saga instead of 2PCNo blocking, better scale and availabilityStrict all-or-nothing and isolation
ChoreographySimple start and loose couplingA hard-to-follow flow as it grows
OrchestrationClear flow and central error handlingA central component to build and run
Undo fast with compensationsQuick recoveryCustomers may briefly see the in-between state
Retry forwardNo need to write an undoOnly works when the failure is temporary

10Common Problems and Mistakes

Common mistakes

  1. No compensation for a step. A failure leaves money taken or stock locked forever.
  2. Non-idempotent steps. A repeated message charges the card twice or refunds twice.
  3. Losing the message. The service saves its change but crashes before sending the next event. Use the outbox pattern.
  4. Expecting isolation. Reading half-done data and treating it as final.
  5. The compensation fails too. It must be retried until it works, and an alert must tell a human if it never does.
  6. A cycle of events. In choreography, services trigger each other in a loop.
  7. Ignoring the pivot. Putting an irreversible step too early.

Things to watch

🧟Stuck sagas
A saga waiting forever for a reply. Set timeouts and a dashboard for old ones.
πŸ”Duplicates
At-least-once messages mean repeats. Check the saga ID before acting.
πŸ”€Out-of-order events
A cancel can arrive before the create it cancels. Handle it.
πŸ‘€Dirty reads
Another request sees a step that is later undone. Use status flags.

11Real-World Examples

πŸ›’E-commerce checkout
Order, stock, payment and shipping run as a saga, with a refund and a release on failure.
✈️Travel sites
Booking a flight, hotel and car from different partners, with cancellations if one fails.
βš™οΈWorkflow engines
Tools such as Temporal, Camunda and AWS Step Functions run orchestrated sagas and keep their state.
🧰Saga libraries
Frameworks such as Axon, MassTransit and Eventuate Tram help build sagas.
🏦Payments
Authorise, capture and refund are natural saga steps, with reversal as the compensation.
πŸš•Ride apps
Match, start, finish and charge a trip across several services.
πŸ“Note
Product names and features change over time. Check each tool's documentation before you pick one.
Mini case: payment declined
🧾Ordercreated
→↓
πŸ“¦Stockreserved
→↓declined
πŸ’³Paymentfailed
→↓undo
↩️Release + cancel

12Related Topics to Read Next

The Problem with Distributed Transactions→

The reason sagas exist.

Two-Phase Commit (2PC)β†’

The strict alternative, and why it often does not scale.

Outbox Pattern→

Sends each saga event reliably, together with the local commit.

Idempotency→

Makes repeated steps and repeated undos safe.

Event-Driven Architecture→

The base of choreographed sagas.

Microservices→

The setting where each service owns its database.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”What: a chain of local transactions with an undo for each step.
  • βœ”Why: one transaction cannot span many services, and 2PC blocks.
  • βœ”On failure: run compensations in reverse order. This is not a rollback.
  • βœ”Choreography: events, no boss. Orchestration: a conductor holds the flow.
  • βœ”Pivot: the point of no return. Risky steps go before it.
  • βœ”Must have: idempotent steps, saved saga state, reliable messages (outbox).
  • βœ”Cost: eventual consistency and no isolation. Show PENDING states.
  • βœ”One line: β€œDo it step by step, and if it breaks, undo it step by step.”
← Previous
Three-Phase Commit (3PC)
Next β†’
Try-Confirm-Cancel (TCC)