# Tool Calls That Can't Double-Charge: Idempotency for Agents

Make agent tool calls idempotent in Python: stable keys, stored results and a demo that cuts 1,085 duplicate charges to zero over 2,000 seeded runs.

Author: Steven Phan
Published: 2026-11-12
Article: https://stevenphan.ca/blog/agent-tool-call-idempotency-python/

## Quick answer

Agent tool call idempotency means a retried call cannot repeat its side effect. If an agent calls a payments tool, the request times out and the agent tries again, you want one charge, not two. The fix is a stable idempotency key for each logical action, a service that remembers results by key, and a small wrapper that returns the stored result when the same action comes around again.

The dangerous failure is not the call that fails before doing anything. It's the call that does the work and then times out, because the agent only sees an error. In our demo, a naive retry loop produced 1,085 duplicate side effects across 6,000 intended ones. The keyed wrapper produced zero. The agent in the demo is a scripted stub, not a real language model, so those numbers describe the stub and a fake service, not any real agent or payments provider.

<nav class="toc" aria-label="Table of contents">
<p><strong>On this page</strong></p>
<ol>
<li><a href="#why-agents-repeat-side-effects">Why agents repeat side effects</a></li>
<li><a href="#download-and-run-the-demo">Download and run the demo</a></li>
<li><a href="#the-flaky-service-and-the-naive-retry-loop">The flaky service and the naive retry loop</a></li>
<li><a href="#derive-one-stable-key-per-logical-action">Derive one stable key per logical action</a></li>
<li><a href="#wrap-the-tool-and-store-results">Wrap the tool and store results</a></li>
<li><a href="#before-and-after-over-2000-seeded-runs">Before and after over 2,000 seeded runs</a></li>
<li><a href="#failure-modes-keys-ttls-and-concurrent-retries">Failure modes: keys, TTLs and concurrent retries</a></li>
<li><a href="#which-calls-dont-need-a-key">Which calls don't need a key</a></li>
<li><a href="#tests-you-can-run">Tests you can run</a></li>
<li><a href="#limits-of-this-demo">Limits of this demo</a></li>
<li><a href="#faq">FAQ</a></li>
<li><a href="#where-to-go-next">Where to go next</a></li>
</ol>
</nav>

