Agent orchestration

Retries and Idempotency for Reliable AI Agents

Reliable agents must know when repeating an action helps and when it creates a second problem. Design retries around durable intent, explicit uncertainty, and the receiver’s side-effect contract.

AI-assisted technical guide with linked primary sources. Examples are illustrative unless stated otherwise. How these guides are made.

A lost response is an unknown outcome

Suppose an agent submits a release request. The server starts the release, but the response disappears. The agent sees a timeout and submits the request again. Two releases may now exist even though the model intended only one. A network error describes what the caller observed; it does not establish what the receiver committed.

Start a retry policy by classifying the operation. Reading a release’s status is different from creating a release. Setting a configuration to a specified value is different from incrementing a counter. RFC 9110’s idempotent-method definition concerns repeated intended effects, not identical response bodies or the absence of every incidental log entry. An API’s documented semantics matter more than a tool name such as “safe deploy.”

For an agent, preserve three outcomes: confirmed success, confirmed rejection, and unresolved. Making unresolved a first-class state prevents a timeout from silently becoming permission to repeat a consequential action.

Classify errors before choosing another attempt

A suggested operation-level failure policy
ObservationNext actionReason
Invalid argumentsReturn a structured correction requestRepeating unchanged input cannot repair the contract
Missing authorizationPause for the appropriate access decisionRetries must not bypass a permission boundary
Documented transient failureRetry within the operation budgetRecovery may occur without changing intent
Timeout after a writeReconcile by operation identityThe side effect may already exist
Conflicting request parametersStop and inspect intentA reused identity must not mean a different action

This table is a design starting point, not a universal mapping from HTTP status codes. Consult the specific service contract. A server error might be retryable for a read but ambiguous for a write. A rate-limit response needs the provider’s waiting rules as well as a safe operation contract.

Give each logical action a durable identity

Separate the task ID, operation ID, and attempt ID. One task can create several intended effects; one operation can require several network attempts. Generate the operation ID before the first submission and persist it outside the conversation. Every repeat of that same intent reuses the operation ID while receiving a new attempt ID for diagnostics.

Amazon’s idempotent API design explains caller-provided request identifiers and checking repeated identifiers against their original parameters. For an agent tool, extend that idea into a contract containing principal, operation type, target, normalized arguments, and an intent fingerprint. Scope deduplication to the authenticated caller; knowing someone else’s identifier must not grant access to their result.

Do not derive identity solely from identical arguments. A developer may intentionally request two independent test environments with the same configuration. Conversely, do not generate a fresh operation ID merely because a transport attempt failed. Identity expresses intent, rather than similarity or impatience.

Worked design: create one release despite a lost reply

Consider a hypothetical release service with durable idempotency support. The following record is an illustrative tool contract, not a command for a particular deployment platform:

{
  "task_id": "upgrade-search-client",
  "operation_id": "op-7f42",
  "operation": "create_release",
  "target": "staging/search",
  "arguments": {"commit": "approved-revision"},
  "approval_id": "approval-for-this-intent",
  "state": "prepared"
}

The tool gateway stores the prepared operation and its approved argument fingerprint. It sends op-7f42 to the release service. If the reply is lost, it records an unresolved attempt rather than asking the model to invent a replacement request.

Recovery first queries the service by that identity. A confirmed release becomes the existing result. If the service permits safely repeating the same operation, resubmit the same identity and arguments. If the service cannot establish the outcome, pause for reconciliation. Changing the commit requires a new intent and a fresh approval; it must not reuse the earlier operation identity.

A local ledger alone cannot prevent duplication at an external system. The receiver needs an appropriate deduplication contract, or the workflow needs another authoritative way to determine whether the effect occurred. An in-memory “already sent” flag disappears precisely when crash recovery matters.

Bound attempts, elapsed time, and aggregate retry load

Assign a deadline to the logical operation and shorter timeouts to individual attempts. Before sleeping or submitting again, check whether enough budget remains for a useful attempt and its reconciliation. A maximum attempt count without a deadline can still leave a task waiting far beyond its useful lifetime.

Amazon’s timeout and backoff guidance describes bounded retries, exponential backoff, jitter, and the overload caused by repeated calls. Apply these controls in the tool layer rather than relying on the model to remember a delay schedule.

For illustration, a gateway might allow three total submissions, with randomized delays below a capped exponential window. Those numbers are hypothetical configuration, not recommended production defaults. Choose real values using the dependency’s latency, limits, and recovery behavior. Inspect SDK retries too: a gateway, SDK, and agent loop can each multiply attempts unless one layer owns the policy.

Read the actual provider’s deduplication rules

