Sagas Aren't Just a Pattern Anymore, They're the Only Honest Way to Move Money

Sagas Aren’t Just a Pattern Anymore, They’re the Only Honest Way to Move Money

Two-phase commit is dead in fintech. Here’s why the saga pattern with compensating transactions is the only realistic way to handle webhooks, card networks, and long-running payment flows.

Let’s be honest about what’s happening in fintech architecture right now: the two-phase commit you learned in your distributed systems class is a museum piece. It belongs next to the floppy disk and the fax machine when you’re dealing with payment providers, card networks, and webhook-based responses.

Here’s the reality. You submit a payment request, then you wait. Maybe seconds, maybe minutes, while the customer completes a bank challenge. The payment provider doesn’t care about your transaction coordinator. They won’t “prepare” on your behalf. And you definitely can’t hold database locks across services while a bank decides whether to approve a charge.

The saga pattern, first described by Garcia-Molina and Salem in a 1987 paper about long-lived database transactions, has become the default answer. It’s not new. It just took microservices and webhooks to make it unavoidable.

Why Two-Phase Commit Became a Non-Starter

The old model was elegant on paper: prepare everyone, commit everyone, or roll back everyone. The problem is that this assumes every participant plays the game. Your internal inventory service can play. Your payment provider with its own database, card network dependencies, and decision latency measured in minutes? Not a chance.

The reddit r/softwarearchitecture community has a blunt take on this: “short answer: you don’t. long answer: do not do distributed transactions.” Another commenter with payments experience put it more practically, they spent years at a payments company and “this is basically the whole job.” They never tried to make it one transaction. Instead, they wrote their own row as pending with an idempotency key, called the provider, and treated the webhook as just one way to move it forward.

That’s the saga pattern in production, minus the textbook language.

What a Saga Actually Promises

A saga is a sequence of local transactions, each with a compensating transaction that semantically undoes it. Instead of “nothing visible until everything commits”, a saga gives you an honest change of contract: every step commits locally, and if the workflow can’t finish, completed steps get semantically undone.

Compensation is not rollback. This distinction matters more in fintech than anywhere else. A rollback makes it as if the change never happened. A compensation is a new forward action that cancels the business effect: a refund, not a deleted charge. An apology email, because the first email cannot be unsent.

If your provider only supports one-step charges, the charge becomes your pivot point earlier, and failures after it need a refund compensation. That’s where the most expensive saga bugs live.

The Boxoffice Saga: A Concrete Walkthrough

Let’s look at a realistic purchase flow that touches inventory, payments, and tickets, systems that can never share a transaction:

Step Service Action Compensation Kind
1 Inventory Hold seat 14F (FREE to HELD, with an expiry) Release the hold Compensatable
2 Payment Authorise $85.00 on the card Void the authorisation Compensatable
3 Inventory Confirm the seat (HELD to SOLD) Release the seat Compensatable
4 Payment Capture the authorisation None in the normal flow Pivot
5 Tickets Issue the ticket and email it None Retriable

The pivot is step 4, capturing the payment. Before it, any failure triggers compensation. After it, every remaining step must be retriable. Once money has moved, unwinding means a refund, a statement entry, and a confused customer. Issuing a ticket is something you can always retry.

The ordering isn’t arbitrary. Authorise first because it’s cheap to void and tells you whether the card is good. Confirm the seat before capturing because confirmation can fail (the hold expired, or a bug elsewhere sold the seat), and that failure is cheap to compensate before money moves. Put steps most likely to fail for business reasons early, and the irreversible step as late as possible.

Here’s the classic failure scenario: the payment for 14F has been captured. Issuing the ticket fails because the email service is down. What should the saga do?

The answer is retry the ticket step until it succeeds. Refunding because an email service is down would turn a temporary outage into a lost sale. Capture is the pivot, the saga only moves forward after it.

Orchestration vs. Choreography: The Endless Debate

There are two ways to drive saga steps, and the tradeoffs are real:

Orchestration Choreography
Who decides the next step A central orchestrator that holds the saga’s state Each service, reacting to the previous service’s event
Where the flow is written down In one place, as a state machine or workflow code Spread across every service’s event handlers
Good for Sagas with several steps, branches and compensations Two or three steps with little branching
Typical failure The orchestrator becomes a dumping ground for business logic Nobody can say what state an order is in, cyclic event dependencies

For a five-step saga with three compensations, orchestration wins. Choreography is pleasant for short flows and painful when someone asks “why is order 8812 stuck?” Orchestration gives that question one place to look. But be careful, the orchestrator service anti-pattern is real, and a poorly designed orchestrator just recreates the monolith you were trying to escape.

