# How to Prevent Duplicate Tool Calls in AI Agents After a Timeout

> Source: <https://startupfortune.com/how-to-prevent-duplicate-tool-calls-in-ai-agents-after-a-timeout/>
> Published: 2026-11-27 23:49:40+00:00

**Recommendation:** Treat tool timeouts as unknown outcomes: commit an idempotency-keyed ledger row before the network call, store the provider's reference, and escalate to a human when no key or status lookup exists.
More in the playbook "Designing agent systems": <https://wpnews.pro/playbooks/agent-architecture>

*Your agent can email a customer twice, or pay them twice, while each step in its reasoning looks sensible. You want a guard in your own code before a real customer finds out for you.*

- A timeout means the outcome is unknown, so your code shouldn't treat it as a failure.
- Build each idempotency key from the business event that authorised the action, and keep model-written text and tool call IDs out of it.
- Commit a ledger row before the network call, then store the provider's reference and response against it.
- Provider deduplication expires, which means your own record has to outlast it.
- When a tool offers neither an idempotency key nor a reliable status lookup, send an unclear result to a person.

Refund £50 and email the customer. That was the job a developer posting as zennicalles gave a test support agent, with one trap built in: the refund tool did its work and then threw a timeout. Running Claude Haiku 5.5 on the OpenAI Agents SDK for JavaScript, the agent issued the refund twice in six runs out of six, according to a [bug report filed on November 5](https://github.com/openai/openai-agents-js/issues/2184). If you're working out how to prevent duplicate tool calls in AI agents, start with the gap between what happened and what the agent was told.

The SDK's default message read "An error occurred while running the tool. Please try again." The model did as it was asked. When the same test passed back the real error, saying the refund request had timed out after 30,000ms, the agent looked up the charge first and never paid twice. A [fix merged on November 9](https://github.com/openai/openai-agents-js/pull/2282) removed the retry advice, and a maintainer confirmed it shipped in version 0.22.0.

Upgrade, but don't treat better wording as a guard. It was a small test, and the same developer saw no duplicates in four runs on Claude Sonnet 5.5, even with the old message.

A tool call has three possible outcomes. It worked, it didn't, or you don't know. Plenty of agent code only has room for the first two, so a dropped connection gets filed as a failure and something tries again.

[How to set an AI agent tool call timeout before one slow API stalls a run](https://startupfortune.com/how-to-set-an-ai-agent-tool-call-timeout-before-one-slow-api-stalls-a-run/)

An ai agent tool call timeout set from each tool's p95 latency, plus a deadline for the whole run, stops a stalled API from holding a worker open. The guide covers httpx and SDK defaults, retry multiplication and the structured error to hand back. - [how to set AI agent tool timeouts](https://startupfortune.com/how-to-set-an-ai-agent-tool-call-timeout-before-one-slow-api-stalls-a-run/) - [prevent slow API from stalling AI agents](https://startupfortune.com/how-to-set-an-ai-agent-tool-call-timeout-before-one-slow-api-stalls-a-run/)

That something could sit almost anywhere in your stack. Your HTTP client retries. A task queue redelivers the job, or a workflow engine reruns the step. The model reads an error and calls the tool again, and an impatient user presses the button twice. A May issue on [Stripe's AI repository](https://github.com/stripe/ai/issues/402) described the awkward version: the payment SDK protects network retries inside one session, but a retry at agent level can start a new session with a new key, so a second charge goes through.

Resuming a paused job causes it too. LangGraph's [interrupt documentation](https://docs.langchain.com/oss/python/langgraph/interrupts) says the runtime restarts the entire node from the beginning, so any code before the interrupt runs again. Put a send_email call above a human approval step and you've scheduled your own duplicate. Move the write below the interrupt, or make it safe to repeat.

## Build the AI agent idempotency key from the intended action

An idempotency key is a label that travels with a request so the receiver can recognise a repeat and avoid doing the work again. The hard part is deciding what counts as a repeat.

A random ID minted on each attempt is useless, since every retry looks new. The model's tool call ID is only slightly better. It can survive a transport retry of one call, but when the model decides to try again you get a fresh call with a fresh ID.

Hashing the tool arguments is a tempting shortcut, and it fails in both directions. If the model rewrites an email on the second pass, one changed word produces a new hash and the message goes out again. If a customer is genuinely owed two identical partial refunds a week apart, the hashes match and the second one gets swallowed. Malcolm Featonby raised that second problem in an Amazon Builders' Library article on [making retries safe](https://aws.amazon.com/builders-library/making-retries-safe-with-idempotent-apis/). A caller may really want two identical EC2 instances, which is why many AWS APIs accept a ClientToken that identifies the request itself.

So take the key from whatever authorised the action. For a refund, that might be your customer account, the word refund, the charge ID and the ID of the approval record or support case line that asked for it. A welcome email can use the event and the user, much like the welcome-user/123456789 pattern in [Resend's documentation](https://resend.com/docs/dashboard/emails/idempotency-keys). A second legitimate refund arrives with its own approval record and therefore its own key.

Your application should supply that reference from the run context, so the model never gets to invent or edit it. Timestamps, attempt counters and anything the model composed stay out.

[How to build an AI agent kill switch before a loop burns your budget](https://startupfortune.com/how-to-build-an-ai-agent-kill-switch-before-a-loop-burns-your-budget/)

Knight Capital lost more than $440 million in roughly 45 minutes in 2012 because nobody could stop a faulty system fast enough. The fix is three layers: a per-run dollar breaker, a global flag, and short-lived credentials. The article also shows how to rehearse the drill in staging. - [how to build an AI agent kill switch](https://startupfortune.com/how-to-build-an-ai-agent-kill-switch-before-a-loop-burns-your-budget/) - [prevent AI agent loops burning your budget](https://startupfortune.com/how-to-build-an-ai-agent-kill-switch-before-a-loop-burns-your-budget/)

Keep a second value beside the key: a fingerprint of the parameters that mustn't change, such as the recipient, amount, currency and target object. Convert amounts to minor units before hashing, so £50 and 50.00 pounds can't drift apart. [RFC 8785](https://www.rfc-editor.org/rfc/rfc8785), the JSON Canonicalization Scheme, gives you a repeatable way to serialise the object first. When a request arrives with a known key and a different fingerprint, stop it and raise it for review. An agent approved for £50 that now asks for £500 needs a human.

Stripe also advises against putting email addresses or other personal data in keys, so hash those ingredients or use opaque IDs from your own database.

## Keep a ledger of side effects before you call anything

The key only helps if something remembers it. Create one table for every action that changes the outside world, with a unique constraint on the key and columns for the fingerprint, the exact outgoing payload, status, provider reference, response, first attempt time and a lease expiry.

In PostgreSQL, one statement can claim the work, with the lease length set as a column default: `INSERT INTO side_effects (effect_key, fingerprint, payload, status) VALUES ($1, $2, $3, 'sending') ON CONFLICT (effect_key) DO NOTHING RETURNING effect_key;` The [RETURNING clause](https://www.postgresql.org/docs/current/sql-insert.html) only gives back rows that were really inserted. Get a row and the job is yours. Get nothing and someone has been here before, perhaps a twin call the model fired in parallel a few milliseconds earlier.

Commit that row before you touch the network. If you hold the transaction open around the API call and the process dies, the database rolls back your only evidence while the money may already have moved.

What you do with an existing row depends on its status, once you've confirmed the fingerprints match. A succeeded row returns the stored result to the agent. A sending row with a live lease means wait. An expired lease turns the row unknown, never free to claim, because the dead worker may have completed the call a moment before it stopped. Mark a row failed only when the provider's answer proves nothing happened, such as a rejection at validation. Timeouts, connection resets and server errors belong under unknown.

Saving the exact payload pays off with generated content. On a retry, send the stored email word for word and ignore whatever new draft the model has produced. Resend answers a reused key carrying a different payload with a 409 error called invalid_idempotent_request, so a freshly worded retry gets refused even when your key is perfect.

Every route to the tool has to pass through this table, so put the check in the function that holds the API credentials. A guard inside the agent loop does nothing for a queue worker calling that function directly.

If you own the receiving service, record the key and make the change in the same transaction, the all-or-nothing approach Featonby describes. A third party's API won't give you that, and the space between their commit and yours is where unknown outcomes live.

## Check status before any retry

When a row is unknown, ask the destination what it has. This is far easier if you planted a marker on the way in. Put your effect key in the metadata when you create a Stripe refund, then [list refunds](https://docs.stripe.com/api/refunds/list) for that PaymentIntent or charge and match it in your code. For Zendesk tickets, the external_id field can carry your reference and be used to filter the ticket list.

A match settles it: save the provider's ID, mark the row succeeded and hand the result back. An empty answer deserves more suspicion. The original request may still be in flight, or a search index may be lagging. Wait, check again with increasing gaps, and resend only if the provider will deduplicate that second request for you, using the same key and the same stored payload.

Without a provider key to protect the resend, don't repeat the write automatically. If the lookup can't settle what happened, queue the case for a person with the payload and timestamps attached. A delayed ticket is an annoyance, while a second payout can be very hard to claw back.

Tell the model the truth in a form it can act on. Return something like "Outcome unknown. The refund may have completed and a status check is running. Do not issue another." For a repeat of a finished action, return the original reference and say it's already done. The ledger will still refuse a duplicate if the model ignores you.

## AI agent duplicate payment prevention and the limits of provider keys

Stripe's [idempotency layer](https://docs.stripe.com/api/idempotent_requests) is a good model, and its details reward a careful read. For API v1, it saves the status code and body of the first request once execution begins, including a 500, and replays that answer to later requests with the same key. It also errors if the parameters differ. Requests that fail validation or collide with one still running aren't saved, so you can retry those.

A 500 can therefore leave you holding a saved error and an uncertain charge. Stripe's [error handling guide](https://docs.stripe.com/error-low-level) treats that result as indeterminate. Minting a new key to get past it is the worst move available, because it can start a second operation. Reconcile through the API, dashboard or webhooks first.

Then there's the clock. Stripe may prune v1 keys once they're at least 24 hours old, and a key reused after pruning counts as a new request. Resend holds email keys for 24 hours. [Zendesk](https://developer.zendesk.com/api-reference/ticketing/introduction/) expires ticket creation keys after just two hours, after which the same request opens another ticket. A job parked overnight for approval can easily wake up outside the window. Store the first attempt time, and once that window has closed, switch from resending to reconciling.

Gmail needs more care. The [reference page for messages.send](https://developers.google.com/workspace/gmail/api/reference/rest/v1/users.messages/send) lists no idempotency parameter. Setting your own Message-ID and searching for it later sounds neat, but the engineering team at [Mixmax](https://www.mixmax.com/engineering/moving-to-the-gmail-api) reported that the Gmail API wouldn't let them set one. Test it on your own account before you rely on it. Until you've proved a marker survives, a timed-out Gmail send should stop for review.

Conflict errors vary too. Zendesk returns a 400 when a ticket key comes back with a different body, where Resend uses 409. An [IETF draft for the Idempotency-Key header](https://datatracker.ietf.org/doc/draft-ietf-httpapi-idempotency-key-header/), still not a finished standard, suggests 422 for that case. Write a small adapter per provider that translates each answer into your ledger's states.

## Idempotent tool calls for LLM agents don't come free with a framework

Durable execution helps you recover, and recovery can repeat work. [Temporal's documentation](https://docs.temporal.io/activity-definition) is blunt that activities may be executed more than once, and suggests combining the Workflow Run ID with the Activity ID as an idempotency key. That holds steady across retries of one activity. If your planner schedules a second activity for the same refund, or a separate workflow picks up the same customer request, the key changes. Pass your business-level effect key through the workflow and use that at the provider.

MCP has a tool annotation called idempotentHint, which defaults to false and signals that repeating a call with the same arguments should have no extra effect. The important word is hint. The [specification says](https://modelcontextprotocol.io/specification/2026-07-28/server/tools) clients must consider annotations untrusted unless they come from trusted servers. Even on a trusted server, a true or false flag can't tell you how long a request is remembered. Ask the maintainer, or read the code, before you switch on automatic retries.

## Break your own agent on purpose

Copy the test that opened this guide. Write a fake tool that performs the action and then raises a timeout, and run it many times on every model you ship. Next, kill the process after the provider accepts the request but before you update the ledger. Start two workers on one job. Have the retry arrive with a reworded email, then move your test clock past the provider's retention window.

Judge each run at the destination. Count refunds in the payment sandbox, messages in a catch-all inbox and tickets in a test help desk. A tidy agent transcript can sit on top of two payments, so the transcript proves very little.

Start with the tools that move money or contact people. If any of them retries automatically today with no ledger behind it, switch that off now. Your read-only calls can keep retrying while you build.

**Also read:** [How Does Visa Compelling Evidence 3.0 Work and What Should SaaS Teams Log?](https://startupfortune.com/how-does-visa-compelling-evidence-30-work-and-what-should-saas-teams-log/) • [How Long Can an ACH Payment Be Reversed After It Clears and You've Shipped?](https://startupfortune.com/how-long-can-an-ach-payment-be-reversed-after-it-clears-and-youve-shipped/) • [Is my fintech business account FDIC insured if the fintech itself fails?](https://startupfortune.com/is-my-fintech-business-account-fdic-insured-if-the-fintech-itself-fails/)

*This article is posted in [AI News](https://startupfortune.com/category/ai/), check it out for more related stories.*

## Join the discussion

[Open in the community →](https://startupfortune.com/community/)

Almost there. Sign in and your reply posts straight away.
