Your Agent Retried the Failure. Then It Learned the Wrong Lesson.
Retries are not safe just because they use backoff. A failed agent attempt can carry stale evidence, speculative reasoning, malformed tool arguments, and ambiguous side effects into the next attempt. Build clean retry forks from validated checkpoints, reconcile uncertain writes, and make retry policy explicit.
On this page
At 2:17 PM, a refund agent sends a write request.
The payment service does not answer before the client timeout.
The agent sees:
TimeoutError: request exceeded 8sThen it does what many “resilient” agent loops are designed to do.
It retries.
But the retry does not start clean.
The model sees the entire failed attempt:
I think the refund probably did not go through.The payment tool timed out.I should try the refund again.So it issues the same business action a second time.
A minute later, the first request appears in the payment ledger.
It had succeeded before the network connection died.
The transport failed.
The business operation did not.
Now the agent has converted an ambiguous timeout into a duplicate side effect.
That is not primarily a prompt problem.
It is a retry-state design problem.
Distributed systems have spent decades learning that retries are not free: you need timeouts, backoff, bounded attempts, idempotency, and a way to reason about ambiguous outcomes.
Agents add another failure surface:
the context of the failed attempt can itself become contaminated.
A retry can inherit stale evidence, malformed tool arguments, speculative conclusions, error text, partial plans, and assumptions the model generated while trying to explain the failure.
So my production rule is simple:
A retry is a new execution attempt. It is not permission to inherit the previous attempt's entire reasoning history.
I want retries to fork from a validated checkpoint, carry forward only trusted state, attach a typed description of what failed, reconcile uncertain side effects, and stop when the failure class says another attempt is unsafe.
A retry is not one thing
Teams often implement a generic helper:
await retry(() => agent.invoke(state));That looks clean.
It also hides the most important question:
What exactly are we retrying?These are different operations:
| Retry type | Example | Typical risk |
|---|---|---|
| Transport retry | HTTP request failed before a response arrived | Duplicate request / retry storm |
| Read-only tool retry | Search API returned 503 | Extra latency and load |
| Side-effect retry | Create refund, send email, delete resource | Duplicate or conflicting effects |
| Reasoning retry | Model chose a bad plan | Repeating the same cognitive path |
| Retrieval retry | Evidence was stale or incomplete | Carrying stale evidence into new attempt |
| Workflow retry | Whole agent run restarts | Repeating already-completed steps |
AWS's reliability guidance explicitly warns that retries can amplify failures, should be bounded, and are safest when operations are idempotent. Stripe's API documentation makes the same business-side point concretely: an idempotency key lets a client retry a create/update request without accidentally creating the effect twice.
That solves an important class of retry bugs.
It does not solve the agent-specific question:
Which pieces of the failed attempt should the next model call be allowed to believe?That is where clean retry forks matter.
Why appending the error to the transcript is dangerous
A common agent loop looks like this:
user task→ model plan→ tool call→ tool error→ append tool error→ model sees everything→ "try again"For some recoverable tool errors, that is perfectly reasonable.
LangGraph's own guidance shows this pattern for LLM-recoverable failures: put a tool error into state and loop back so the model can react.
The problem is treating that pattern as universal.
The failed transcript can contain at least four categories of information:
1. immutable task intent2. validated external observations3. model-generated hypotheses4. invalid or ambiguous attempt-local stateOnly the first two deserve automatic trust on the next attempt.
Yet a raw conversation transcript gives all four similar visual weight.
The model may see:
Tool: timeoutAssistant: "The refund probably failed."Assistant: "The customer is eligible."Assistant: "Retry with the same amount."Those assistant messages are not facts.
They are artifacts of the attempt that just failed.
If you feed them back as history, the retry begins with an anchor.
The failed attempt can poison its successor
I see five recurring contamination modes.
1. Speculation becomes evidence
The agent says:
The write likely did not happen.The next attempt reads that sentence as prior context and behaves as if it were observed system state.
It was not.
2. Stale evidence survives invalidation
Attempt one retrieved:
account_status = ACTIVEThen a later tool call reveals the account was merged and the record is stale.
If the retry inherits the original retrieval blindly, it may still plan against ACTIVE.
3. Bad arguments become anchors
Attempt one called:
{ "accountId": "acct_813", "refundCents": 25000 }The tool rejects the account ID.
The next model now sees the exact malformed argument set in context.
Models are very good at pattern continuation.
Sometimes too good.
4. Error text changes the plan more than ground truth does
A verbose stack trace or provider-specific error message can dominate the attention budget.
The retry starts optimizing around the error string rather than the business objective.
5. Partial side effects are interpreted as “nothing happened”
This is the most dangerous class.
The agent knows the client call failed.
It does not know whether the business operation failed.
Those are different facts.
Treat attempt boundaries as trust boundaries
I would make the retry boundary explicit in the architecture.