![Timeline diagram with two lanes, the agent and wrapper above and the service below. Step 1, the agent calls with key K. Step 2, the service does the work, charging once and storing the result under key K. Step 3, the reply is lost to a timeout, shown as a dashed amber arrow with a cross. Step 4, the agent retries with the same key K. Step 5, the service sees key K already used and returns the stored result with no second charge. Step 6, the agent gets one result and one charge. A final box reads Charges: 1, not 2.](https://stevenphan.ca/_astro/idempotency-retry-flow.Da9r1W1Z_dTQXU.webp)

## Why agents repeat side effects

A normal program retries because you wrote a retry loop. An agent retries for the same reason, plus a few more. The framework may retry on a transport error. The model may see "request timed out" in its context and decide to call the tool again. A long task may be resumed after a crash, and the model replays a step it cannot prove finished.

Each is reasonable on its own. The trouble is that a timeout does not tell you whether the work happened. The request might have died before it reached the service, or the service might have finished and the reply got lost on the way back. From the caller's side the two cases look identical.

Reads are fine to repeat. Writes aren't: a charge, an email, a ticket, a refund, a row inserted into a table. This is the same line the [read-only MCP tool tutorial](https://stevenphan.ca/blog/mcp-python-read-only-tool/) draws when it gives a model a lookup it can call safely. This post covers the other side, where the tool changes something and a repeat has a cost.

An operation is idempotent when doing it twice leaves the system in the same state as doing it once. Most writes aren't, so you attach a key that says "this is the same action as before."

## Download and run the demo

Download the [idempotency demo project](https://stevenphan.ca/downloads/agent-tool-call-idempotency-python.zip) and extract it into a new folder. You need Python 3.10 or newer. There are no packages to install, no API keys and no network calls.

```text
README.md
agent.py
fake_services.py
idempotency.py
simulate.py
failures.py
test_idempotency.py
```

From the extracted folder, run these (we ran all three from a fresh unzip while writing this post, using Python 3.13):

```bash
python3 simulate.py
python3 failures.py
python3 -m unittest -v
```

On Windows, use `py -3` instead of `python3`. Every number in this post comes from those scripts.

## The flaky service and the naive retry loop

The fake service in `fake_services.py` has two writes, `charge` and `create_ticket`, and one read, `get_balance`. Each write rolls a seeded random number. With 5 percent probability it times out before doing any work. With 15 percent probability it does the work and then times out. Those rates are our demo settings, high enough that the problem shows quickly. They are not measurements of any real service.

The scripted agent in `agent.py` follows a fixed plan of three logical actions: charge 4,900 cents, charge 1,500 cents and open a ticket. When a call raises a timeout, it calls again, up to three attempts. That's all the stub does. There's no model in the loop, and the file marks the one place where you'd swap in a real model call to decide what to do next.

Here's the naive version, which calls the service directly with no key and no memory:

```python
# Naive call path used by simulate.py in "naive" mode.
def call_tool(run_id, step_id, tool, args):
    return getattr(svc, tool)(**args)   # no key, no store
```

We ran 2,000 seeded runs of this. The agent intended 6,000 effects, and the service recorded 7,085. The extra 1,085 are duplicates: customers charged twice or three times, or a second ticket opened for the same welcome call.

## Derive one stable key per logical action

An idempotency key identifies one logical action, not one attempt. The first attempt, the second retry and the replay after a crash should all carry the same key, and a different action should get a different key.

The obvious question is who makes the key. [Stripe's idempotent requests documentation](https://docs.stripe.com/api/idempotent_requests) (checked 2026-11-12) says the client generates the key and suggests V4 UUIDs or another random string with enough entropy, up to 255 characters, and says to avoid sensitive data such as email addresses inside keys. A random UUID works when your code creates it once per operation and keeps it for the retries.

Agents add a wrinkle. If the model re-emits the tool call after a timeout, your code may not be holding on to a key from the first attempt. So the demo derives the key deterministically from things your orchestrator already knows:

```python
# Excerpt from idempotency.py. We ran this through the tests in the zip.
def derive_key(tool, run_id, step_id):
    raw = json.dumps([tool, run_id, step_id], separators=(",", ":"))
    return hashlib.sha256(raw.encode()).hexdigest()
```

The inputs are the tool name, a run ID and a step ID. Your orchestrator assigns the run and step IDs. The model never invents them, and nothing in the key comes from the clock, a random generator or an attempt counter. Hashing keeps the key short.

If your application already creates a key per operation and stores it before the first attempt, that works as well. What matters is that every retry of one logical action presents the same key.

## Wrap the tool and store results

The key alone is not enough, and the demo shows why. There are two places a repeat can be caught:

1. **The service.** If the service stores the result under the key, a retry after a lost reply gets the stored result back. This is the only layer that can fix the timeout-after-work case, because the caller never received a result to store.
2. **Your wrapper.** If your own code stores finished results by key, a repeat of an action that already succeeded never reaches the service. This helps when the service has no key support, when a key's TTL has run out, or when you want to skip a pointless network call.

`IdempotentTool` in `idempotency.py` does both. In outline, from the file:

```python
# Condensed from IdempotentTool.__call__ in idempotency.py (tested in the zip).
key = derive_key(self.tool_name, run_id, step_id)
fp = fingerprint(args)
hit = self.store.get(key)
if hit:
    if hit["fp"] != fp:
        raise ValueError("same logical action, different arguments")
    return hit["result"]                 # already done: no service call
kwargs = dict(args)
kwargs["idempotency_key"] = key          # lets the service dedupe a lost reply
result = self.fn(**kwargs)               # may raise a timeout: nothing stored
self.store.put(key, fp, result)
return result
```

Two details are worth noticing. First, a timeout stores nothing, because there is no result to store. The next attempt goes to the service with the same key and the service answers from its own record. Second, the wrapper keeps a fingerprint of the arguments. If the same logical action shows up again with different arguments, it refuses, which catches a model that "corrects" an amount mid-retry.

The full class also holds a per-key gate so two threads handling the same action don't both run it.

## Before and after over 2,000 seeded runs

`simulate.py` runs four setups through the same 2,000 seeds, so each run faces the same fault rolls where the call sequence is the same. It counts a duplicate as any effect beyond one per logical action. Here's the real output:

```text
2000 seeded runs x 3 logical actions = 6000 intended effects; replay chance after success = 0%
mode                                  effects  duplicates  never done  saw 3 timeouts  service calls
naive retry (no key, no store)           7085        1085           0              44           7476
local store only (key not sent)          7085        1085           0              44           7476
key sent to service only                 6000           0           0              44           7476
wrapper: key + local store               6000           0           0              44           7476

2000 seeded runs x 3 logical actions = 6000 intended effects; replay chance after success = 10%
mode                                  effects  duplicates  never done  saw 3 timeouts  service calls
naive retry (no key, no store)           7633        1633           0              48           8053
local store only (key not sent)          7085        1085           0              44           7476
key sent to service only                 6000           0           0              48           8053
wrapper: key + local store               6000           0           0              44           7476
```

What the table says, for this stub and this fake service:

- **Naive retries duplicate.** 1,085 duplicates out of 6,000 intended effects, which is about 18 percent extra.
- **A local store alone does not fix timeouts.** The row matches the naive row in the first table. When the reply is lost, there is nothing to store, so the retry hits the service again with no key and does the work twice.
- **The key sent to the service does the heavy lifting** for the timeout case: zero duplicates in both tables.
- **The local store earns its place in the second table.** There, the stub re-issues a step that already succeeded 10 percent of the time, imitating a model that loses track of its progress. The wrapper answers those from its store, so it makes 7,476 service calls against 8,053 for the key-only setup. Both end at zero duplicates.

"Never done" is zero in every row, which means every intended action did happen at least once. It doesn't mean the agent knew that. The "saw 3 timeouts" column counts steps where the agent used up its attempts and gave up, even though the work had usually succeeded on the service side. Idempotency stops the double charge. It does not tell the agent the first attempt worked. For that, give the agent a read tool such as "look up this charge by key" and have it check before reporting failure.

## Failure modes: keys, TTLs and concurrent retries

`failures.py` makes each of these visible. All counts below are real output from that script.

### Key derivation mistakes

```text
== 1. key derivation mistakes (2000 seeded runs, 3 actions each) ==
  stable key per logical action : 0 duplicates
  random uuid on every attempt  : 1085 duplicates
  attempt number inside the key : 1085 duplicates
  args-only key, 2 real coffees : 1 charge recorded (1 customer purchase silently dropped)
  per-step key, 2 real coffees  : 2 charges recorded
```

A key that changes on every attempt is the same as no key. That covers a fresh random UUID per call, a timestamp, and an attempt number baked into the key. The duplicate count matches the naive run exactly, 1,085, because every retry looks new to the service.

The opposite mistake is a key that is too coarse. Building the key from the arguments alone means two separate but identical purchases collapse into one, and the second customer purchase is silently dropped. Dropping a real action is harder to notice than repeating one, because nothing errors. Keying on the run and step avoids both, as long as your plan gives the two coffees two different step IDs.

### TTLs

```text
== 2. TTL: the key expires before the retry arrives ==
  service key TTL 60s, retry after  30s -> 1 charge(s)
  service key TTL 60s, retry after 120s -> 2 charge(s)
```

Stored keys cannot live forever. Stripe's documentation (checked 2026-11-12) says that for API v1, keys can be removed automatically once they are at least 24 hours old, and a new request is generated if a key is reused after pruning. The demo uses a 60 second TTL on a manual clock only so the effect is instant.

Pick a TTL longer than your longest realistic retry window, including a resumed job that waits for a human or a queue. If a retry could arrive after the key expires, your own wrapper store should outlive the service's, or you need a way to look up what already happened before you retry.

### Concurrent retries

```text
== 3. concurrent retries of the same logical action (8 threads) ==
  service dedupe, check then act, no lock : 8 charge(s) from 8 simultaneous calls
  service dedupe, atomic check-and-store  : 1 charge(s) from 8 simultaneous calls
  wrapper in-flight gate, same process, buggy service: 1 charge(s)
```

Two retries can be in flight at once, for example a worker that timed out and a second worker that picked up the same job. If the service checks "have I seen this key?" and then acts in two separate steps, both callers can pass the check before either records the key. The "no lock" line shows 8 charges from 8 calls here. That number depends on thread timing, so it varies from run to run; in one rerun of the same script we saw 4. The point holds either way: it's more than one.

The fix on the service side is one atomic step: check and record the key together, for example with a database unique constraint or a lock. Your own wrapper helps within one process, since its per-key gate made the 8 threads produce a single charge even against the buggy service. It cannot help across separate machines, so the service has to do the atomic check.

### Reusing a key with different arguments

```text
== 4. same key, different arguments ==
  second call refused: key 2440b52a3596 reused with different arguments
  charges recorded: 1
```

A service should refuse a repeated key whose arguments changed rather than guess which request was meant. Stripe's documentation says its idempotency layer compares incoming parameters with the original request and errors if they differ. Treat that error as a real signal. It usually means a model changed its mind mid-retry, or your step IDs are not unique.

## Which calls don't need a key

Reads. Looking up a balance, listing tickets, fetching a record and searching a document store don't change anything, so repeating them is harmless. In the demo, five repeated `get_balance` calls returned the same value and created no new effects:

```text
== 5. reads do not need keys ==
  5 repeated get_balance calls -> {4900}, new effects: 0
```

Stripe's documentation (checked 2026-11-12) makes the same point for its API: send keys on `POST` requests, and do not bother on `GET` and `DELETE`, which are idempotent by definition. Be careful with the word "by definition" in your own tools, though. A tool named `get_report` that also marks the report as emailed is not a read. Judge a tool by what it changes, not by its name.

A short checklist for each tool you give an agent:

- Does it create, send, charge, delete or update something? If yes, it needs a key and a stored result.
- Can the service accept a key? If not, put a lookup read in front of the write ("is there already a ticket with this reference?") and decide who does the check atomically.
- Is the effect something you can't take back, like an email? Keep a record of what you sent and check it before sending again.

If you're building a loop like this from scratch, the [build an AI agent in Python tutorial](https://stevenphan.ca/blog/build-an-ai-agent-in-python/) shows the tool-calling loop that these wrappers slot into.

## Tests you can run

`test_idempotency.py` has 12 tests using the standard library's `unittest` (pytest also collects them). We ran them from a fresh unzip and they all passed:

```text
Ran 12 tests in 0.062s

OK
```

They check that:

- keys are stable and differ by step, run and tool
- three timeouts after the work still leave exactly one charge through the wrapper, and three through the naive path
- a finished action is replayed from the store without a second service call
- two real purchases with different step IDs both happen
- the same step with different arguments is refused, by the wrapper and by the service
- an expired service key allows a duplicate, which documents the TTL risk
- eight concurrent callers through the wrapper make one charge
- reads leave the effect count unchanged
- the wrapper has zero duplicates in a smaller simulation while the naive path does not

For a new write tool in your own agent, a test that forces a timeout after the work is the one that catches the bug.

## Limits of this demo

The agent is a script. It does not decide anything, it doesn't hallucinate a different amount, and it never forgets to reuse a key. A real model will sometimes do each of those, so real duplicate rates and failure patterns will differ from the numbers here.

The service is fake and in memory. Real payment and ticket systems have their own key rules, retention periods and error codes. Read the documentation for the service you call, and check it again before you rely on a detail, because those rules can change.

The 5 and 15 percent timeout rates, the 2,000 seeds and the 10 percent replay chance are our demo settings. The wrapper's store is a Python dictionary, so it vanishes when the process exits. In real code, put it in a database, write the key before the first attempt, and make the check atomic.

Finally, a key stops an accidental repeat. It does nothing about a prompt that talks an agent into a first charge it shouldn't make.

## FAQ

### Why do AI agents retry tool calls and repeat side effects?

A timeout does not say whether the work happened, so a framework or a model may call the tool again. If the service had already finished and only the reply was lost, the retry repeats the charge, email or ticket. In our demo, a naive retry loop produced 1,085 duplicates out of 6,000 intended effects.

### What is an idempotency key for an agent tool call?

It is an identifier for one logical action that stays the same across every retry of that action. The service uses it to recognize a repeat and return the stored result. In the demo, the key is derived from the tool name, a run ID and a step ID that the orchestrator assigns.

### Can a local result store alone stop duplicate charges?

No. When the service completes the work and the reply times out, the caller has no result to store, so the retry runs the work again. In the demo, the local store alone matched the naive retry at 1,085 duplicates. Sending the key to a service that stores results fixed the timeout case.

### How long should an idempotency key live?

Longer than your longest realistic retry window. In the demo, a retry after the 60 second TTL expired created a second charge. Stripe's documentation says keys for API v1 can be removed automatically once they're at least 24 hours old (checked 2026-11-12).

### Do read-only tool calls need idempotency keys?

No. Reads do not change anything, so repeating them is harmless. In the demo, five repeated balance lookups created zero new effects. Judge a tool by what it changes, because a tool with a read-like name can still have a side effect.

### What goes wrong when two retries run at the same time?

If the service checks a key and acts in two separate steps, both callers can pass the check and both do the work. In the demo, a service without an atomic check recorded several charges from 8 simultaneous calls, and the exact count varied between runs. An atomic check-and-store gave one charge.

## Where to go next

- Add a write tool to your own agent loop from the [build an AI agent in Python tutorial](https://stevenphan.ca/blog/build-an-ai-agent-in-python/), then give it a step ID scheme and the wrapper from this demo.
- Compare with the read-only side of tool design in the [MCP server tutorial](https://stevenphan.ca/blog/mcp-python-read-only-tool/).
- Replace the stub in `agent.py` with a real model call at the marked spot, and rerun `simulate.py` to see how your own agent's retry behaviour compares.
- Read the [Stripe idempotent requests documentation](https://docs.stripe.com/api/idempotent_requests) for how one production API handles keys, pruning and parameter mismatches.
