If Your Agent Can Retry, the Tool Already Needs an Idempotency Key A developer argues that side-effect tools called by coding agents must carry caller-chosen idempotency keys, since SDK-level retries after a timeout can duplicate writes like invoice creation. The writeup presents an IdempotentToolRunner that tracks in-flight and completed calls by tool and key, replays stored results on retry, and rejects concurrent in-flight duplicates, with keys derived from agent run ID, tool name and a per-intent counter rather than hashed arguments. 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. The sequence is dull, which is why it keeps shipping: create invoice {customer: "acme", amount: 4900} . 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 runner below does three things: It is the client-side half of the pattern. The destination still needs its own uniqueness guarantee. I will come back to that. python 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: python 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. A clean retry returns the first result and does not write again: php 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 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: Idempotency-Key on the request, unique constraint on the server. external id , or a well-defined "find or create" on a branch name you control. 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. 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.