Skip to main content
Back to all articles
AI Engineering 12 min readUpdated October 28, 2026

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.

By Salman Butt · Senior Full-Stack & Generative AI Engineer
#AI Agents#Retries#Reliability Engineering#Context Engineering#Checkpointing#Idempotency#AgentOps#LangGraph#TypeScript#Python#Production AI
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:

Text
TimeoutError: request exceeded 8s

Then 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:

Text
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:

TypeScript
await retry(() => agent.invoke(state));

That looks clean.

It also hides the most important question:

Text
What exactly are we retrying?

These are different operations:

Retry typeExampleTypical risk
Transport retryHTTP request failed before a response arrivedDuplicate request / retry storm
Read-only tool retrySearch API returned 503Extra latency and load
Side-effect retryCreate refund, send email, delete resourceDuplicate or conflicting effects
Reasoning retryModel chose a bad planRepeating the same cognitive path
Retrieval retryEvidence was stale or incompleteCarrying stale evidence into new attempt
Workflow retryWhole agent run restartsRepeating 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:

Text
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:

Text
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:

Text
1. immutable task intent2. validated external observations3. model-generated hypotheses4. invalid or ambiguous attempt-local state

Only 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:

Text
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:

Text
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:

Text
account_status = ACTIVE

Then 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:

JSON
{ "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.

Clean retry fork for production AI agents

The clean fork starts from:

Text
immutable task intent+ validated checkpoint+ still-valid evidence+ side-effect ledger+ typed failure envelope

It does not automatically include:

Text
the previous chain of reasoningspeculative conclusionsinvalid tool outputssuperseded evidenceunverified assumptionsraw error noise

This 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.

TypeScript
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:

Text
facts≠attempt-local reasoning

and:

Text
client error≠business-effect status

Once 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:

TypeScript
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:

TypeScript
previousAssistantMessagespreviousScratchpadpreviousPlanTextrawConversationDump

If 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:

Python
from dataclasses import dataclassfrom typing import Any, Literal​​EvidenceStatus = 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: bool​​def 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:

Text
POST /refunds→ request accepted by server→ refund created→ response lost→ client timeout

From the caller's perspective:

Text
unknown

The wrong recovery strategy is:

Text
LLM: "It probably failed. Try again."

The right recovery strategy is:

Text
reconcile

Ask 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.

Side-effect reconciliation before an agent retry

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:

TypeScript
try {  await issueRefund(input);} catch (error) {  return { status: "failed" };}

A timeout may not mean failed.

A more useful result is:

TypeScript
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.

TypeScript
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 classRetry?Context policy
HTTP 503 on read-only searchUsually yes, bounded + backoffKeep trusted state
Rate limitUsually yes after server/backoff delayKeep trusted state
Schema validation failureMaybe one repaired attemptDrop malformed arguments
Stale evidenceRe-retrieve before retryInvalidate old evidence
Policy blockNo autonomous retryEscalate/change authorization
Ambiguous side effectNot until reconciledPreserve operation identity
Semantic contradictionMaybe, from clean checkpointExclude unsupported hypothesis
Repeated same failureUsually stopEscalate or choose alternate path

Notice that “retryable” is not only a property of the exception.

It is a property of:

Text
failure class× operation semantics× side-effect state× attempt history× risk tier

Backoff 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:

Text
wait 1swait 2swait 4s

does 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:

Text
distributed-system retry safety+agent-state retry safety

The first includes:

Text
timeoutsbounded attemptsbackoffjitteridempotencycircuit breakers

The second includes:

Text
checkpointsstate validationevidence invalidationclean context forksfailure envelopesside-effect reconciliation

You 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:

Text
What is the last state we are willing to trust?

Not:

Text
What was the last token the model emitted?

For a refund workflow, a checkpoint might contain:

JSON
{  "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:

Text
"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:

Text
plan stepselected toolvalidated argumentstool resultevidence recordpolicy decisionside-effect recordfailure envelope

If the model produces a plan like:

Text
1. Look up account2. Confirm refund policy3. Issue refund

that 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:

TypeScript
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:

Text
What should the agent remember across sessions and time?

Retry context asks:

Text
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:

Text
task_id     = task_710attempt_id  = attempt_710_3operation_id = refund_op_811

Those IDs answer different questions.

task_id:

Text
Which user/business objective are we trying to complete?

attempt_id:

Text
Which execution trajectory produced this result?

operation_id:

Text
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:

Text
tool-call retriesreasoning retriesworkflow attemptswall-clock durationcost

A workflow with:

Text
3 model retries× 3 tool retries per model attempt× 2 provider failovers

can 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:

TypeScript
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:

Text
one more try

It should be a state transition:

Text
human reviewalternate workflowdegraded read-only modeexplicit failure

Stop when the same failure repeats

A useful signal is:

Text
same failure class+same tool+same normalized arguments+same evidence version

twice 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.

TypeScript
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:

Text
dependency recoveredarguments changedevidence refreshedprovider changedauthorization changedhuman supplied missing input

If 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:

Text
The tool completely failed again and maybe the account is broken.Try another way.

Better:

JSON
{  "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:

Text
erase history and repeat identically

It means:

Text
restart from trusted statewith explicit knowledge of why the prior attempt failed

That failure envelope can justify a new strategy.

Examples:

Text
retrieval stale→ query authoritative source​provider overloaded→ fail over to approved secondary​tool arguments invalid→ regenerate arguments from schema​semantic conflict→ collect one more source or escalate​side effect unknown→ reconcile before write​policy blocked→ do not retry; request authorization

This 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:

Text
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 attempt

Useful metrics include:

Text
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 retry

The metric I especially like is:

Text
retry with no new information

If 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 failureExpected behavior
Read-only HTTP 503Retry with bounded backoff
Tool returns schema validation errorNew attempt excludes malformed arguments
Retrieval source becomes staleOld evidence marked invalid; authoritative evidence fetched
Write succeeds but response is droppedReconcile and do not duplicate write
Write confirmed not appliedReplay with same operation identity/idempotency key
Side-effect status cannot be provenStop autonomous write retry
Model invents a hypothesis before failureHypothesis does not become trusted retry evidence
Same normalized failure repeatsRetry budget stops or changes strategy
Policy denies an actionNo autonomous retry
Dependency overload triggers multiple retry layersCentral policy prevents multiplicative retry storm
Human supplies missing factClean fork includes new validated input
Retry budget is exhaustedEscalate/degrade instead of “one more attempt”

The test is not:

Text
Did the agent eventually return an answer?

It is:

Text
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:

Text
reconstruct deterministic workflow statefrom recorded events

A retry means:

Text
perform another attempt at work that did not complete acceptably

Those 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:

Text
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:

Text
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 remains

The 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