Dev.to AI πŸ€– Ai πŸ‘ 2 πŸ“– 10 min read

Idempotency for AI Agents: Safe Retries for Tool Calls

On Monday, the support agent tells a customer that their refund has gone through. On Tuesday, the finance team finds two refunds for the same order. Nobody changed the prompt. The model didn't hallucinate. The payments s

On Monday, the support agent tells a customer that their refund has gone through. On Tuesday, the finance team finds two refunds for the same order. Nobody changed the prompt. The model didn't hallucinate. The payments service did exactly what it was asked, twice.

What happened is older than language models. The first refund request reached the payments service and committed. The reply took too long and timed out. The agent saw an error, so it tried again, and the second request committed too. The agent never knew the first one had worked.

This post is about that bug: the timeout after the commit. It looks like an AI problem because an agent is involved, but it's a distributed-systems problem with an LLM on top, which is how one of the most-discussed DEV posts of the past few weeks put it. This piece adds a fault-injection run with real numbers, a rule for building the right idempotency key, and a way to classify your tools so you know which ones are safe to retry.

Three Retry Layers You Didn't Know You Had

Ask most teams where retries happen in their agent, and they'll point to one place. There are usually three, and none of them knows about the others:

  • The HTTP client or SDK retries on timeouts and some error codes, often by default.
  • The agent framework or tool wrapper retries a failed tool call, sometimes with its own policy.
  • The model itself reads a failed tool result and decides to call the tool again. This is the layer people forget. The model is a retry layer, and it can also rephrase the call when it tries again.

Each layer is reasonable on its own. Stacked, they multiply. Two attempts at each of three layers means up to eight requests for a single intent, and none of them has any idea that an earlier attempt may already have succeeded.

What a Fault-Injection Run Shows

To see how much this matters, I wrote a small simulation. An agent asks a payments service to refund an order. The service commits the refund, and then, a set percentage of the time, loses the reply, which is the timeout-after-commit case. A smaller share of requests fail before anything is written. All three retry layers get one retry each. And when the model re-issues a call, there's a 50% chance it rephrases the free-text reason field, because models do that.

I ran 20,000 refund requests per setting, against four ways of building an idempotency key: none at all, a random key generated for every attempt, a hash of all the arguments, and a key built from the business identity of the action (the order and the word "refund").

When 5% of replies are lost after the commit, 5.0% of orders were refunded twice with no key. A random key for every attempt gave the same 5.0%. Hashing all arguments gave 0.0%, and so did the business-identity key.

When 20% of replies are lost, no key and a random key each produced 20.1% duplicate refunds. The hash of all arguments produced 0.1%. The business-identity key produced 0.0%.

When 40% of replies are lost, which is a bad day for a dependency, no key and a random key each produced 40.4% duplicates. The hash of all arguments produced 1.4%. The business-identity key still produced 0.0%.

Three things stand out:

The duplicate rate tracks the lost-reply rate almost exactly. Every lost reply after a commit turns into a second write.

A random key per attempt is no protection at all. It behaves identically to having no key, because every retry looks like a new request. It's the most common false sense of safety, since the code does send an idempotency key.

Hashing every argument works until the model rephrases. Retries inside the client and framework resend the same arguments, so they dedupe. But when the model re-issues the call with a reworded reason, the hash changes and the duplicate gets through. That's the 1.4% on the bad day.

Retries themselves worked fine. In every run, no order was left without a refund. The retries did their job. They just weren't safe to run without a key.

These numbers come from a toy model with assumed rates, not from your production system. The shape is what matters. Change the rates to match your own failure data.

Build the Key From What the Action Means

The lesson from the run is simple to state and easy to get wrong: an idempotency key should identify the intent, not the attempt.

A few rules:

  • Use business identity. The order ID plus the action name tells the service "this is the refund for order 1234", however many times you ask.
  • Don't generate the key per attempt, and don't let the model write it. Generate it once in your own code, when the step is planned, and reuse it on every retry at every layer.
  • Don't hash free text. Anything the model can reword, such as a reason, a note or a message, should stay out of the key. If you hash all the arguments, you've made the key depend on the model's phrasing.
  • Include what makes two actions genuinely different. Two partial refunds of different amounts on the same order are different intents. Put the amount, or a step number, into the key so they aren't collapsed into one.
  • Scope and expire keys. Keep them per tenant or account, and keep them long enough to outlast your longest retry window.

Classify Every Tool Before You Retry It

Not every tool needs a key. A helpful way to decide is to put each tool in one of four classes:

  • Read-only: looking up an order, fetching a status. Retry freely, with backoff.
  • Idempotent write: setting a value to a specific state, such as "mark order 1234 as shipped". Repeating it changes nothing, so retries are safe.
  • Non-idempotent write: charging a card, sending a message, creating a record. Each repeat does something new. These need an idempotency key, or they shouldn't be retried at all.
  • Irreversible: deleting data, paying out money, sending an email that can't be unsent. These need a key, an audit record and usually a human approval step.