The Crash Problem: What Your Orchestrator Must Persist

Here’s the part most tutorials skip: an orchestrator is a process, and processes restart. Everything needed to resume must be in durable storage, written after every step: the saga id, the current step, whether it’s running forward or compensating, and every value a later step or compensation needs, like the authorisation id that capture and void both require.

The dangerous moment is between performing a step and recording that it was performed. A crash there means the restarted orchestrator runs the step again. You cannot close that window. Every step and every compensation must be idempotent: safe to execute twice with the same effect as once.

The usual approach is to send an idempotency key derived from the saga id and the step name, so the payment provider recognises the second authorise as a repeat. Here’s what a minimal orchestrated saga looks like with persisted state:

STEPS = [
    ("hold", hold, release),          # compensatable
    ("authorize", authorize, void),   # compensatable
    ("confirm", confirm, release),    # compensatable
    ("capture", capture, None),       # pivot: after this, only forward
    ("issue", issue, None),           # retriable
]
PIVOT = 3

class Orchestrator:
    def __init__(self, store, services, crash_at=None):
        self.store, self.s, self.crash_at = store, services, crash_at

    def _point(self, where):
        if where == self.crash_at:
            raise Crash(where)

    def _save(self, saga_id, rec):
        self.store[saga_id] = copy.deepcopy(rec)          # durable write

    def run(self, saga_id):
        rec = copy.deepcopy(self.store[saga_id])          # resume from durable state
        while rec["status"] == "RUNNING" and rec["step"] < len(STEPS):
            name, action, _ = STEPS[rec["step"]]
            self._point(f"before {name}")
            try:
                action(self.s, rec["data"])
            except Transient:
                continue                                   # retry (real code: backoff, budget)
            except Declined:
                if rec["step"] >= PIVOT:
                    raise                                  # forward-only steps must not decline
                rec["status"] = "COMPENSATING"
                self._save(saga_id, rec)
                break
            self._point(f"after {name}")                   # effect happened, not yet recorded
            rec["step"] += 1
            self._save(saga_id, rec)
        if rec["status"] == "RUNNING":
            rec["status"] = "DONE"
        while rec["status"] == "COMPENSATING" and rec["step"] > 0:
            name, _, compensate = STEPS[rec["step"] - 1]
            self._point(f"undo {name}")
            compensate(self.s, rec["data"])                # must be idempotent
            rec["step"] -= 1
            self._save(saga_id, rec)
        if rec["status"] == "COMPENSATING":
            rec["status"] = "CANCELLED"
        self._save(saga_id, rec)
        return rec["status"]
  

Three things matter here. The step index is saved only after the step’s effect, so a crash re-runs at most one step. Business failures switch the saga to compensating, while temporary failures are retried, because a timeout is not a “no.” And compensation walks backwards from the last completed step, saving after each one, so a crash during compensation resumes compensating rather than starting over.

An order service starts a saga in an orchestrator that logs each step and calls inventory, payment and shipping services in order. A decision checks whether all steps succeeded: yes leads to order approved, no leads to compensation in reverse order and order rejected.
An orchestrated saga: each step is logged, on failure compensations run in reverse order.

Timeouts Are Unknown Outcomes

If the authorise call times out, the card may or may not be authorised. Retry with the same key, or query the provider by key, before deciding. Never compensate on a timeout as if it were a decline.

This is where payments engineers earn their salary. A timeout says nothing about whether the provider acted. Compensating on a timeout can release a seat while an authorisation stays on the card. That’s how you get customers with held charges and no booking.

Compensations can fail too. A void can hit the same outage as the authorise. Compensations must be retried until they succeed, never abandoned after a few attempts. When retrying cannot work, an authorisation expired by itself, an account closed, move the saga to a state that a human handles, and alert on it.

The other rule that catches teams off guard: steps after the pivot must not have business failures. If ticket issuing can be refused for a business reason, move that check before the pivot. A forward-only step that can say “no” leaves you with money and no product.

The Real-World Banking Implementation

This isn’t theoretical. There’s a banking system implementation with a fraud service that shows exactly how this plays out in production code. The architecture is event-driven: a client enters through the gateway to create accounts, transfer funds, verify suspicious transfers with OTP, or initiate external payments.

Transfers debit the sender, undergo fraud checks, then complete or trigger compensating refunds. Kafka events connect these stages to account updates and notifications. The transaction service’s TransactionService.java acts as the saga orchestrator, delegating to the account API for debits and credits, publishing events to Kafka, and advancing the saga based on fraud check results.

