Cruxly

Cruxly › AI engineering › Agentic Systems

Reliable Agents: Retries, Idempotency, Checkpoints and Sagas

a crash at step 8 must not repeat steps 5 to 7, and a failure at step 9 must be undone, not ignored

Open the interactive lesson

Prompt: "Our support agent runs a 12-step workflow for a damaged-item complaint: read the ticket, look up the customer and order, check the policy, reserve a replacement, issue a refund, write the ledger entry, email the customer, and so on. Last night one run died at step 8, and another failed at step 9 after steps 5 to 7 had already changed things. What do you do differently so neither leaves a mess?"

40 minutes first. Sort the 12 steps into read-only and side-effecting before you say anything about retries. Everything else depends on that split.

A 12-step run dies at step 8: what is safe to retry

Start with a table of steps, because the answer to "can I retry it" is a property of the step, not of the agent. Here is the run, illustratively.

StepActionKindIf repeated
1Read the ticketread-onlyharmless
2Look up the customerread-onlyharmless
3Look up the orderread-onlyharmless
4Check the refund policyread-onlyharmless
5Reserve a replacement unitside effecta second reservation ties up two units
6Issue a refund of Rs 1,800side effectthe customer is refunded twice
7Write the ledger entryside effectduplicate accounting row
8Email the customerside effecttwo emails, confusing, but not costly
9-12Open a shipping job, update the CRM, close the ticket, notify the warehouseside effectsvarious

The naive recovery is to restart the run from step 1. Steps 1 to 4 are fine to repeat. Steps 5 to 7 are not: the restarted agent has no memory that it already refunded, and a fresh model call may even decide differently this time. The process that died at step 8 left the world partly changed, and a "from scratch" retry doubles those changes.

The rule is: retry read-only steps freely, retry side effects only when they are safe to repeat, and a side effect is safe to repeat in two cases.

Anything that is neither, such as "append a row" or "send an email" with no dedupe, must not be blindly retried. It needs a check first: did this already happen?

There is also a subtler case: the step that died mid-call. If the process crashed while step 8's email request was in flight, you do not know whether the email was sent. This is the state to design for, because it is where double-sending comes from. It is called an unknown outcome, and the only safe move is to ask the downstream system (by key) rather than guess.

Idempotency keys, and checkpoints that make resume safe

An idempotency key turns "retry" from a risk into a non-event. The caller sends the same key with every attempt of the same logical action. The receiving system stores the key with the result: the first attempt acts and records the outcome, and any later attempt with that key returns the recorded outcome without acting again.

Build the key in code, never ask the model for it. A model asked to produce a key can produce a different one on a retry, and then the server sees two requests. Derive it from stable facts:

key = hash(run_id, step_number, tool_name, canonical_args)
refund key = hash("run-4471", 6, "issue_refund", {"order": "ORD-88213", "amount": 1800})

The same step of the same run always sends the same key. Two points that interviewers like:

Checkpoint after every step, so resume starts where the run stopped. The checkpoint holds the run ID, the step index, the outputs of finished steps and the state the next step needs. For a side-effecting step, write twice:

  1. Before the call: record intent: issue_refund, key K, status: started.
  2. After the call: record status: done, result: ....

On resume the runner reads the last checkpoint and finds one of three situations.

Last record for the stepMeaningAction
doneIt finishedSkip it, use the stored result
started, no resultUnknown outcome, the crash was mid-callAsk the tool by key whether it happened. If yes, store the result and move on. If no, repeat the call with the same key
nothingThe step never beganRun it normally

This only works if the tool honours the key. Idempotency has to exist at the tool layer, the same discipline the Guardrails lesson applies to refunds. If a downstream API has no idempotency support, you wrap it: keep your own table of (key, result) and check it before every call, and accept that a crash between "call succeeded" and "result stored" is a residual window you reduce but cannot fully close, which is why reconciliation jobs exist.

Checkpoint store is for operations, not for the audit trail. It can be overwritten. Keep a separate append-only record if you need evidence (see the audit discussion in the Guardrails lesson).

Step 9 fails after steps 5 to 7 changed the world: compensating actions

Retrying cannot help when the failure is permanent. Suppose step 9 (open the shipping job) is rejected because the address is undeliverable. Steps 5 to 7 have reserved stock, refunded money and written a ledger row, and there is no database transaction to roll back, because these are separate systems. Leaving things as they are means a customer has a refund and a reservation for an order that is not being fulfilled.

The saga pattern is the answer: every side-effecting step has a paired compensating action, and on a permanent failure you run the compensations for the completed steps in reverse order.

