{"slug": "if-your-agent-can-retry-the-tool-already-needs-an-idempotency-key", "title": "If Your Agent Can Retry, the Tool Already Needs an Idempotency Key", "summary": "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.", "body_md": "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.\n\nI 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.\n\nThe 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.\n\nThe sequence is dull, which is why it keeps shipping:\n\n`create_invoice({customer: \"acme\", amount: 4900})`.\nReads 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.\n\nThe runner below does three things:\n\nIt is the client-side half of the pattern. The destination still needs its own uniqueness guarantee. I will come back to that.\n\n``` python\nfrom __future__ import annotations\n\nimport threading\nimport time\nfrom dataclasses import dataclass\nfrom typing import Any, Callable\n\nclass IdempotencyKeyRequired(ValueError):\n    pass\n\nclass IdempotencyConflict(RuntimeError):\n    pass\n\n@dataclass\nclass Record:\n    tool: str\n    key: str\n    status: str  # in_flight | done\n    value: Any = None\n    created_at: float = 0.0\n\nclass IdempotentToolRunner:\n    \"\"\"Replay a side-effect tool safely when the agent retries.\"\"\"\n\n    def __init__(\n        self,\n        store: dict[str, Record] | None = None,\n        clock: Callable[[], float] = time.time,\n    ):\n        self._store = store if store is not None else {}\n        self._lock = threading.Lock()\n        self._clock = clock\n\n    def _slot(self, tool: str, key: str) -> str:\n        if key is None or not str(key).strip():\n            raise IdempotencyKeyRequired(\n                f\"{tool}: side-effect tools require a non-empty idempotency_key\"\n            )\n        return f\"{tool}:{key}\"\n\n    def run(self, tool: str, idempotency_key: str, fn: Callable[[], Any]) -> Any:\n        slot = self._slot(tool, idempotency_key)\n        with self._lock:\n            existing = self._store.get(slot)\n            if existing and existing.status == \"done\":\n                return existing.value\n            if existing and existing.status == \"in_flight\":\n                raise IdempotencyConflict(\n                    f\"{slot} is already in flight; wait or reuse the original result\"\n                )\n            self._store[slot] = Record(\n                tool, idempotency_key, \"in_flight\", None, self._clock()\n            )\n\n        try:\n            value = fn()\n        except Exception:\n            # The side effect is not known to have succeeded. Drop the\n            # reservation so a later retry is allowed to try again.\n            with self._lock:\n                current = self._store.get(slot)\n                if current and current.status == \"in_flight\":\n                    del self._store[slot]\n            raise\n\n        with self._lock:\n            self._store[slot] = Record(\n                tool, idempotency_key, \"done\", value, self._clock()\n            )\n        return value\n```\n\nWire 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:\n\n``` python\nrunner = IdempotentToolRunner()\n\ndef create_invoice_tool(customer: str, amount: int, idempotency_key: str) -> dict:\n    return runner.run(\n        \"create_invoice\",\n        idempotency_key,\n        lambda: billing_api.create(customer=customer, amount=amount),\n    )\n```\n\nA 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.\n\nA clean retry returns the first result and does not write again:\n\n``` php\nwrites: list[str] = []\n\ndef create_invoice(amount: int) -> dict:\n    writes.append(f\"invoice-{amount}\")\n    return {\"invoice_id\": f\"inv_{len(writes)}\", \"amount\": amount}\n\nrunner = IdempotentToolRunner()\nfirst = runner.run(\"create_invoice\", \"req-1\", lambda: create_invoice(4900))\nsecond = runner.run(\"create_invoice\", \"req-1\", lambda: create_invoice(4900))\n\nassert first == second == {\"invoice_id\": \"inv_1\", \"amount\": 4900}\nassert writes == [\"invoice-4900\"]\n\n# A different key is a different intent and is allowed to write.\nthird = runner.run(\"create_invoice\", \"req-2\", lambda: create_invoice(4900))\nassert third[\"invoice_id\"] == \"inv_2\"\nassert writes == [\"invoice-4900\", \"invoice-4900\"]\n```\n\nAn 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.\n\n```\ntry:\n    runner.run(\"refund\", \"  \", lambda: {\"ok\": True})\n    raise AssertionError(\"empty key should fail\")\nexcept IdempotencyKeyRequired:\n    pass\n```\n\nIf 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*.\n\nThat 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:\n\n`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.\nIf 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.\n\nA 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.\n\nI 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.\n\nI will not ask the model to be careful. Prompt text is not a uniqueness constraint.\n\nI will not hash tool arguments and call that an idempotency key. Retries and new intents can share arguments.\n\nIf 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.\n\n*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.*", "url": "https://wpnews.pro/news/if-your-agent-can-retry-the-tool-already-needs-an-idempotency-key", "canonical_source": "https://dev.to/faultline_dev/if-your-agent-can-retry-the-tool-already-needs-an-idempotency-key-1a16", "published_at": "2026-11-23 02:37:12+00:00", "updated_at": "2026-11-23 02:41:42.354542+00:00", "lang": "en", "topics": ["ai-agents", "ai-tools", "developer-tools", "ai-safety"], "entities": [], "also_reported_by": [], "takeaway": "Give every side-effect tool a caller-chosen idempotency key (agent_run_id + tool_name + per-intent counter) and replay stored results on retry, because argument hashing and prompt instructions cannot prevent duplicate writes.", "recommendation": {"advice": "Key every side-effect tool call with a stable caller-chosen idempotency key and replay the stored result on retry, rather than relying on backoff or prompt instructions to avoid duplicate writes.", "playbook": "agent-architecture", "playbook_url": "https://wpnews.pro/playbooks/agent-architecture"}, "alternates": {"html": "https://wpnews.pro/news/if-your-agent-can-retry-the-tool-already-needs-an-idempotency-key", "markdown": "https://wpnews.pro/news/if-your-agent-can-retry-the-tool-already-needs-an-idempotency-key.md", "text": "https://wpnews.pro/news/if-your-agent-can-retry-the-tool-already-needs-an-idempotency-key.txt", "jsonld": "https://wpnews.pro/news/if-your-agent-can-retry-the-tool-already-needs-an-idempotency-key.jsonld"}}