FDE Times dataFDE jobs open 932▼14 Change in open roles over 7 days, like-for-like: roles from companies we started tracking this week are left outNew in 7 days 62Companies hiring 202Remote-friendly 24%Median US pay $201kTop hirer Databricks 92
中文VI

The newspaper of the Forward Deployed Engineer

Guides

When an agent fails across three systems, rollback can't save you

A saga records how to undo every committed step, and flags a human when the compensation itself fails.

ShareLinkedInFacebookX

In brief

  • A compensating transaction is a new transaction that runs after the original step has committed, and its logic depends on the business operation involved.
  • Record each step with the way to undo it, attach an idempotency key to every call, retry first, and compensate only when there is no way forward.
  • An irreversible step, such as sending an email, belongs after every check. If a compensation itself fails, stop and call a human.
Decision tree for when a saga step reports an error. If the error is transient, retry with the same idempotency key, up to 3 times. If it still fails, or the error is not transient, the orchestrator compensates from the log. If the compensation succeeds, the outcome is compensated. If the compensation also fails, the outcome is needs_human and the saga awaits human review.
The orchestrator compensates only when it cannot move forward. If the compensation itself fails, needs_human is a separate state for the caller to inspect and raise an alert.

A refund agent that writes to three systems has no shared transaction to roll back. Take one that reserves stock in the warehouse system, creates a credit note in the ERP and then emails the customer a confirmation. Step two returns an error, but step one has already committed. The warehouse is now holding a batch of goods that nobody needs.

Sagas exist for this situation. As the Azure Architecture Center describes it, a large operation is split into a chain of local transactions, and when one step fails, the saga runs compensating transactions to reverse the steps before it.

For an FDE, this is everyday work rather than distributed-systems theory. The more write access an agent gets to a client’s systems, the earlier in the review someone asks what happens when it fails halfway. This guide builds a small orchestrator in Python so that you have a concrete answer.

What will you build, and what do you need?

The result is an orchestrator that runs three steps in sequence. It logs each step, retries on transient errors, compensates from the log when it cannot go forward, and flags a human when a compensation fails. All you need is Python 3 and a text editor.

Every external system here is a mock function. The code is simplified to teach the principle and is not ready for production.

Step 1: Which step has no way back?

Before writing any code, classify each step. Microsoft’s saga documentation calls the step with no way back the pivot transaction: once the pivot succeeds, compensations no longer make sense, and the steps that follow it must be retryable until they finish.

An email to a customer is the typical example, because nobody can recall it. The design rule that follows is clear: run an irreversible step only once every important check has passed.

STEPS = [
    {"name": "reserve_stock", "kind": "compensable", "undo": "release_stock"},
    {"name": "create_credit_note", "kind": "compensable", "undo": "void_credit_note"},
    {"name": "send_customer_email", "kind": "pivot", "undo": None},
]

Check: every step whose undo is None must sit at the end of the list. If the agent has to send an email midway, that is a sign to split the work into two workflows, each ending in its own irreversible step.

Step 2: Record the undo as you go

The core mechanism is to record each step together with the way to undo it. When the operation fails, the workflow winds back through the completed steps. The log must live outside the process’s memory and be read back at startup; otherwise a single crash wipes out all progress.

import json, os

class SagaLog:
    def __init__(self, path):
        self.path = path
        self.entries = []
        if os.path.exists(path):  # restarting after a crash: load earlier progress
            with open(path) as f:
                self.entries = json.load(f)

    def record(self, step, status, undo=None):
        self.entries.append({"step": step, "status": status, "undo": undo})
        with open(self.path, "w") as f:
            json.dump(self.entries, f, indent=2)

    def is_undone(self, step):
        return any(e["step"] == step and e["status"] == "undone" for e in self.entries)

Check: call record, kill the process, then create a new SagaLog with the same path. entries must contain the same lines you wrote, each showing which step finished and which command reverses it.

Step 3: Does a duplicate call corrupt the data?

Retrying means a step may run more than once, so every step must be idempotent. Stripe offers a working example: for each idempotency key, it stores the status code and body of the first request, whether that request succeeded or failed, and returns the same result for every retry with that key.

def idem_key(saga_id, action):
    return f"{saga_id}:{action}"

_seen = {}  # simulates the client's system storing results by key
def fake_reserve_stock(key):
    if key not in _seen:
        _seen[key] = {"reserved": 5}
    return _seen[key]

Check: call fake_reserve_stock twice with the same key. The stock must be reserved only once.

Step 4: Retry first, compensate later

A passing network error is no reason to cancel a whole operation. Compensate only when there is no way forward: the retries have run out, or the error is known not to be transient.

class Transient(Exception): pass
class Permanent(Exception): pass

