All posts

AI agent retries and idempotency: how to stop duplicate tool calls

AI agent retries can send the same email twice or create two tickets. How idempotency keys, call IDs and tool design make agent tool calls safe to retry.

CodeKrypt 6 min read

Your agent sends a customer a refund confirmation, the HTTP call times out, your retry wrapper fires, and the customer gets two emails. Or worse, two refunds. AI agent retries and idempotency are the unglamorous part of agent engineering that decides whether you can leave an agent running unattended, because agents retry far more than ordinary request handlers do.

This post is about the domain, not any particular deployment of ours. Sources are public docs, linked inline.

Why do AI agents create duplicate tool calls?

The model never executes anything. In OpenAI's function-calling flow, the model returns a request for a tool call and your application executes it, then sends back a result tied to that call's call_id. The same guide notes the model may request several calls in a single turn. That puts your code in charge of everything between "the model asked" and "the result came back", and that gap is where duplicates come from:

None of these needs the model to be wrong. They are the same failure modes as any distributed system, multiplied by long multi-step runs. Our post on why AI agents fail in production covers the wider picture; this is one concrete fix.

Which tool calls are safe to retry?

Sort every tool by what happens if it runs twice.

Tool typeExampleRun twice meansRetry safety
ReadLook up an orderNothingSafe
Idempotent writeSet ticket status to "closed"Same end stateSafe
Non-idempotent writeCreate a ticket, send an emailDuplicateUnsafe without a key
Irreversible / moneyRefund, payout, deleteReal-world harmUnsafe; key plus approval

"Set status to closed" is idempotent because the target state is in the request. "Add a note" is not. Where you can, design tools as set to this state rather than do this action.

Retry with an idempotency key: the second attempt returns the stored result instead of repeating the actionAgent runtimeTool wrapperExternal systemattempt 1 (key K)executes oncetimeout, retry (key K)Same key: stored result returned, no second action

How do idempotency keys work?

The pattern is well documented by payments APIs. With Stripe's idempotent requests, the client generates a unique key and sends it with the request. For API v1, Stripe saves the status code and body of the first request made with that key, and retries with the same key return the saved response. Keys can be up to 255 characters, V4 UUIDs or similarly random strings are suggested, and keys may be pruned after they are at least 24 hours old. If you reuse a key with different parameters, the request errors instead of silently doing something else. Per Stripe's docs, GET and DELETE requests are idempotent by definition and keys have no effect there.

Not every system you integrate with offers this. For those that do not, you build the equivalent yourself, in the tool wrapper.

Where should the idempotency key come from?

Not from the model. If the model invents a key, a re-asked call gets a fresh key and defeats the purpose. Derive it in your own code from stable identifiers:

key = hash(run_id + step_id + tool_name + normalized_arguments)

The call_id from the provider is useful for matching results to requests, but it identifies one model response; if you regenerate the response after a failure it changes. Anchor the key to your run and step identifiers, which survive restarts.

What does a safe tool wrapper look like?

Put the logic in one wrapper that every side-effecting tool goes through, rather than in each tool:

  1. Compute the key.
  2. Look it up in a table (your database is fine; a Redis entry with a TTL longer than your longest retry window also works).
  3. If a completed result exists, return it without calling the tool.
  4. If an attempt is in flight, wait or return "in progress" instead of starting a second one.
  5. Otherwise record "started", call the tool passing the key downstream where the API supports it, then record the result.

Step 4 is the one teams skip. Two workers picking up the same step at the same time will both pass a naive "not seen yet" check unless the insert is atomic, for example a unique constraint on the key.

Also decide what you store on failure. Stripe's v1 behaviour is to return the saved response even for 500 errors, which is predictable but means a transient failure sticks. Pick deliberately which errors are final and which should allow a fresh attempt.

Retries, timeouts and backoff: what else to configure?

How do you test retry safety?

Add cases to your agent evaluation set that inject faults: drop the response after the tool succeeds, kill the worker between "started" and "completed", deliver the same message twice. The assertion is simple: the external system shows exactly one effect. These tests are deterministic, so they can run in CI without model calls if you stub the model's tool requests.

Also log the key, attempt number and whether a stored result was returned, so that observability can show you retries that are quietly happening in production.

What to do next

  1. List every tool your agent can call and tag each read, idempotent write, non-idempotent write or irreversible.
  2. For the last two groups, route calls through one wrapper that derives keys from run and step IDs.
  3. Use the downstream provider's idempotency support where it exists.
  4. Add fault-injection cases to your test suite before widening the agent's permissions.

If you are planning an agent that touches billing, tickets or customer messaging, this is the kind of reliability design our AI automation service covers.

CodeKrypt avatar

CodeKrypt

Drafted by CodeKrypt's AI writing pipeline, built and maintained by our engineers, under fixed rules on sources and claims. How we write

Frequently asked questions

Why do AI agents make duplicate tool calls?
Usually for ordinary distributed-systems reasons: a network timeout after the action succeeded, a worker restart mid-run, a queue delivering a message twice, or your own retry logic. The model can also request the same action again if it never saw a result. None of these require the model to misbehave.
What is an idempotency key in an AI agent?
A unique identifier your code attaches to a side-effecting request so the receiving system can recognise a retry and return the original result instead of repeating the action. Stripe's API is the best-known public example.
Should I let the model generate idempotency keys?
Generally no. Derive the key in your own code from stable identifiers such as the run ID and step ID, so a retry of the same step always produces the same key.
Do read-only tools need idempotency keys?
No. Reads are safe to repeat. Focus on tools that send, create, charge, update or delete.

Related reading

Chat on WhatsApp