GOAT EngineerPreparing your learning space…

System Design · Concept Library · Free article

Distributed Transactions & Sagas — Committing Work Across Services That Can’t Share One Transaction

How to make a multi-step operation whose steps live in different systems — charge a card, then grant Pro — end all-or-nothing, when there’s no single database transaction to wrap them in. Why two-phase commit doesn’t fit across services and a payment provider, the saga that replaces it (local transactions plus compensating undos), orchestration vs choreography, and the isolation you give up — for interns through principal engineers.

A distributed transaction is one logical operation whose steps live in different systems — charge a card in the payment provider, then grant Pro in your own database — with no shared transaction to make them succeed or fail together. The classic fix, a two-phase commit, makes every participant lock its resources and wait for a central coordinator to say commit; that works inside one datacenter and falls apart across independent services and an external provider that has no prepare phase and no interest in holding a lock for you. So you give up atomic-everywhere and buy something weaker but workable: a saga — the operation as a sequence of local transactions, each paired with a compensating action that semantically undoes it. If a later step fails, you run the compensations in reverse (the charge went through but granting Pro failed, so you refund), and the customer ends fully upgraded or fully refunded, never charged-and-stranded. You can drive the sequence from a central orchestrator or let each service react to the previous step’s event (choreography). The price is honesty about isolation: a saga’s half-finished state is visible to everyone else while it runs, so you engineer around it instead of pretending it can’t happen.

The card is charged, the server dies, and the customer is still on Free

Hatch just launched a paid Pro tier, and the upgrade looks like the simplest thing in the world: charge the customer’s card, then flip their account to Pro. Two steps, one right after the other. On the happy path it works every time. Then, on launch night, a server crashes in the one-in-a-thousand instant that matters — right after the payment provider charged the card $8, but before the line of code that grants Pro ran. The money is gone. The account still says Free. And your own database has no record that any of it happened.

This is a different kind of bug from anything in the first thirteen chapters. A slow read you cache; a lost node you fail over; a duplicate text you make idempotent. But here two separate systems — the external payment provider and your database — each did their own thing correctly, and the operation as a whole is wrong. Half of it committed. There was no single switch that made both steps land together or neither land at all, because the two steps live in two systems that have never heard of each other.

And notice what makes it unforgivable here specifically: the effect is money. A half-finished read is invisible; a half-finished charge is a customer paying for nothing, emailing you furious, and disputing the charge with their bank. Money is where partial failure stops being a theoretical concern and becomes the product.

Why you can’t just wrap it in a transaction

The instinct is right and worth saying out loud: if this were two rows in one Postgres database — debit a balance, credit another — you would open a transaction, do both writes, and commit. If anything failed in between, the database rolls the whole thing back to how it started, as if you never touched it. That is the cleanest tool in all of systems, and when the whole operation lives in one database you should reach for it every time.

A database transaction can do that because it controls everything involved. It holds the locks, it owns the write-ahead log, it decides what commit and rollback mean, and it can undo any change because it has not truly finished until it says so. The moment a step in your operation lives somewhere the database does not control — a different microservice with its own database, or an external payment provider on the other end of an HTTPS call — that power evaporates. Your database can roll back its own row. It cannot roll back a charge that already settled on a card at a company it has no authority over.

So the real problem statement sharpens: you have an operation with two or more steps, each of which commits independently in a system you do not fully control, and you need the overall result to be all-or-nothing anyway. There are two families of answers. The first tries to force the independent commits into one synchronized commit — that is two-phase commit, and it is where most people start. The second gives up on synchronized commit and instead makes the operation recoverable — that is the saga. We will look hard at the first, see exactly where it breaks for us, and let that failure invent the second.

Two-phase commit: make everyone vote, then make everyone wait

The classic way to make several independent systems commit together is a two-phase commit, run by a central coordinator. It happens in the two phases its name promises. In the prepare phase the coordinator asks every participant one question: can you commit this, and will you promise to commit it if I tell you to? Each participant does all the work up to the very edge of committing — validates, reserves, writes to its log — locks the rows involved, and answers yes or no. Only if every participant votes yes does the coordinator move to the commit phase and tell them all to finish. If even one votes no, it tells everyone to abort, and because each held its changes at the edge, they can all cleanly back out.

On paper it delivers exactly the atomicity we lost: all commit or none do. This is real technology — it is the XA standard, and databases and message brokers inside a single datacenter use it. The reason we do not reach for it here is not that it is wrong; it is that its central assumption — everyone holds their locks and waits for the coordinator — is a promise our participants cannot or will not keep.

