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.
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:
Timeouts after success. The action happened; the response was lost.
Worker crashes mid-run. A job restarts from the last checkpoint and
replays the step.
At-least-once queues. Many queues deliver a message more than once by
design.
Layered retries. An SDK retries, your wrapper retries, and the
orchestrator retries the whole step.
Re-asked calls. If a result never reaches the model, it may request the
same action again in its next turn.
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 type
Example
Run twice means
Retry safety
Read
Look up an order
Nothing
Safe
Idempotent write
Set ticket status to "closed"
Same end state
Safe
Non-idempotent write
Create a ticket, send an email
Duplicate
Unsafe without a key
Irreversible / money
Refund, payout, delete
Real-world harm
Unsafe; 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.
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:
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:
Compute the key.
Look it up in a table (your database is fine; a Redis entry with a TTL
longer than your longest retry window also works).
If a completed result exists, return it without calling the tool.
If an attempt is in flight, wait or return "in progress" instead of
starting a second one.
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?
Retry only classified errors. Network failures, 429 and 5xx are
candidates. Validation errors and 4xx rejections are not; retrying them
burns money on LLM turns that will fail the same way.
Use exponential backoff with jitter so many runs do not retry in
lockstep after an outage.
Cap total attempts per step and per run, and fail loudly into a review
queue when the cap is hit. Our post on
human-in-the-loop approval
covers that handoff.
Retry the tool, not the model turn, whenever the failure was in the
tool. Re-running the model call costs tokens and may produce a different
action.
Set timeouts shorter than the caller's patience and treat a timeout as
"unknown outcome", never as "failed". That distinction is exactly why
idempotency is needed.
Consider parallel_tool_calls carefully. OpenAI documents setting it to
false to allow at most one call per turn. For ordered or dependent side
effects, that removes a class of races.
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
List every tool your agent can call and tag each read, idempotent write,
non-idempotent write or irreversible.
For the last two groups, route calls through one wrapper that derives keys
from run and step IDs.
Use the downstream provider's idempotency support where it exists.
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
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.
AI automation vs RPA vs Zapier-style workflow tools is a question about inputs, not hype. How to match each to the process, where they combine, and the mistakes that make automation brittle.
MCP vs function calling is not either/or: function calling is how a model asks for a tool, MCP is how tools are packaged and served. When each fits, and what each means for security and maintenance.
Human-in-the-loop AI agents need approval gates only where actions are costly or irreversible. How to decide which actions to gate, which review pattern fits, and how to avoid approval fatigue.