The clean fork starts from:
immutable task intent+ validated checkpoint+ still-valid evidence+ side-effect ledger+ typed failure envelopeIt does not automatically include:
the previous chain of reasoningspeculative conclusionsinvalid tool outputssuperseded evidenceunverified assumptionsraw error noiseThis is the same reason I prefer raw structured state over prompt-shaped history in long-running agents.
State should describe what the system knows.
A transcript describes what the model happened to say.
Those are not equivalent data structures.
Partition state by trust and lifetime
I like to make the distinction concrete in types.
type EvidenceStatus = | "validated" | "invalidated" | "superseded";type Evidence = { id: string; kind: string; value: unknown; status: EvidenceStatus; observedAt: string; source: string;};type SideEffectState = | "none" | "confirmed_not_applied" | "applied" | "unknown";type FailureClass = | "transport" | "validation" | "tool_timeout" | "side_effect_unknown" | "stale_evidence" | "policy_block" | "semantic_conflict";type FailureEnvelope = { attemptId: string; failureClass: FailureClass; facts: string[]; invalidatedEvidenceIds: string[]; sideEffectState: SideEffectState; retryable: boolean;};type AgentCheckpoint = { taskIntent: string; evidence: Evidence[]; sideEffectLedger: SideEffectRecord[];};type SideEffectRecord = { operationId: string; idempotencyKey?: string; action: string; state: "pending" | "applied" | "not_applied" | "unknown"; externalRef?: string;};The important part is not these exact names.
It is the separation:
facts≠attempt-local reasoningand:
client error≠business-effect statusOnce those distinctions exist in state, your retry policy can reason about them deterministically.
Build the next attempt from trusted state
Here is the pattern I want:
type RetryContext = { taskIntent: string; evidence: Evidence[]; sideEffects: SideEffectRecord[]; failure: FailureEnvelope; instruction: string;};function buildRetryContext( checkpoint: AgentCheckpoint, failure: FailureEnvelope,): RetryContext { const invalidated = new Set( failure.invalidatedEvidenceIds, ); const evidence = checkpoint.evidence.filter( (item) => item.status === "validated" && !invalidated.has(item.id), ); return { taskIntent: checkpoint.taskIntent, evidence, sideEffects: checkpoint.sideEffectLedger, failure, instruction: "Start a new attempt from the trusted state. " + "Do not assume the prior attempt's hypotheses were true.", };}Notice what is missing:
previousAssistantMessagespreviousScratchpadpreviousPlanTextrawConversationDumpIf some prior conclusion matters, promote it into structured state after validation.
Do not preserve it merely because the model said it earlier.
The same pattern in Python:
from dataclasses import dataclassfrom typing import Any, LiteralEvidenceStatus = Literal[ "validated", "invalidated", "superseded",]SideEffectState = Literal[ "none", "confirmed_not_applied", "applied", "unknown",]FailureClass = Literal[ "transport", "validation", "tool_timeout", "side_effect_unknown", "stale_evidence", "policy_block", "semantic_conflict",]@dataclass(frozen=True)class Evidence: id: str kind: str value: Any status: EvidenceStatus observed_at: str source: str@dataclass(frozen=True)class FailureEnvelope: attempt_id: str failure_class: FailureClass facts: list[str] invalidated_evidence_ids: list[str] side_effect_state: SideEffectState retryable: booldef build_retry_evidence( evidence: list[Evidence], failure: FailureEnvelope,) -> list[Evidence]: invalidated = set( failure.invalidated_evidence_ids ) return [ item for item in evidence if item.status == "validated" and item.id not in invalidated ]This is intentionally boring code.
Retry safety should be boring.
Do not ask the model whether an ambiguous write succeeded
Suppose this happens:
POST /refunds→ request accepted by server→ refund created→ response lost→ client timeoutFrom the caller's perspective:
unknownThe wrong recovery strategy is:
LLM: "It probably failed. Try again."The right recovery strategy is:
reconcileAsk the system of record.
Use an operation ID.
Reuse the idempotency key.
Query the resource.
Inspect the effect ledger.
Only then decide whether replay is safe.