Look at what has to stay frozen between the vote and the commit. Every participant has locked its rows and is holding them, doing nothing, until the coordinator comes back. Flip the toggle and feel how that plays out when one participant is slow — and what happens to everyone else while it thinks:

The interactive version of this example is available when JavaScript loads.

So two-phase commit is the right answer to the wrong shape of problem. It fits a few databases inside one datacenter that trust a coordinator and can afford to hold locks for milliseconds. It does not fit a long, loosely-coupled operation that reaches out to an independent service and an external provider over a flaky network. We need something that never asks anyone to hold a lock and wait — something that accepts each step will commit on its own, and makes the operation survive that instead of preventing it.

The saga: a sequence of local commits, each with an undo

The saga flips the whole strategy. Instead of trying to make the steps commit together, it lets each step commit immediately and on its own — a real, local, fully-finished transaction in one system — and pairs every step with a compensating action that can semantically undo it later. The operation becomes a sequence: do step one and commit it, do step two and commit it, and so on. If every step succeeds, you are done. If a step fails partway through, you walk back through the steps that already committed and run each one’s compensation in reverse order, until the world is back to a consistent state.

For the Pro upgrade the sequence is short: charge the card (commit), then grant Pro (commit). If granting Pro fails after the charge already went through, the saga runs the charge’s compensation — a refund — and the customer lands back where they started, minus nothing. Nobody is charged-and-stranded, because the only two outcomes the saga allows are all steps done or all committed steps undone. Step through it, and try failing the grant to watch the compensation fire:

The interactive version of this example is available when JavaScript loads.

What you traded is worth naming plainly. A two-phase commit gives you a real all-or-nothing instant — the world never observes a half-done state because nothing commits until everything is ready. A saga has no such instant. Its steps genuinely commit one at a time, so for a stretch of real time the charge has happened and Pro has not, and that half-finished state is really out there. The saga does not prevent the intermediate state; it guarantees you climb out of it. That difference — prevention versus recovery — is the entire trade, and it comes back to bite in the isolation section later.

A compensation is a new fact, not a rewind

It is tempting to picture a compensation as an undo button — press it and the step vanishes as if it never ran. That mental model is wrong, and the difference matters. A database rollback truly erases: it throws away uncommitted changes so no one ever saw them. A compensation cannot do that, because the thing it is undoing already committed and the world already reacted to it. The charge really settled on the card; the customer’s bank really saw it. You cannot un-happen it. You can only add a new, opposite fact that cancels its effect: a refund. The money moved out and then moved back — two real events, not one erased one.

Because compensations run during failures — exactly when the network is flaky and things are being retried — they carry three requirements that ordinary code can skip. They must be idempotent: a refund that gets retried must not refund twice, so it carries the same kind of idempotency key you met in Chapter 2, now guarding the undo. They must be retryable: a compensation that fails cannot just give up, because giving up leaves the customer stranded — the very thing the saga exists to prevent. And they must essentially always be able to succeed: you design steps so their compensations can’t hit a wall, because there is no compensation for a failed compensation.

Orchestration vs choreography: a conductor or a chain reaction

A saga is a sequence of steps and compensations — but something has to actually drive it: decide what runs next, notice a failure, and kick off the compensations. There are two ways to arrange that, and the choice shapes how the whole system feels to build and to debug.

In orchestration, one component — an orchestrator, sometimes called the saga coordinator — owns the flow. It calls the billing step, waits for the result, calls the grant step, and if that fails, calls the refund compensation. The sequence lives in one place as explicit logic, like a conductor cueing each section of the orchestra in turn. In choreography, there is no central brain. Each service does its step and emits an event; the next service is subscribed to that event, reacts, does its step, and emits its own. The saga is not written down anywhere as a whole — it emerges from services reacting to one another, like dancers who each know their own next move from the music. Flip between the two and watch the same upgrade run:

The interactive version of this example is available when JavaScript loads.

The same saga, driven two ways.
OrchestrationChoreography
Where the flow livesIn one orchestrator, as explicit, readable logicSpread across services as event subscriptions — no single place shows the whole flow
CouplingServices are simple and unaware of the saga; the orchestrator knows everyoneNo central dependency, but each service must know which event to emit and react to
Debugging a stuck runEasy — ask the orchestrator where the saga is; it holds the stateHard — the state is implied by which events have and haven’t fired; you reconstruct it
Failure handlingCentralised — the orchestrator triggers compensations in orderDistributed — each service must know how to compensate and whom to notify
Best whenComplex flows, many steps, tight control and visibility needed (a payment upgrade)Simple, loosely-coupled flows where services should stay autonomous

