Skip to content
Lesson 53

Sagas and distributed transactions

A package touches our database, a payment provider and a partner, and no single commit reaches all three. Learn how a saga gives every step a planned undo, why the order of the steps matters, and why an undo must be retried like any other step.

The lesson in text

Click a paragraph to hear it.

01Half a holiday

It's Thursday at eleven, and StayHub's new product has been live for two days: Stay plus Transfer. A hotel room and a car from the airport, paid in one charge. About 1,100 packages sell every day.

Maya has bad news. 86 guests were charged about €410 each. Their room is stuck on pending, and no transfer was booked. Two of them land in Lisbon tonight.

Omar reads the code. It holds the room, charges the card, then asks RideCo, the transfer partner, for a driver. About 8% of the time, RideCo answers: no drivers. And there, the code simply stops with an error.

An error stops our code. It undoes nothing in the other systems. In this lesson, you'll learn how a flow across several companies ends either fully done or fully undone. It's called a saga.

02A trip on three websites

Think of planning a trip on three websites. You book a flight on one, a hotel on another, and a car on a third. No button says: all three, or none.

If the car turns out to be sold out, you go back. You cancel the hotel on the hotel's site. Then you cancel the flight on the airline's site. Each site has its own cancel button.

StayHub's package is the same trip. The room lives in our inventory database. The charge lives at the payment provider. The transfer lives at RideCo. Three owners, three records.

One package, three owners
StayHub inventory
Room held, "pending"
saved, stays
Payment provider
Card charged, about €410
saved, stays
RideCo (partner)
"No drivers": nothing booked
refused
Our database's rollback reaches only the first box.
Each step is saved by a different system. When RideCo refused, the code threw an error: that stopped our code, but nobody told the inventory or the provider. 86 guests were left charged, with a pending room and no transfer.

Inside one database, a transaction makes several changes all or nothing. But that's a promise one database makes about its own data. Our rollback can't reach the provider or RideCo. That's why the charge stayed.

03Why not one big yes?

There is a classic answer, called two-phase commit. A coordinator first asks everyone: are you ready? Each one does the work, locks it, and promises. Only when all say yes does the coordinator say: go.

It works inside systems built for it. Google's Spanner database uses it between its own machines. But while they wait for the go, everyone keeps their locks. And if the coordinator dies in between, they're stuck, waiting.

And here's the real problem. RideCo and the payment provider don't support it. They'll never join our transaction. They offer something much simpler: a cancel, and a refund.

04Every step plans its undo

So we do what you did with the three websites. A saga is a flow across services where each step saves for real, and each step comes with a planned undo.

That undo is called a compensation. Hold the room, undone by releasing it. Book the transfer, undone by cancelling it. Charge the card, undone by a refund.

If a later step fails, the saga runs the compensations of the finished steps, in reverse order. The last thing done is the first thing undone.

Each step and its planned undo
StepCompensationWhy here
1. Hold the room (15 minutes)Release the holdCheap; the hold also expires on its own
2. Book the transferCancel the transferFree; fails about 8% of the time
3. Charge the card (the pivot)RefundExpensive: two lines on the statement, days to arrive
4. Confirm the bookingNone: retried until it succeedsAfter the pivot we only push forward
5. Send the emailNone: it can't be unsentAlways last
If a step fails for good, the compensations of the finished steps run in reverse order: the last thing done is the first thing undone. A compensation is a new action, not an eraser.

A compensation is a new action, not an eraser. A refund doesn't delete the charge: the guest sees both lines on their statement, and waits days for the money. So the order of the steps matters a lot.

05Order by how easy the undo is

Back to the trip. You'd book the thing most likely to sell out first, and pay for the hard-to-cancel thing last. Same rule here: order the steps by how easy they are to undo.

First, hold the room for 15 minutes. If everything else is lost, the hold expires on its own. Then the transfer: it fails 8% of the time and is free to cancel, so it goes before any money moves.

Then the charge. This is the pivot, the point of no return. Before it, a failure means compensate. After it, we only push forward, and retry each remaining step until it succeeds.

After the pivot comes confirming the booking. And the email goes last, because an email can never be unsent.

Now, RideCo says no drivers at step two. What runs? Only one compensation: release the room. Nothing was charged yet. Most failures now cost a released hold, and nothing more.

Where it fails decides what runs
RideCo says "no drivers" (step 2)
  1. Release the room
The card is declined (step 3)
  1. 1. Cancel the transfer
  2. 2. Release the room
Confirm hits a database blip (step 4)
  1. Nothing: retry confirm with the same key
Because the transfer, which fails most, comes before the charge, the common failure costs only a released hold: no refund, nothing on the guest's statement.

06The orchestrator remembers

Someone has to remember where each package is. That's the orchestrator: one component that sends each step, records the progress, and runs the compensations.

But the orchestrator can crash too. So it saves its progress and its next command together, in one transaction, like the outbox from the lesson on events. When it restarts, it reads where it was and carries on.

