A coding agent hits a timeout waiting for create_invoice. The SDK retries. That sounds like resilience. If the first call already created the invoice, it is a duplicate charge with a cleaner stack trace.
I keep seeing this treated as an orchestration problem: add backoff, raise the timeout, tell the model "do not call the tool twice." None of that holds. Backoff retries the write. A longer timeout still expires. The model does not remember that the first call succeeded if it never saw the result.
The fix is older than agents. Side-effect tools need an idempotency key, the same way a payments API does. If you allow a retry, you already needed one.
What actually happens
The sequence is dull, which is why it keeps shipping:
- The agent calls
create_invoice({customer: "acme", amount: 4900}). - The billing service writes the row and the process, the proxy, or the MCP client times out before the id comes back.
- The runtime retries the same tool call.
- You now have two invoices.
Reads are fine to retry. Writes are not, unless the write is keyed. "The arguments look the same" is not a key. Two legitimate invoices for the same customer can have the same amount. The key has to be chosen by the caller, once, and reused on every retry of that attempt.
The wrapper
The runner below does three things:
- Refuse to run a side-effect tool without a non-empty key.
- If that key already completed, return the original result and do not run the function again.
- If a call is in flight with that key, refuse to start a second one.
It is the client-side half of the pattern. The destination still needs its own uniqueness guarantee. I will come back to that.
from __future__ import annotations
import threading
import time
from dataclasses import dataclass
from typing import Any, Callable
class IdempotencyKeyRequired(ValueError):
pass
class IdempotencyConflict(RuntimeError):
pass
@dataclass
class Record:
tool: str
key: str
status: str # in_flight | done
value: Any = None
created_at: float = 0.0
class IdempotentToolRunner:
"""Replay a side-effect tool safely when the agent retries."""
def __init__(
self,
store: dict[str, Record] | None = None,
clock: Callable[[], float] = time.time,
):
self._store = store if store is not None else {}
self._lock = threading.Lock()
self._clock = clock
def _slot(self, tool: str, key: str) -> str:
if key is None or not str(key).strip():
raise IdempotencyKeyRequired(
f"{tool}: side-effect tools require a non-empty idempotency_key"
)
return f"{tool}:{key}"
def run(self, tool: str, idempotency_key: str, fn: Callable[[], Any]) -> Any:
slot = self._slot(tool, idempotency_key)
with self._lock:
existing = self._store.get(slot)
if existing and existing.status == "done":
return existing.value
if existing and existing.status == "in_flight":
raise IdempotencyConflict(
f"{slot} is already in flight; wait or reuse the original result"
)
self._store[slot] = Record(
tool, idempotency_key, "in_flight", None, self._clock()
)
try:
value = fn()
except Exception:
# The side effect is not known to have succeeded. Drop the
# reservation so a later retry is allowed to try again.
with self._lock:
current = self._store.get(slot)
if current and current.status == "in_flight":
del self._store[slot]
raise
with self._lock:
self._store[slot] = Record(
tool, idempotency_key, "done", value, self._clock()
)
return value
Wire it at the tool boundary, not in the prompt. The agent, or the orchestrator that dispatches the agent, must pass a key that is stable across retries of the same attempt:
runner = IdempotentToolRunner()
def create_invoice_tool(customer: str, amount: int, idempotency_key: str) -> dict:
return runner.run(
"create_invoice",
idempotency_key,
lambda: billing_api.create(customer=customer, amount=amount),
)
A usable key is agent_run_id + tool_name + a counter the orchestrator increments per new intent. Hashing the arguments alone is a trap: a real second invoice can look identical to a retry.
What it does, on purpose
A clean retry returns the first result and does not write again:
writes: list[str] = []
def create_invoice(amount: int) -> dict:
writes.append(f"invoice-{amount}")
return {"invoice_id": f"inv_{len(writes)}", "amount": amount}
runner = IdempotentToolRunner()
first = runner.run("create_invoice", "req-1", lambda: create_invoice(4900))
second = runner.run("create_invoice", "req-1", lambda: create_invoice(4900))
assert first == second == {"invoice_id": "inv_1", "amount": 4900}
assert writes == ["invoice-4900"]
# A different key is a different intent and is allowed to write.
third = runner.run("create_invoice", "req-2", lambda: create_invoice(4900))
assert third["invoice_id"] == "inv_2"
assert writes == ["invoice-4900", "invoice-4900"]
An empty key is rejected. That is not pedantry. If the field is optional, the agent will omit it, and you are back to duplicate writes.
try:
runner.run("refund", " ", lambda: {"ok": True})
raise AssertionError("empty key should fail")
except IdempotencyKeyRequired:
pass
What it cannot save you from
If the first call raises — timeout, process crash, a dropped connection — this runner forgets the reservation. That is deliberate. A client-side cache cannot know whether the write landed. Allowing a retry is the only honest option unless the destination also keys the write.
That is the part people skip. A wrapper in your agent runtime is not enough if the billing API will happily create a second invoice for the same key it has never seen. Send the key through:
- Stripe-style:
Idempotency-Keyon the request, unique constraint on the server. - GitHub: a unique
external_id, or a well-defined "find or create" on a branch name you control. - Your own table:
UNIQUE(idempotency_key)before the side effect, return the existing row on conflict.
If you only keep the cache in process memory, a restart loses it and a second worker will not see it. Put the Record store in Redis or Postgres if more than one process can run the tool. The interface above already accepts an external store dict; swap it for something durable.
A concurrent second caller while the first is in flight gets IdempotencyConflict instead of a second write. That is the correct failure. Wait, or return the eventual result; do not start another invoice.
What I will not do
I will not "just retry three times with exponential backoff" and call it a reliability design. Backoff is for reads, and for writes that are already idempotent.
I will not ask the model to be careful. Prompt text is not a uniqueness constraint.
I will not hash tool arguments and call that an idempotency key. Retries and new intents can share arguments.
If a tool can be retried, it already needed a key. Put the key on the call, remember the result, and make the destination reject a second write for the same key. Everything else is a cleaner way to do the work twice.
This article was AI-assisted: an assistant helped tighten wording. The code was written and run locally; I verified the tests. The opinions are mine.
Top comments (0)