Don’t reach for a saga by reflex

A saga is a real tool with a real cost, and the most common mistake is using one where you didn’t need one. Before you build compensations for everything, ask the cheapest question first: do these steps actually live in different systems? If the whole operation is rows in one database, you do not have a distributed transaction at all — you have a local one, and a plain database transaction gives you true atomicity for free. Do not trade that away for a saga’s weaker guarantees out of habit.

Reach for the lightest tool the shape allows.
If the operation is…UseWhy
Several writes inside one databaseA local database transaction (ACID)True all-or-nothing, real isolation, free rollback — nothing distributed to solve
A few trusted services in one datacenter that can hold a lock brieflyTwo-phase commit (XA), if you must have a synchronous atomic commitReal atomicity across participants — but only if every one can prepare-and-wait
Steps across independent services and/or an external provider, over a flaky networkA saga (local commits + compensations)No global locks, no coordinator to block on, survives partial failure by recovering — the Hatch upgrade
A saga with complex flow and high stakes (money)A saga, orchestratedCentral visibility and one place to answer "where is this stuck?"
A saga with few steps and services that should stay autonomousA saga, choreographedNo central dependency; the event chain is enough

A saga has no isolation — its half-done state is visible

Here is the part most explanations skip, and it is the one that bites in production. A database transaction gives you the I in ACID — isolation — which means no one else can see your half-finished work; the outside world only ever observes the before or the after, never the messy middle. A saga throws that away. Its steps commit for real, one at a time, so for the whole stretch between step one and the last step, the intermediate state is genuinely visible to everyone else in the system. The charge has landed and Pro has not, and any other query running right then can see exactly that inconsistent snapshot.

That open window causes three classic anomalies — the same ones a database’s isolation levels exist to prevent, now yours to handle by hand:

  • Dirty read — another process reads a value the saga wrote in a step that later gets compensated. A nightly revenue job reads the charge, counts the customer as paid, then the grant fails and the charge is refunded — the report is now wrong, built on money that flowed out and back.
  • Lost update — a concurrent transaction updates the same record without knowing a saga is mid-flight over it, and one of the two writes silently wins. The saga’s compensation and the concurrent edit stomp each other.
  • Fuzzy / non-repeatable read — two steps of the same saga read the same record and get different answers, because something changed it in between — so the saga makes a decision on stale data.

Watch the dirty read happen in the window, then close it. A support tool reads the account partway through the upgrade; flip on a countermeasure and see the difference:

The interactive version of this example is available when JavaScript loads.

The saga log: the flow has to outlive the machine running it

A saga can be a sequence of minutes or even days, and the orchestrator driving it will, at some point, crash in the middle. When it restarts, it has to know exactly where the saga was — which steps committed, which are pending, whether it was going forward or already compensating — or it cannot safely continue. The only way to know is to have written it down before each step. That durable record of a saga’s progress is the saga log: every step and its outcome, appended as it happens, so the state of an in-flight saga is always reconstructable from storage rather than held only in a process’s memory.

Writing a correct, crash-safe orchestrator with retries, timeouts, and a durable log is hard enough that it has become a category of infrastructure. Durable-execution engines — Temporal, AWS Step Functions, Netflix Conductor, Camunda — give you the orchestrator, the log, the retries, and the timers as a platform, so you write the saga as ordinary-looking code and the engine persists every step and resumes exactly where it left off after any crash. You do not have to build the log yourself; you do have to understand that one exists and why, because that is what the interview is really asking.

Failure modes and the gotchas that cause them

The nastiest saga failure is the one that fires the undo twice. Because compensations run during trouble — when the network is dropping replies and everything is being retried — a refund can easily be triggered more than once, and if it isn’t idempotent, you refund an $8 charge two or three times and hand real money away. This is the Chapter 2 lesson pointed at the undo. Slide the retry count and compare a blind refund with a keyed one:

The interactive version of this example is available when JavaScript loads.