This is where classic distributed-systems patterns become essential for agent engineering.
Stripe documents idempotency keys specifically so a client can safely retry creation/update requests without duplicating the operation. AWS guidance similarly warns against retrying non-idempotent operations because retries can produce duplicated results.
The agent does not get to reason its way around that rule.
“Timeout” should mean “outcome unknown” until proven otherwise
I would avoid code like this:
try { await issueRefund(input);} catch (error) { return { status: "failed" };}A timeout may not mean failed.
A more useful result is:
type WriteOutcome<T> = | { status: "applied"; value: T } | { status: "not_applied"; reason: string } | { status: "unknown"; operationId: string; idempotencyKey: string; };Now the workflow has a state it can handle honestly.
async function recoverUnknownWrite( outcome: Extract< WriteOutcome<unknown>, { status: "unknown" } >,): Promise<"applied" | "not_applied" | "unknown"> { const status = await getOperationStatus( outcome.operationId, ); if (status === "applied") return "applied"; if (status === "not_found") return "not_applied"; return "unknown";}If reconciliation still returns unknown, I would usually stop the autonomous retry for a consequential write.
Ambiguity is not a reason to become more aggressive.
It is a reason to reduce autonomy.
Classify the failure before deciding to retry
A global maxRetries = 3 is not a retry policy.
It is a counter.
I want the retry decision to depend on the failure class.
| Failure class | Retry? | Context policy |
|---|---|---|
| HTTP 503 on read-only search | Usually yes, bounded + backoff | Keep trusted state |
| Rate limit | Usually yes after server/backoff delay | Keep trusted state |
| Schema validation failure | Maybe one repaired attempt | Drop malformed arguments |
| Stale evidence | Re-retrieve before retry | Invalidate old evidence |
| Policy block | No autonomous retry | Escalate/change authorization |
| Ambiguous side effect | Not until reconciled | Preserve operation identity |
| Semantic contradiction | Maybe, from clean checkpoint | Exclude unsupported hypothesis |
| Repeated same failure | Usually stop | Escalate or choose alternate path |
Notice that “retryable” is not only a property of the exception.
It is a property of:
failure class× operation semantics× side-effect state× attempt history× risk tierBackoff solves load. It does not solve contaminated reasoning
Exponential backoff and jitter are excellent tools.
They prevent clients from synchronizing retry storms and hammering a struggling dependency. AWS has documented this pattern extensively.
But this:
wait 1swait 2swait 4sdoes not make the agent's reasoning cleaner.
If attempt two receives the same poisoned state, you have delayed the same mistake.
So I think of retry safety as two independent layers:
distributed-system retry safety+agent-state retry safetyThe first includes:
timeoutsbounded attemptsbackoffjitteridempotencycircuit breakersThe second includes:
checkpointsstate validationevidence invalidationclean context forksfailure envelopesside-effect reconciliationYou need both.
Checkpoints should represent recoverable truth
LangGraph's durable execution model is useful here because node boundaries can act as checkpoints; its documentation notes that smaller nodes create more frequent recovery points, reducing how much work must be repeated after a failure.
The engineering lesson is broader than one framework.
A checkpoint should answer:
What is the last state we are willing to trust?Not:
What was the last token the model emitted?For a refund workflow, a checkpoint might contain:
{ "task": "refund eligible invoice", "invoiceId": "inv_2048", "eligibility": { "value": true, "source": "refund-policy-v18" }, "authorizedAmountCents": 25000, "refundOperation": { "operationId": "refund_op_811", "idempotencyKey": "invoice-inv_2048-refund-v1", "state": "unknown" }}That is recoverable state.
This is not:
"I think the refund failed, so I'll try one more time."Make attempt-local reasoning disposable
I do not need every production agent to expose or store hidden reasoning.
In fact, I prefer the orchestration layer to work with explicit artifacts:
plan stepselected toolvalidated argumentstool resultevidence recordpolicy decisionside-effect recordfailure envelopeIf the model produces a plan like:
1. Look up account2. Confirm refund policy3. Issue refundthat plan may be useful for observability.
It should not automatically become an immutable fact on the next attempt.
A retry can reconstruct a new plan from the trusted state.
That is the whole point of the clean fork.
Use supersession, not deletion, for evidence history
Clean context does not mean erasing audit history.
If a piece of evidence was wrong or stale, keep the record for debugging but mark its status:
const evidence: Evidence[] = [ { id: "ev-17", kind: "account_status", value: "ACTIVE", status: "superseded", observedAt: "2026-09-30T09:10:12Z", source: "crm-replica", }, { id: "ev-22", kind: "account_status", value: "MERGED", status: "validated", observedAt: "2026-09-30T09:11:04Z", source: "crm-primary", },];The audit trail keeps both.
The retry prompt receives only the current trusted one.
This connects naturally to memory garbage collection and evidence supersession, but the lifetime here is shorter.
Memory GC asks:
What should the agent remember across sessions and time?Retry context asks:
What may cross the boundary from one failed execution attempt into the next?Different boundary. Same need for evidence discipline.
Separate retry identity from task identity
One business task can have several execution attempts.
Do not give them the same identifier.
I like:
task_id = task_710attempt_id = attempt_710_3operation_id = refund_op_811Those IDs answer different questions.
task_id:
Which user/business objective are we trying to complete?attempt_id:
Which execution trajectory produced this result?operation_id:
Which external side effect are we reconciling?This becomes invaluable in traces.
Without separate identity, two retries can look like one long confusing conversation.
A retry budget should exist at more than one level
You need to bound at least:
tool-call retriesreasoning retriesworkflow attemptswall-clock durationcostA workflow with:
3 model retries× 3 tool retries per model attempt× 2 provider failoverscan explode into far more work than anyone intended.
AWS's Well-Architected guidance specifically warns about retries at multiple layers compounding into retry storms.
Agent systems can create the same multiplication, with an extra cost dimension.
So I want one owner for retry policy.
For example:
type RetryBudget = { maxWorkflowAttempts: number; maxToolRetriesPerAttempt: number; maxWallClockMs: number; maxAdditionalCostUsd: number;};function exhausted( budget: RetryBudget, state: { workflowAttempts: number; toolRetries: number; elapsedMs: number; retryCostUsd: number; },): boolean { return ( state.workflowAttempts >= budget.maxWorkflowAttempts || state.toolRetries >= budget.maxToolRetriesPerAttempt || state.elapsedMs >= budget.maxWallClockMs || state.retryCostUsd >= budget.maxAdditionalCostUsd );}When the budget is exhausted, the answer should not be:
one more tryIt should be a state transition:
human reviewalternate workflowdegraded read-only modeexplicit failureStop when the same failure repeats
A useful signal is:
same failure class+same tool+same normalized arguments+same evidence versiontwice in a row.
That often means the retry has no new information.
If nothing material changed, another identical attempt is not resilience.
It is repetition.
type AttemptFingerprint = { failureClass: FailureClass; toolName?: string; argumentHash?: string; evidenceVersion: string;};function shouldStopRepeatedFailure( current: AttemptFingerprint, previous?: AttemptFingerprint,): boolean { if (!previous) return false; return ( current.failureClass === previous.failureClass && current.toolName === previous.toolName && current.argumentHash === previous.argumentHash && current.evidenceVersion === previous.evidenceVersion );}A retry should have a reason to expect a different outcome:
dependency recoveredarguments changedevidence refreshedprovider changedauthorization changedhuman supplied missing inputIf none of those happened, stop pretending the next run is meaningfully different.
Retry prompts should be explicit about uncertainty
When I do send failure information back to the model, I want it normalized.
Bad:
The tool completely failed again and maybe the account is broken.Try another way.Better:
{ "failureClass": "side_effect_unknown", "confirmedFacts": [ "request left the application", "client did not receive a response before timeout" ], "notKnown": [ "whether the external refund was applied" ], "requiredNextStep": "reconcile operation status before any new write"}The shape teaches the model where certainty stops.
That is much more useful than dumping a stack trace and hoping it interprets the failure correctly.
The retry should sometimes use a different strategy
A clean fork does not mean:
erase history and repeat identicallyIt means:
restart from trusted statewith explicit knowledge of why the prior attempt failedThat failure envelope can justify a new strategy.
Examples:
retrieval stale→ query authoritative sourceprovider overloaded→ fail over to approved secondarytool arguments invalid→ regenerate arguments from schemasemantic conflict→ collect one more source or escalateside effect unknown→ reconcile before writepolicy blocked→ do not retry; request authorizationThis is where provider failover fits.
Failover changes the dependency.
A clean retry fork changes the attempt state contract.
They complement each other.
Observability should show what crossed the attempt boundary
Most tracing systems can show that a retry happened.
I also want to know:
which checkpoint it forked fromwhich evidence IDs crossed the boundarywhich evidence IDs were invalidatedwhich side effects were unresolvedwhich failure class triggered the retrywhich policy authorized the retrywhat materially changed before the next attemptUseful metrics include:
retry success rate by failure classattempts per tasksame-failure-twice rateidentical-tool-call retry rateretry context bytes / tokensinvalid evidence carried into retryunresolved side-effect replay attemptsdeduplicated writesretry-induced latencyretry-induced costescalation after retryThe metric I especially like is:
retry with no new informationIf that number is high, your system is probably burning tokens rather than recovering.
Test the retry boundary with failure injection
I would build tests specifically around ambiguous and contaminated states.
| Injected failure | Expected behavior |
|---|---|
| Read-only HTTP 503 | Retry with bounded backoff |
| Tool returns schema validation error | New attempt excludes malformed arguments |
| Retrieval source becomes stale | Old evidence marked invalid; authoritative evidence fetched |
| Write succeeds but response is dropped | Reconcile and do not duplicate write |
| Write confirmed not applied | Replay with same operation identity/idempotency key |
| Side-effect status cannot be proven | Stop autonomous write retry |
| Model invents a hypothesis before failure | Hypothesis does not become trusted retry evidence |
| Same normalized failure repeats | Retry budget stops or changes strategy |
| Policy denies an action | No autonomous retry |
| Dependency overload triggers multiple retry layers | Central policy prevents multiplicative retry storm |
| Human supplies missing fact | Clean fork includes new validated input |
| Retry budget is exhausted | Escalate/degrade instead of “one more attempt” |
The test is not:
Did the agent eventually return an answer?It is:
Did the next attempt begin from a state we can defend?Do not confuse replay with retry
This distinction matters in durable agent systems.
A replay can mean:
reconstruct deterministic workflow statefrom recorded eventsA retry means:
perform another attempt at work that did not complete acceptablyThose are not automatically the same thing.
Temporal, for example, distinguishes workflow/task execution histories and retry behaviors; separate workflow retries can have separate event histories. Durable systems make these boundaries explicit because execution history has semantics.
Agent frameworks should be equally careful.
If you replay a checkpoint and then execute a new model/tool path, you are creating a new attempt.
Give it a new attempt identity and apply the retry policy.
What I would not do
I would not wrap the entire agent in a generic retry(3) and call it resilient.
I would not interpret every timeout as “operation failed.”
I would not replay a consequential write until its effect status is reconciled.
I would not give a retry the previous model's full speculative rationale by default.
I would not keep invalidated evidence in the active context just because it is useful for the audit log.
I would not retry a policy denial as if it were a transient 503.
I would not let three different layers each retry three times without one system owning the total budget.
I would not keep trying the same tool with the same arguments against the same evidence and expect intelligence to emerge from repetition.
And I would not ask the model to decide whether idempotency matters.
That is system design.
The production rule I would keep
A production retry should answer five questions before it runs:
1. What exactly failed?2. Which facts from the previous attempt are still trusted?3. Did any external side effect possibly happen?4. What materially changes in the next attempt?5. What condition makes us stop?That produces a much safer retry loop:
classify failure→ locate trusted checkpoint→ invalidate contaminated evidence→ reconcile side effects→ build clean retry context→ change strategy if needed→ spend bounded retry budget→ stop or escalate when uncertainty remainsThe most important design decision is the attempt boundary.
The audit log can remember everything. The retry context should not.
Your tracing system should retain the failed plan, bad arguments, errors, and hypotheses so engineers can investigate them.
Your next model attempt should receive only what it needs to recover safely.
That is the difference between durable execution and durable confusion.
And it leads directly to the next problem: when a production agent fails, how do you prove whether the prompt, model, retrieval, tool, policy, or external dependency actually caused it?
That is where counterfactual replay and failure attribution become useful.
References
KEEP READING
Related engineering notes
A Failover Route Is Not a Recovery Path: Proving Independence in AI Infrastructure
Two LLM providers can share the same failure domain. Build an evidence-backed recovery graph that checks cloud, networking, identity, control-plane and capacity dependencies before admitting fallback routes, then test correlated outages without weakening safety.
Read articleAn Eval Platform Sunset Can Erase Your Release Evidence: Build an Evidence-Escrow Migration Gate
When a hosted LLM evaluation platform retires, switching runners is not enough. Preserve the historical evidence, reconstruct grader semantics, validate scoring parity, and enforce a fail-closed release gate that survives the service shutdown.
Read articleWhen the Package Runs Before Your App: Quarantining AI Framework Releases
The 2026 agent-framework PyPI compromise exposed a blind spot in AI build pipelines: Python startup hooks execute before application imports. Design an artifact-quarantine gate, inspect wheels without installing them, separate credentials, and recover from suspected exposure.
Read article