Idempotency is a service contract with limits. Check retention time, concurrent-request behavior, argument matching, result replay, and which endpoints participate. A successful replay after five minutes does not establish safety after the provider has forgotten the key.

For a concrete documented example, Stripe’s idempotent-request reference distinguishes API v1 result replay from API v2 recovery semantics. It also describes parameter matching and key retention behavior for v1. This is why a generic tool wrapper should not promise that every provider treats failures or expired keys identically.

Record the contract version relevant to the integration. Keep operation identities free of personal data and secrets, and protect stored arguments according to their sensitivity. A useful audit trail can retain fingerprints and authorized resource references without dumping every request body into model context.

Handle crashes, late replies, and human decisions

Test the awkward boundaries: crash before submission, crash after submission, response received before the local ledger is updated, duplicate workers, and a late reply after cancellation. For internal database changes, atomically binding the operation record to the mutation can close a local crash window. For an external call, the database transaction cannot simply include another service’s commit; reconciliation remains necessary.

Cancellation also needs a defined meaning. Stopping further attempts does not undo an already accepted release. If compensation is appropriate, record it as a separate operation with its own authorization and verification. Never label a cancelled caller as proof that the remote effect vanished.

Escalate with evidence: intended target, operation identity, attempts, last confirmed state, uncertainty, and available recovery choices. “Something failed, retry?” is too vague for a meaningful approval. The next person needs to know whether they are authorizing a repeat, a changed action, or a reconciliation check.

Keep local agent attention separate from retry enforcement

When a local coding agent pauses to ask how to handle an uncertain tool outcome, finding that session promptly is useful. Purrvio’s Mac preview shows supported local sessions, with the richest support for Claude Code and Codex, and helps you return to the relevant terminal.

Purrvio does not implement a durable operation ledger, enforce retry budgets, or guarantee idempotency. Those controls belong in the service and tool design. If session visibility fits your workflow, try the free Mac preview. It runs on macOS 13 or later on Apple silicon and Intel. The locally signed preview is not Apple-notarized; read the installation notes before first launch.

A checklist before enabling automatic retries

  • Document which operations are reads, mutations, or ambiguous after transport failure.
  • Persist logical operation identity before the first consequential submission.
  • Reject changed arguments under an existing identity.
  • Confirm receiver-side deduplication or an authoritative reconciliation path.
  • Set attempt limits, deadlines, backoff, and a single retry-policy owner.
  • Exercise crash windows, concurrent duplicates, late results, and expired identities.
  • Keep unresolved outcomes visible and route consequential decisions with concrete evidence.

Measure recovery quality, not just the percentage of attempts eventually returning success. Duplicate effects, unresolved operations, exhausted budgets, and time awaiting decisions reveal whether the workflow is becoming more reliable or merely more persistent.

Frequently asked questions

Is retrying a tool call the same as asking the model again?

No. A tool retry repeats a defined operation under a controlled contract. Asking the model again can produce changed arguments or a new action. Persist the original intent and enforce retry rules outside conversational memory.

Does an idempotency key guarantee exactly-once execution?

No universal guarantee follows from a key alone. The receiver must implement the documented contract, including concurrency and retention rules. A local identifier without receiver-side handling does not prevent duplicate external effects.

What should an agent do after a write times out?

Treat the outcome as unresolved until authoritative evidence establishes it. Reconcile using the operation identity or repeat only under an appropriate idempotent contract. Escalate when the effect cannot be determined safely.

Sources and further reading

Primary references checked for this guide on 10 November 2026. Documentation can change; confirm version-specific behavior before using commands in a production workflow.

  1. RFC 9110: HTTP Semantics, idempotent methods

    Defines intended-effect idempotency and the constraints on automatically repeating non-idempotent requests.

  2. Making retries safe with idempotent APIs — Amazon Builders’ Library

    Supports caller-provided request identities, argument matching, atomic local handling, and retention considerations.

  3. Timeouts, retries, and backoff with jitter — Amazon Builders’ Library

    Explains timeout budgets, bounded retries, backoff, jitter, and amplification across retrying layers.

  4. Idempotent requests — Stripe API reference

    Provides a concrete provider contract, including differences between API v1 and v2, parameter matching, and v1 retention behavior.

Download Purrvio.

Free Mac preview. No account or API keys.

This locally signed preview isn’t Apple-notarized. macOS may block the first launch.

Download free preview ↗

3.2 MB ZIP · Apple silicon and Intel · macOS 13.0+

Read installation steps

One email before you go.

I’ll send a short setup note and reply if you hit a snag. No spam, unsubscribe anytime.