StepCompensationNotes
5 reserve replacementrelease the reservationclean
6 refund Rs 1,800reverse or void the refundmay be impossible once settled
7 ledger entrywrite a reversing entrynever delete, append the opposite

Compensations are real actions and they fail too. They need their own idempotency keys, their own retries, and their own checkpoints. A saga whose undo step is not idempotent can double-undo.

A compensation is semantic, not literal. You cannot un-send an email. The compensating action is a second email ("please ignore the previous message"). You cannot always un-pay a refund either, which brings up the design rule that matters most:

Order the workflow so irreversible steps come as late as possible, after every step that might still fail. Do the validation, the address check and the stock reservation first, since those are cheap to undo, then refund, then send the email. The step after which you cannot go back is sometimes called the pivot. If the only thing left after it is retryable (a notification, a CRM update), the saga rarely needs to run at all.

Timeouts, step budgets, dead letters, and telling the three kinds of error apart

Every call and every run needs a limit, or the failure mode becomes "hung forever". For example:

Dead-letter handling is how a stuck run stops being everyone's problem. After the retry cap, or after repeated failed resumes, move the run to a dead-letter queue with its last checkpoint, the error and a readable summary. A person can fix the cause and replay it, or discard it. What you must not do is retry forever, or drop the run silently. Alert on the queue depth, because a growing queue is an incident.

Classify the error before you decide the response, since one blanket retry policy is wrong for two of the three.

ClassExamplesResponse
Model errorMalformed tool arguments, a tool that does not exist, an answer that fails the output schema, a looping planReturn a clear error message to the model and let it try again, with a small cap. Do not retry the identical call unchanged. If it keeps failing, escalate or switch to a more capable model
Tool error, caller's faultA business-rule rejection such as "order not yet delivered", a 4xx validation errorDo not retry. Feed the message to the model, since it may choose another action. Never repeat a call that will return the same refusal
Tool error, transientA timeout, a 5xx, a rate-limit 429Retry with backoff and the same idempotency key, up to the cap
Infrastructure errorThe worker process dies, the host is restarted, the model provider is down, the network dropsResume from the last checkpoint on another worker. For a provider outage, back off or fail over, and park the run if it persists

Why the distinction pays off: retrying a model error with the same input wastes tokens and produces the same mistake, while giving up on a transient tool error throws away a run that would have succeeded on the second try. And note that a model error that reaches a side-effecting tool is a safety issue, which is why the validation lives in the tool.

Follow-ups they will ask

"Does a checkpoint after every step not slow things down?" A small write per step is cheap next to a model call that takes seconds. If it matters, checkpoint after each side-effecting step and at the end of each read-only batch. The cost of skipping it is repeating work you cannot repeat.

"Where do the checkpoints live?" In a durable store outside the worker process: a database row per run or a workflow engine's history. Anything in memory dies with the process. Durable execution engines package this (replay-based resume, retries, timers), and the Frameworks, Protocols and Durable Execution lesson covers them.

"What about LLM nondeterminism on resume?" Do not re-run completed steps' model calls and hope for the same output. Store each step's result in the checkpoint and replay from the stored values. The model is consulted only for steps that have not happened yet.

"Two workers pick up the same run, what then?" Use a lease or lock on the run, with an expiry so a dead worker's lease lapses. The idempotency keys are the second line of defence if the lease is ever violated.

"How would you test this?" Fault injection: kill the process at every step boundary and in the middle of every side-effecting call, resume, and assert the world has exactly one refund, one reservation and one ledger row. Add a test where a tool times out after succeeding server-side.

"What if the compensation is impossible?" Then it is not a saga step but a pivot: put it last, put an approval gate before it, and give the customer-facing fix to a human.

How to say it in the interview

"I would start by marking each step as read-only or side-effecting, because that decides what is safe to retry. Read-only steps I can repeat freely. Side-effecting ones need an idempotency key built in code from the run ID, the step and the arguments, so a retry that reaches the server twice has the effect once. I would checkpoint after every step, and for side effects write the intent before the call and the result after, so a run that dies at step 8 resumes at step 8 and, if the result is missing, asks the other system by key whether it happened, instead of repeating steps 5 to 7. If step 9 fails permanently, I run compensating actions for the earlier changes in reverse order, a saga, and I order the workflow so the steps that cannot be undone come last. Around all that sit timeouts, a step budget, and a dead-letter queue so a stuck run is parked with its state instead of retried forever. And I would classify each failure as a model error, a tool error or an infrastructure error, because each gets a different response."

Checklist

Practice this interactively
Share this lessonWhatsAppLinkedInX

Related lessons