The orchestrator saves its progress with the next command
BEGIN;one single save
UPDATE sagas SET step = 'TRANSFER_BOOKED' WHERE id = 'pk_311';the progress
INSERT INTO outbox (command, key) VALUES ('Charge', 'pk_311-charge');the next command
COMMIT;both, or neither
Orchestrator
Outbox
Payment provider
progress + Charge, together
Charge, key pk_311-charge
sent again after a crash: same key, charged once
charged ✓
One transaction holds both, so a crash can't lose the command or send one for a state that never saved. Every command carries its own key, so a repeat after a crash is harmless.

After a crash, it may send the same step twice. So every step and every undo carries its own key, like the package number plus the word charge. Ask twice with the same key, and the provider charges once.

It also tells two kinds of errors apart. A timeout, or a busy server, means we don't know yet: retry with the same key. Only a clear no, like no drivers, starts the compensations.

And a saga gives up one thing a database gave you for free: isolation. Others can see the halfway states. For a moment, a package is held but not paid. So name that state, pending, and never let another flow treat it as booked.

07The refund that ran once

Two weeks later, a Saturday at 14:20. The first saga version is live. A hotel in Porto has closed for renovation, so confirming fails for 23 packages, and this version starts compensating.

At the same moment, the payment provider is having a bad hour. Since 14:15, it has answered 503: service unavailable. The request was never processed.

The refund is tried once. It fails, the error is logged, and the saga moves on. It releases the room and marks itself compensated. Done, it says. But the refunds never happened, and nothing will ever retry them.

An undo that runs once versus an undo that's a real step
Before: tried once
  1. 1. Refund → 503, error logged
  2. 2. Release the room
  3. 3. Saga: COMPENSATED (but still charged)
After: a step like any other
  1. 1. Refund, key pk_311-refund → 503: retry with backoff, same key
  2. 2. Saga stays COMPENSATING until every undo succeeded
  3. 3. Stuck for more than 10 minutes: alert someone
Saturday 14:20: confirming failed for 23 packages while the provider answered 503. The one-shot refund left 23 guests charged and the saga saying “done”.

23 guests stayed charged for a package that no longer exists. They found out from their bank. Some filed chargebacks, and every chargeback costs StayHub a fee.

The rule: a compensation is a step like any other. Retry it with the same key until it succeeds. Keep the saga in compensating until every undo is done. And alert someone when a saga is stuck for more than 10 minutes.

08One conductor, or a dance

One more decision. Karim says: we already run Kafka. Let each service react to the previous event. Room held, so book the transfer. Transfer booked, so charge. No orchestrator to run. That's called choreography.

Lina answers: then the flow lives in five subscriptions across three teams. When a package is stuck, who knows which event never came? For the steps that take money, she wants one place that knows the whole story.

So StayHub does both. The orchestrator drives the money path: hold, transfer, charge, confirm. Then loyalty points and analytics react to a package confirmed event, on their own time.

Orchestration or choreography
Orchestration: one conductor

One component sends each step, stores where each package is, and runs the undos.

Use for: hold, transfer, charge, confirm.

Cost: one more component to run.

Choreography: a dance

Each service reacts to the previous event. No central piece.

Use for: loyalty points, analytics, after “package confirmed”.

Cost: the flow is spread over many subscriptions and hard to trace.

StayHub orchestrates the money path, where someone must answer “where is this package stuck?”, and lets side effects react to events.

And before any saga between two of your own services, ask: should these be one service? If two tables always change together, one local transaction beats any saga.

09Your job as lead

You ask Claude Code to add compensations. It shows you this: try the refund, then release the room, and if anything fails, log the error. Errors are handled, it says.

That's exactly the refund that ran once, and it forgets the transfer. Ask for the undos in reverse order, each with its own key, retried until done, with the progress saved.

For any flow across services, ask four questions. What is the undo of each step? Which step is the pivot? What happens if the orchestrator crashes halfway? And what does the guest see in between?

Let's recap. No transaction reaches other companies. A saga gives every step a planned undo, run in reverse. Order the steps by how easy they are to undo: the charge as the pivot, the email last. Save progress with the next command, key every step, and retry the undos too. Next: two copies of a nightly job, both sure they're in charge.

Check yourself

0/10 answered
  1. 1Why can't one database transaction make "hold the room, charge the card, book the transfer" all-or-nothing?

  2. 2The flow holds the room, charges the card, then RideCo refuses and the code throws an error. What does the error undo?

  3. 3Why doesn't StayHub use two-phase commit with RideCo and the payment provider?

  4. 4In a saga, steps 1 and 2 succeeded and step 3 fails for good. What happens?

  5. 5Why does booking the transfer come before charging the card?

  6. 6Where does "send the confirmation email" go in the package saga?

  7. 7Claude Code's saga calls RideCo, gets a timeout, and immediately starts compensating. What do you ask for?

  8. 8The payment provider answers 503 to a refund. The compensation logs the error and the saga marks itself compensated. What happens?

  9. 9How should the orchestrator save its progress?

  10. 10Karim wants each service to react to the previous event, with no orchestrator. Where does that fit best?

Free account

Save your progress — create a free account

Free. No card. Your finished lessons follow you to any device, and you can ask questions in the community.

Create my free account
Founding members

Every lesson is free while we build. Lock in €9/month for later.

The first 100 members keep the founding price for as long as they stay. Reserving is free: no card, nothing is charged.

See the founding offer

Questions from the community

All questions →