The failure modes worth naming

  • The double compensation. A retried refund with no idempotency key runs twice and over-refunds. Fix: every compensation carries the same kind of idempotency key as a forward step, so a repeat is recognized and ignored.
  • The stuck / pending saga. A step neither succeeds nor definitively fails — the downstream service is just hanging — and the saga sits half-done forever. Fix: a timeout on every step that turns "no answer" into a decision (retry forward, or compensate back).
  • The compensation that itself fails. The refund call errors out, so the undo can’t complete and the customer stays stranded — the one outcome the saga exists to prevent. Fix: compensations must be retryable and designed to essentially always succeed; a compensation that can hard-fail is a design bug.
  • The poison saga. One malformed run keeps failing, retrying, and blocking the pipeline behind it. Fix: a retry ceiling plus a dead-letter path that parks the bad saga for a human instead of letting it wedge everything.
  • The un-compensatable step ran too early. An irreversible step committed and then a later step failed, leaving nothing to undo it with. Fix: the pessimistic ordering from earlier — put the step you can’t take back last.

Measuring and debugging a saga in production

A saga’s whole failure surface is invisible unless you instrument it, because a half-finished saga looks like nothing is wrong — no error is thrown, the request may have even returned. These are the numbers that tell you the truth:

  • In-flight saga count and age. How many sagas are open right now, and how old is the oldest? A saga that has been open far longer than the flow should take is stuck — this is your primary stuck-saga alert, and it’s the metric that catches the money-taken-no-Pro customer before they email you.
  • Compensation rate. What fraction of sagas end in compensation instead of success? A rising rate means a downstream step is failing often — the refund path working is good, but a spike in it is a symptom to chase.
  • Step-level success and latency. Which step fails or hangs most? That points you straight at the flaky participant instead of guessing across services.
  • Dead-letter depth. How many sagas gave up and parked for a human? Anything above zero is a queue of stranded operations that need eyes.
  • End-to-end trace per saga. A single correlation id threaded through every step and event so you can pull up one upgrade and see its whole story — indispensable for the choreographed case where the flow lives nowhere else.

What a saga costs, and when not to use one

A saga buys you correctness across services at a steep price in complexity, and paying it when you didn’t have to is its own kind of failure. Every step now needs a compensation you have to write, test, and keep correct as the business logic changes. You lose real isolation and take on the anomaly-handling yourself. You need a durable log, timeouts, retries, dead-letters, and the observability to see any of it. That is a lot of machinery — worth it when the operation genuinely spans systems and partial failure is unacceptable, and pure overhead when it doesn’t.

Signs you don’t need a saga

  • The whole operation fits in one database. Use a transaction — you have true atomicity and isolation for free; a saga would only take them away.
  • The steps don’t really have to be atomic. If it is fine for step two to happen later and independently, just emit an event and let it run on its own — you don’t need a coordinated undo, only eventual completion.
  • There is nothing to compensate. If no step moves money, ships a thing, or has any side effect you’d need to reverse, the failure handling a saga adds is scaffolding around an empty room.
  • One irreversible step, done once. If the operation is a single un-undoable action, a saga adds no safety — there is no earlier step to roll back and no later step whose failure you’re guarding against.

How real systems run distributed transactions

Every real approach is one of the two families you’ve seen — force a synchronous commit, or make the operation recoverable — plus infrastructure to make it bearable. Inside a single datacenter, databases and message brokers still use two-phase commit through the XA standard, where holding locks for milliseconds across a handful of trusted participants is affordable. Across services, the industry has largely moved to sagas, and the orchestrator has become a product: Temporal and Netflix Conductor and Camunda run your saga as durable code, persisting every step so it resumes after any crash; AWS Step Functions does the same as a managed state machine. Teams who prefer choreography wire services together over an event log like Kafka, each step reacting to the last one’s event.

Payment platforms are the canonical example because money forces the issue. Stripe and its peers hand you exactly the two primitives a saga needs: an idempotency key on every charge and refund so retries are exactly-once, and webhooks that confirm asynchronously — which is precisely why you also run a reconcile job, since a webhook can be dropped. Ride-share and travel bookings, order fulfilment, account signups that span three services — all of them are sagas underneath: a sequence of local commits, each with an undo, driven by an orchestrator that remembers where it is. Different products, one shape: give up the atomic instant, and buy back correctness with a log and a compensation.

The upgrade saga, step by step

The whole pattern reduces to an orchestrator that appends to a log before and after each step, so a crash at any point leaves a record it can resume from. In pseudocode:

The forward path (charge → grant)

  • Begin. ledger.append(txnId, "PENDING") — the saga is on the books before anything moves.
  • Charge, exactly-once. provider.charge(amount, key=txnId) then ledger.append(txnId, "CHARGED") — the same txnId is the idempotency key, so a retried charge never double-bills.
  • Grant Pro. accounts.setPlan(userId, "pro") then ledger.append(txnId, "GRANTED") — a local, trivially-reversible write.
  • Done. The customer is fully upgraded, and every step is written down in order.