Write the class next to each tool's definition. When a tool's class changes, the retry rule changes with it. This one habit prevents most of the double-charge stories.

Server-Side Dedupe Is Half the Job

A key does nothing unless something checks it. The service that performs the action has to store the result under the key and return that stored result when the same key arrives again. Two details are easy to miss:

  • Duplicates that arrive at the same time. If the first request is still running when the retry lands, you need a lock or a unique constraint so both don't commit.
  • Providers without key support. If the tool you call doesn't accept idempotency keys, build your own ledger in front of it. Record the intent before the call, mark it done after, and on a retry check the ledger first. Where you can, read the current state before you repeat a write: "does a refund for this order already exist?" is a cheap question.

Teach the Model What an Error Means

A timeout is not a failure. It's an unknown outcome, and the model needs to be told that. If a tool simply returns "error", the model will do the natural thing and try again.

Return a structured result instead. Say whether the outcome is known or unknown, whether the call is safe to repeat, and what to do next. For an unknown outcome on a non-idempotent tool, the instruction should be to check the status with a read tool and not to repeat the write. This is a design choice in your tools, not in the prompt, and it removes the third retry layer for the calls that matter most.

Set One Retry Policy, Not Three

The cleanest fix for stacked retries is to decide which layer owns retrying and turn the others down:

  • Know your defaults. Find out what your SDK and framework retry by default, and decide whether to keep it.
  • Use backoff with jitter, and give each intent a retry budget so a struggling dependency isn't hammered.
  • Cap total attempts across layers, not per layer.
  • Don't retry non-idempotent calls without a key, whatever layer is asking.
  • Send the hopeless cases somewhere visible. When retries run out on an irreversible action, route it to a dead-letter queue or a human, not another loop.

When the Agent Should Stop and Ask

Some actions deserve a pause even with a good key. If the action is irreversible and the outcome is unknown, such as a payout that timed out, the right behaviour is to stop and escalate with the context a person needs: what was attempted, the key, and what the status check returned. A human approval step for irreversible actions costs a little speed and prevents the bug nobody can undo.

What to Log So You Can See It

You can't fix a retry bug you can't see. For every tool call, record the attempt number, the idempotency key, the tool name, the business object it touched and whether the outcome was known or unknown. Then the signature of this bug is easy to spot: two calls with different keys for the same order. Another DEV post, a production tracing checklist for agent retries, makes the same point and goes deeper on spans and attributes.

Idempotency Checklist

  • You know every place your agent can retry: client, framework and model
  • Each tool is classified as read-only, idempotent write, non-idempotent write or irreversible
  • Non-idempotent and irreversible tools take an idempotency key, or are never retried
  • Keys are built from business identity and generated once in your code, not per attempt
  • Keys never include text the model can reword
  • Actions that are genuinely different, such as partial amounts, produce different keys
  • The service stores results by key, handles concurrent duplicates and expires keys sensibly
  • Where a provider lacks key support, you keep your own intent ledger and read state before writing
  • Tool errors say whether the outcome is known, whether it's safe to repeat and what to do next
  • One layer owns retries, with backoff, jitter, a retry budget and a cap across layers
  • Irreversible actions with an unknown outcome go to a human or a dead-letter queue
  • Logs show attempt number, key and outcome, and you alert on two keys for one business object
  • You've run a fault-injection test that loses the reply after the write commits

Quick FAQ

Isn't this a prompt problem I can fix with better instructions? Instructions help the model behave, but they can't undo a duplicate write that already happened. The fix belongs in the tool and the service, where keys and dedupe are enforced regardless of what the model decides.

Why not just turn retries off? Retries are useful. In the simulation, no order went without a refund even with 40% of replies lost. Turning them off would trade duplicate writes for missed ones. Keep retries and make them safe.

Can the model generate the idempotency key? It shouldn't. The model can reword or lose context between attempts. Generate the key in your own code from the business identity, and pass it to the tool.

What if the tool provider has no idempotency support? Build a ledger in front of it: record the intent, check for an existing result before repeating, and read the current state before any write you can't safely repeat.

How long should a key live? At least as long as your longest retry window, including any queue delays. Longer is safer for money-moving actions.

Final Thoughts

The reframe worth keeping is that an agent inherits every failure mode of the network it sits on, plus a new one: the model that decides to try again. The answer is classic engineering, which means classifying side effects, keying by intent, deduplicating on the server and making errors say what they mean. None of it is exotic, and all of it is easy to skip when the demo works.

If you'd like help making an agent safe to run against real systems, Kilowott's Kilowott Intelligence team reviews how AI tools are connected and governed, including what they can change and how safely. You can also browse their case studies or get in touch.

What's the worst duplicate action an agent has taken in your system? Tell us in the comments.

Source and further reading: Your agent's retry bug isn't an AI problem. It's a distributed-systems problem with an LLM on top by Dimitris Kyrkos, and What to Log When Your AI Agent Retries: A Production Tracing Checklist. The simulation results above come from a toy model with assumed failure rates, not from a production system.

πŸ“° Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.