Here’s what’s interesting: the fraud detection service checks balance, tracks velocity and average in Redis, then publishes the check result. If the fraud check fails, the saga triggers compensation, refunding the debit. The orchestration pattern handles this cleanly because the saga state lives in one place.

Isolation: The Part Sagas Leave to You

A database transaction hides intermediate state from other transactions. A saga does not. While an order saga is running, another request can read the reserved stock, or a second saga can modify the same record.

The standard countermeasures:

  • Semantic locks. Mark records as in progress (an order in PENDING, stock in RESERVED) so other operations know to wait or refuse. The HELD state is a lock expressed in the data, not a database lock held across the workflow. The expiry on the hold makes sure an abandoned saga doesn’t hold the seat forever.
  • Commutative updates. Design operations so they give the same result in any order, such as incrementing and decrementing counts instead of setting them.
  • Reread before writing. Check that a value hasn’t changed since the saga read it, and fail or restart if it has. Confirm with WHERE state = 'HELD' AND hold_id = ? so a lost hold fails cleanly instead of overwriting someone else’s purchase.

Durable Workflow Engines vs. Hand-Rolled

You can write the orchestrator yourself with a table in your database for saga state. Or you can use a durable execution engine. Temporal lets you write the saga as ordinary code: the workflow function calls activities (the steps), and the engine records every result in an event history, so after a crash it replays the workflow to the same point and continues. AWS Step Functions offers a similar idea as a state machine definition with retry and catch clauses.

The tradeoffs are real in both directions. An engine gives you persistence, retries, timers, and visibility that a hand-rolled orchestrator has to rebuild, and it’s been tested against crashes far more than your version will be. In exchange, you operate or pay for another system that every purchase depends on, and you accept its programming model: Temporal workflow code must be deterministic, and changes to running workflows need explicit versioning.

Neither choice removes the need for idempotent steps, a pivot, and compensations designed by someone who understands the business.

When Not to Use a Saga

Sagas are not a universal solution. Do not use one where a local transaction would do, splitting one database into services and then reassembling atomicity with a saga is a self-inflicted cost. Do not use one where you need isolation the semantic-lock tricks cannot provide, such as an invariant over many rows that concurrent sagas could jointly violate. And do not use one when steps cannot be compensated or retried, because then the saga only describes a failure, it doesn’t handle it.

This is also where the transactional outbox pattern pairs naturally with sagas, because each step must update its database and send a message without losing either.

The AI Assistant Problem

If you’re using AI assistants to write sagas, be careful. Assistant-written sagas commonly put the whole flow in one function with try/except blocks that call compensations inline. That handles exceptions, not crashes: if the process dies, nothing remembers the saga existed.

The recurring flaws are compensations without idempotency checks (a restart refunds twice), compensating on timeouts, and steps after the pivot that can decline. Consider this compensation code an AI assistant generated for a failed seat confirmation:

async def compensate_failed_confirm(saga_id, store, payments, inventory):
    saga = await store.load(saga_id)

    # confirmation failed after the charge: give the money back
    refund = await payments.refund(
        charge_id=saga.data["charge_id"],
        amount=saga.data["amount"],
    )
    saga.data["refund_id"] = refund["id"]
    saga.status = "REFUNDED"
    await store.save(saga)

    await inventory.release(saga_id, saga.data["seat"])
    saga.status = "CANCELLED"
    await store.save(saga)
    return saga.status
  

The flaw: the refund is not idempotent. If the orchestrator crashes after the provider processes the refund but before store.save, the restarted orchestrator runs this compensation again and refunds a second time. The fix is to check whether a refund_id is already recorded and to send an idempotency key with the refund call.

Every step and compensation needs an idempotency key derived from the saga id and step name. That’s non-negotiable when real money is involved.

The Honest Contract

The saga pattern asks you to give up a comforting illusion: that “nothing visible until everything commits” is achievable across systems you don’t control. In exchange, you get eventual consistency with semantic guarantees, and systems that actually work with payment providers, webhooks, and card networks.

For fintech, this isn’t a trend. It’s the only honest way to build. The architecture of systems like the banking saga implementation, with its orchestrator, fraud service, Kafka events, and Redis state, shows what production-grade looks like. The domain-driven design principles that underpin these distributed systems matter more than ever, especially as AI generates more of the code.

Test your saga with crashes injected at every step boundary. Assert your invariants: a sold seat has exactly one capture and one ticket, and a cancelled saga has no net charge. Then, and only then, can you call yourself a distributed systems engineer who’s actually ready for fintech production.

Share:

Related Articles