The compensation path (grant failed → refund)

  • On grant failure, decide. Retry the grant a few times off the request path (forward recovery); if it still can’t complete, compensate.
  • Refund, exactly-once. ledger.append(txnId, "REFUND_REQUESTED"), then provider.refund(key=txnId + ":refund"), then ledger.append(txnId, "REFUNDED") — the refund carries its own idempotency key so a retried compensation pays out once.
  • Land clean. The customer ends fully refunded; the ledger tells the whole story — PENDING → CHARGED → REFUND_REQUESTED → REFUNDED.
  • Sweep the rest. A scheduled reconcile diffs the ledger against the provider and repairs any saga a crash left stranded between a provider call and its log write.

Pitfalls

  • Building a saga inside one database. The most common waste: the whole operation was local, so a transaction gave you true atomicity and isolation for free — and you traded them for compensations you now have to maintain. Check the boundary first.
  • Non-idempotent compensations. A refund without a key double-pays on retry, and compensations always get retried. Every undo needs the same idempotency key as a forward step.
  • Assuming isolation you don’t have. Code that reads a record mid-saga sees a half-done state — charged but not granted. Treat every in-flight record as unstable; use a semantic-lock status so readers know.
  • No timeout on a step. A step that hangs leaves the saga stuck forever with no error. Put a timeout on every step so "no answer" becomes a decision, not a limbo.
  • A compensation that can hard-fail. If your undo can permanently error, a failure strands the customer — the one thing the saga exists to prevent. Design compensations to essentially always succeed, with retries and a dead-letter.
  • The irreversible step in the middle. Put anything you can’t take back last, so no later failure can force you to undo the un-undoable.

Best practices

  • Use a transaction when you can — reach for a saga only when the steps genuinely span systems no single commit covers.
  • Log before you act — append the intended step to a durable log first, so a restart always knows where the saga was.
  • Make every step and compensation idempotent — carry an idempotency key end to end so any retry, forward or back, lands exactly once.
  • Order for regret — put the hardest-to-compensate step last, so nothing after it can fail and force an impossible undo.
  • Guard isolation by hand — a semantic-lock status on in-flight records so concurrent readers don’t act on a half-done state.
  • Instrument the invisible — in-flight saga age, compensation rate, and dead-letter depth, plus a reconcile job as the backstop.
  • Prefer orchestration for high-stakes flows — one place holds the state and answers "where is this stuck?"

Rapid-fire cheat-sheet (intern → principal)

"What is a distributed transaction?"
One logical operation whose steps commit in different systems — charge a card in the provider, grant Pro in your database — with no shared transaction to make them succeed or fail together. The problem is that the steps have separate commit points, so a crash between them leaves one done and the other not.
"Why not just use two-phase commit?"
It makes every participant lock its resources and wait for a coordinator, so a slow participant freezes everyone and a dead coordinator blocks the lot — and an external payment provider has no prepare phase to enlist in at all. 2PC fits a few trusted databases in one datacenter, not loosely-coupled services over a flaky network.
"What is the saga pattern?"
Run the operation as a sequence of local transactions, each committing on its own and each paired with a compensating action that semantically undoes it. If a later step fails, run the compensations in reverse so the system ends all-done or all-undone — never stranded mid-flight.
"How is a compensation different from a rollback?"
A rollback erases uncommitted work so no one saw it. A compensation can’t erase — the step already committed and the world reacted — so it adds a new opposite fact: a refund cancels a charge. Semantic undo, not a rewind. And because it runs during failures, it must be idempotent and retryable.
"Orchestration vs choreography?"
Orchestration: a central coordinator owns the flow and triggers compensations — easy to see and debug, best for complex, high-stakes flows like payments. Choreography: services react to each other’s events with no central brain — decoupled and simple for short flows, but the saga lives nowhere whole, so a stuck run is hard to trace.
"What do you give up with a saga, and how do you handle it?" (the principal one)
Isolation. The steps commit one at a time, so the half-done state is really visible and you get dirty reads, lost updates, and fuzzy reads. You rebuild isolation in the application — semantic locks on in-flight records, ordering the risky step last, commutative updates, reread-before-write — plus a durable log to survive crashes and a reconcile job to catch what still slips. A saga trades true atomicity for recoverability, and the senior job is managing everything that trade exposes.

The takeaway

By GOAT Engineer. Back to Concept Library. Privacy Policy · Contact.