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 lessonPrompt: "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.
| Step | Action | Kind | If repeated |
|---|---|---|---|
| 1 | Read the ticket | read-only | harmless |
| 2 | Look up the customer | read-only | harmless |
| 3 | Look up the order | read-only | harmless |
| 4 | Check the refund policy | read-only | harmless |
| 5 | Reserve a replacement unit | side effect | a second reservation ties up two units |
| 6 | Issue a refund of Rs 1,800 | side effect | the customer is refunded twice |
| 7 | Write the ledger entry | side effect | duplicate accounting row |
| 8 | Email the customer | side effect | two emails, confusing, but not costly |
| 9-12 | Open a shipping job, update the CRM, close the ticket, notify the warehouse | side effects | various |
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.
- It is naturally idempotent: "set order status to REFUNDED" gives the same state however many times you apply it.
- It carries an idempotency key, so the receiving system recognises the repeat and returns the first result instead of acting again (next section).
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:
- The key identifies the logical action, so it must not include things that change on retry (a timestamp, a random nonce, an attempt counter).
- It must still change when the intent changes. If the agent legitimately decides on a Rs 900 partial refund instead, the arguments differ and so does the key, which is correct.
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:
- Before the call: record
intent: issue_refund, key K, status: started. - 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 step | Meaning | Action |
|---|---|---|
done | It finished | Skip it, use the stored result |
started, no result | Unknown outcome, the crash was mid-call | Ask the tool by key whether it happened. If yes, store the result and move on. If no, repeat the call with the same key |
| nothing | The step never began | Run 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.
| Step | Compensation | Notes |
|---|---|---|
| 5 reserve replacement | release the reservation | clean |
| 6 refund Rs 1,800 | reverse or void the refund | may be impossible once settled |
| 7 ledger entry | write a reversing entry | never 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.
- Make "stuck halfway" a visible state. Mark the run
compensatingorneeds-review, notfailed, so nothing mistakes a half-undone run for a finished one. - Gate truly irreversible steps. For an action that cannot be compensated at all, an approval gate before it (see Guardrails) is the safety measure, not a compensation.
- Record every compensation so the audit trail shows both the action and its undo.
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:
- Per tool call: a timeout of 10 seconds for a lookup, longer for a known-slow export. A timeout makes the outcome unknown for side effects, so it triggers the key check from earlier, not a blind retry.
- Per model call: a timeout and a bounded number of retries for transient provider errors.
- Per run: a maximum step count (for example 25 for a workflow that needs about 12) and a wall-clock limit (for example 5 minutes). When the agent is looping, say calling the same tool with the same arguments three times, the budget stops it instead of letting it spin.
- Retry with backoff and jitter: waits of 1, 2 and 4 seconds, each randomised a little, so that a thousand runs that failed together do not all retry in the same second and flatten the service they are waiting on. Cap the attempts.
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.
| Class | Examples | Response |
|---|---|---|
| Model error | Malformed tool arguments, a tool that does not exist, an answer that fails the output schema, a looping plan | Return 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 fault | A business-rule rejection such as "order not yet delivered", a 4xx validation error | Do 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, transient | A timeout, a 5xx, a rate-limit 429 | Retry with backoff and the same idempotency key, up to the cap |
| Infrastructure error | The worker process dies, the host is restarted, the model provider is down, the network drops | Resume 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
- Classify every step as read-only or side-effecting before discussing retries, and say that read-only steps can be replayed freely.
- Build idempotency keys in code from run ID, step, tool and canonical arguments, never from the model, a timestamp or an attempt counter.
- Checkpoint after every step, and write intent before and result after each side effect so resume can tell done, unknown and not-started apart.
- For an unknown outcome, ask the downstream system by key instead of guessing, and admit the residual window when a tool has no idempotency support.
- Pair each side effect with a compensating action, run them in reverse order, make each idempotent, and mark the run needs-review.
- Put irreversible steps as late as possible and gate the ones that cannot be compensated.
- Set per-call timeouts, a max-step budget and a wall-clock limit, retry with capped backoff and jitter, and send exhausted runs to a dead-letter queue.
- Split errors into model, tool (deterministic or transient) and infrastructure, with a different response for each.
Related lessons
- The Agent Loop in Depth: ReAct, Plan-and-Execute, Reflection and Stop Conditions
- Designing Tools an Agent Can Actually Use
- Agent Memory: Working, Episodic, Semantic and Procedural, Without the Rot
- Context Engineering for Long-Horizon Agents
- Frameworks, Protocols and Durable Execution: MCP, A2A and Long-Running Agents
- MCP Servers, Prompt Injection, and Tamper-Evident Audit