AI Agents Need Idempotency Keys: Retries Are the Real Failure Mode
TL;DR — Most agent failures that hurt are not hallucinations. They are duplicated side effects from retries, timeouts and replayed loops. Distributed systems solved this decades ago with idempotency keys and durable exec
TL;DR — Most agent failures that hurt are not hallucinations. They are duplicated side effects from retries, timeouts and replayed loops. Distributed systems solved this decades ago with idempotency keys and durable execution, and agent frameworks are relearning it the hard way.
The agent charged the customer twice. The model was not confused. It did exactly what it was asked, twice, because the first call timed out and the loop did what loops do.
This is the failure mode I think the agent conversation underweights. We argue about reasoning quality and prompt design. Meanwhile the incidents that cost money come from a much older place: at-least-once execution of non-idempotent side effects.
An agent loop is a retry machine
Look at the structure of a typical tool-calling agent. The model emits a tool call. A runtime executes it. The result goes back into context. If anything in that chain is ambiguous, something retries.
- The HTTP client times out and its retry middleware fires again.
- The orchestrator crashes after the tool ran but before the result was persisted, then replays the step on restart.
- The model sees an error or an empty result and decides, reasonably, to call the tool again.
- A human clicks regenerate on a run that had already done real work.
Each of these is a normal, defensible behavior. Together they mean any tool with a side effect will eventually be invoked more than once for a single intended action. That is not a bug in a given framework. It is the shape of the problem.
The network gives you the same lesson it always has. When a request times out, you do not know whether it executed. The only safe responses are to make the operation safe to repeat, or to accept the risk of a duplicate or a miss.
We already know the answer
HTTP semantics have separated safe and idempotent methods for a long time. A PUT or DELETE repeated yields the same server state as one call. A POST carries no such promise. Payment APIs worked around this with client-supplied idempotency keys: the caller generates a unique token per logical operation, the server stores the outcome keyed by that token, and a repeat returns the stored result instead of acting again. There is also an ongoing IETF effort to standardize an Idempotency-Key header for exactly this purpose.
The mechanism is simple enough to describe in four lines:
- The caller mints a key for the intent, not for the attempt.
- The server records key, request fingerprint and result atomically with the side effect.
- A repeat with the same key and same payload returns the recorded result.
- A repeat with the same key and a different payload is rejected loudly.
Step one is where agents go wrong. The key has to be tied to the intended action, and the intended action is a decision the model made at a specific point in a specific run. If the runtime mints a fresh key on every attempt, you have idempotency in name only.
Where the key should come from
My opinion: the agent runtime, not the model, owns idempotency keys. Never ask an LLM to invent a unique token and hope it stays stable across a replay. Models are not reliable generators of stable identifiers, and a regenerated step will produce a different one.
Derive the key deterministically instead. A workable recipe is a hash of run ID, step index and a canonical serialization of the tool name and arguments. On a replay of the same step with the same arguments, you get the same key. If the model changes its mind and sends different arguments, you get a different key, which is correct, because it is a different intent.
Then pass that key all the way down to the system that performs the effect. A key checked only in your agent layer protects you from your own retries but not from the downstream service's. The enforcement point has to be as close to the side effect as possible, ideally in the same transaction as the write.
Tool descriptions should declare their retry contract
Tool protocols are starting to acknowledge this. The Model Context Protocol lets servers attach annotations to tools, including hints about whether a tool is read-only, destructive or idempotent. Those hints are advisory, and the spec is explicit that clients should not trust them from an untrusted server. But the direction is right. A tool schema that says nothing about retry safety forces the runtime to assume the worst.
I would go further than hints. Treat the retry contract as a first-class part of every tool definition:
- Pure reads: retry freely, cache aggressively.
- Idempotent writes: retry with a stable key.
- Non-idempotent writes: never auto-retry. On ambiguity, query the downstream state to learn whether the action happened, or escalate to a human.
That third class is the one teams avoid designing for. But "send the email", "issue the refund" and "provision the cluster" live there. If your only defense is a polite instruction in the system prompt saying do not do this twice, you do not have a defense.
Durable execution is the other half
Keys handle duplicate calls. They do not handle a runtime that dies mid-run and forgets what it already did. This is the problem durable execution engines exist for: persist each step's input and result in an event history, and on recovery replay the history instead of re-executing completed steps. Workflow systems in this category are explicit that side-effecting activities must still be written to tolerate being run more than once, because the crash can land between the effect and the record of the effect.
That sentence should be tattooed on every agent framework README. Exactly-once is something you build from at-least-once delivery plus idempotent handling. Streaming systems say the same thing. Kafka's transactional guarantees apply to reads and writes within Kafka. The moment your consumer calls an external API, you are back to making that call safe to repeat.
For agents, the practical pattern is:
- Persist the model's tool call before executing it.
- Execute with the derived idempotency key.
- Persist the result keyed the same way.
- On recovery, read the log first and execute only what is missing.
This also gives you something agent debugging badly needs: a faithful, replayable record of what the agent actually did, separate from what it said it did.
The uncomfortable part
None of this is novel, and that is the point. The agent ecosystem has spent two years on the novel parts and is now rediscovering the old ones at production prices. The model reasoning better will not remove the need. A perfect reasoner behind a flaky network still sends a request it cannot confirm landed.
If you are building or buying an agent platform, ask four questions before you ask about model quality:
- Which of your tools are safe to retry, and where is that declared?
- Who generates idempotency keys, and are they stable across replays?
- Where is the key enforced: in the agent, or at the side effect?
- After a crash mid-step, what does the system believe happened?
If the answers are vague, the first expensive incident is already scheduled. It will not look like an AI failure. It will look like a duplicate row, a double charge or a second deployment, and the postmortem will say "retry". It will be right.
Sources
RFC 9110: HTTP Semantics: HTTP defines safe and idempotent methods; PUT and DELETE are idempotent while POST carries no such guarantee. — https://www.rfc-editor.org/rfc/rfc9110
Stripe API Reference: Idempotent requests: Client-supplied idempotency keys let a server return the stored result of a repeated request instead of acting again. — https://docs.stripe.com/api/idempotent_requests
The Idempotency-Key HTTP Header Field (IETF draft-ietf-httpapi-idempotency-key-header): An IETF effort exists to standardize an Idempotency-Key header for making non-idempotent requests safely retryable. — https://datatracker.ietf.org/doc/draft-ietf-httpapi-idempotency-key-header/
Model Context Protocol: MCP lets servers annotate tools with hints such as read-only, destructive and idempotent, which clients should treat as advisory. — https://modelcontextprotocol.io
Temporal Documentation: Durable execution replays recorded event history, and side-effecting activities must still tolerate being executed more than once. — https://docs.temporal.io
Apache Kafka Documentation: Kafka's exactly-once guarantees cover read-process-write within Kafka; external side effects need their own idempotent handling. — https://kafka.apache.org/documentation/
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.