def run_with_retry(fn, key, attempts=3):
    for _ in range(attempts):
        try:
            return fn(key)
        except Transient:
            continue
    raise Permanent(f"retries exhausted: {key}")

def run_saga(saga_id, steps, systems, log, priority=()):
    done = []
    for s in steps:
        try:
            run_with_retry(systems[s["name"]], idem_key(saga_id, s["name"]))
            log.record(s["name"], "done", s["undo"])
            done.append(s)
        except Permanent:
            log.record(s["name"], "failed")
            # returns "compensated" or "needs_human" depending on how compensation goes
            return compensate(saga_id, done, systems, log, priority)
    return "completed"

This is the orchestration style in Microsoft’s saga documentation: the orchestrator sends requests, stores and interprets the state of each task, and handles recovery with compensating transactions. The price is that the orchestrator becomes a potential point of failure, which is one more reason to keep the log on disk.

Step 5: In what order do you compensate, and what if that fails too?

The default is the reverse of the order in which the steps ran, but that is not mandatory. The data store most sensitive to inconsistency should be undone first. In this example, the accounting ERP probably matters more than the warehouse.

A compensation can itself fail. The system therefore has to record its progress so that it can resume from the point of failure. Sometimes it must stop, ask for human intervention and send an alert that states the reason.

def compensate(saga_id, done, systems, log, priority=()):
    ordered = sorted(reversed(done), key=lambda s: s["name"] not in priority)
    for s in ordered:
        if log.is_undone(s["name"]):
            continue  # already compensated in an earlier run, skip
        try:
            run_with_retry(systems[s["undo"]], idem_key(saga_id, s["undo"]))
            log.record(s["name"], "undone")
        except Permanent as e:
            log.record(s["name"], "needs_human", str(e))  # reason goes in the undo field for brevity
            return "needs_human"  # stop and wait for a human
    return "compensated"

The return status is easy to overlook. If run_saga still reports “compensated” when compensation stopped midway, the caller will assume everything is clean while the warehouse is still holding stock. That is why needs_human must be a separate status that the caller can check in order to raise an alert.

Check: make create_credit_note raise Permanent. The log must show reserve_stock done, create_credit_note failed, then reserve_stock undone; run_saga must return "compensated", and the email must never be sent. Next, make release_stock fail as well: the log must stop at needs_human and run_saga must return "needs_human". Fix release_stock and call compensate again with a new SagaLog opened from the same file: any step already marked undone is skipped, and only the unfinished one is compensated.

Step 6: Two sagas touch the same customer

Say a customer sends two requests in a row. If two sagas run in parallel on the same order, a compensation from one can land between the forward steps of the other. The Sequential Convoy pattern deals with this by grouping messages under a key such as the order ID. Each group is processed in sequence, while different groups still run in parallel.

The trap is the poison message. A message that keeps failing blocks every message behind it in the same session. You need to count deliveries and move the message to a dead-letter queue once it passes the retry threshold. The sample code leaves this out, but do not skip it in production.

Common mistakes

The most common mistake is to treat a compensation as an Undo button. Wikipedia defines a compensating transaction as a new transaction that reverses the effects of one already committed, which makes it different from a rollback.

Nor does a compensation return the system to its original state. It has to account for work running concurrently, and that logic depends on the application.

The second mistake is to forget that sagas have no isolation. The result of the original step is visible to other systems before it is compensated, so lost updates and dirty reads can occur. There are familiar countermeasures: a semantic lock (an application-level flag saying the record is being updated), commutative updates, and rereading a value before writing it.

The third mistake comes from the agent. In ambiguous or high-impact cases, the workflow should stop and wait for human approval. Do not let the LLM decide whether to compensate. Let the orchestrator decide by rule, with the agent limited to making proposals.

What does this look like at a client site?

In the first week, hold off on writing the orchestrator. Sit down with the client’s operations team and go through each API the agent will write to. Does it accept an idempotency key? What is the undo command? Who is allowed to step in when the undo fails? The table of answers becomes your STEPS.

When you read FDE job descriptions, look for phrases such as “multi-system workflows”, “ERP/CRM integration” or “agents with write access”. On a CV, a line such as “designed a saga for a refund agent: isolated the pivot step, idempotency keys on every write, escalation process for failed compensations” says more than any claim of “experience with distributed systems”.

Agents will fail halfway at some point. What the client remembers after the incident is whether you could immediately open a log file showing which steps ran, which were compensated and which are waiting for a human.

Was this article useful?

Use with your AI assistantAsk Claude ↗Ask ChatGPT ↗
5 sources
Read next on the roadmap · Stage 3: Applied AINo access to the client's CRM? Build the MCP demo anywayA one-file Python server in Claude Code settles the hardest part, tool design, so that only the data layer changes when the real system arrives.