AIEP
Reliability & ResilienceValidated in ProductionUpdated 2026-11

Idempotent Tool Calls

Give every side-effecting tool call a key derived from the run and its arguments, so a retried, re-issued or replayed call returns the first result instead of sending, charging or writing twice.

Runnable example, tested in CISourceTestsJump to code
$cd examples && pytest reliability/test_idempotent_tool_calls.py
agentstoolsretriesidempotencyside-effects

What It Is

Idempotency keys, the standard way payment and messaging APIs make retries safe, applied to agent tool calls. Every call to a tool with side effects gets a key built from the run, the tool name and the canonical arguments. Before running the tool, an executor records that the call has started. Afterwards it records the result. A repeat of a finished call returns the stored result without touching the tool. The key also goes to the downstream API, so a repeat that slips through is still deduplicated at the far end.

The Problem It Solves

Agent systems repeat themselves far more than ordinary services do:

  • The tool call times out after the email was actually sent. The model sees an error and calls send_email again.
  • The worker crashes mid-run, the job restarts, and the loop replays from the last checkpoint. Every tool call since then runs again.
  • Semantic Rollback retries a failed step, and the step includes a payment.
  • The model, unsure whether something worked, simply does it again "to be safe".

Each of these is harmless for reads and costly for writes: a customer gets three refund emails, a card is charged twice, a ticket is filed four times. The model can't prevent this. It has no reliable memory of what actually happened outside its context.

How It Works

flowchart TD
    C["Tool call (run, tool, args)"] --> R{"Side-effecting?"}
    R -->|"no"| X["Run it"]
    R -->|"yes"| K["key = hash(run, tool, canonical args, nonce)"]
    K --> L{"Ledger has key?"}
    L -->|"done"| D["Return stored result
(tool not run)"] L -->|"started, API dedupes by key"| S L -->|"started, no dedupe"| H["Hold: needs reconciliation"] L -->|"no, or failed"| S["Record 'started'"] S --> T["Run tool, passing the key downstream"] T -->|"ok"| OK["Record 'done' + result"] T -->|"clean error"| F["Record 'failed' (safe to retry)"]
  1. Derive the key from what makes the action unique: run ID, tool, and arguments serialized canonically (sorted keys), so the same action always gets the same key. Add a nonce only for actions that are meant to repeat, like a reminder sent once a day.
  2. Record intent before acting. Write "started" first. If the process dies after the side effect but before the result is saved, the record is the evidence that something may have happened.
  3. Answer repeats from the ledger. A key marked "done" returns the stored result. The model gets the same receipt as the first time and moves on.
  4. Pass the key downstream. Stripe, many payment providers and a growing number of APIs accept an Idempotency-Key header and deduplicate on their side. This covers the window between "sent" and "recorded".
  5. Don't guess after a crash. A "started" record with no result, for a tool whose API can't deduplicate, means you don't know whether it happened. Hold it for a status lookup or a person rather than running it again.
  6. Refuse key reuse with different arguments. If the same explicit key arrives with different arguments, that's a bug, not a retry.

When to Use It

  • Agents or workflows that call tools which send, charge, book, create or delete.
  • Anything with automatic retries, checkpoint replay, or a "try again" button.
  • Tools whose downstream API accepts idempotency keys. Then the pattern is cheap and closes the crash window completely.

When NOT to Use It

  • Read-only tools. Searching twice is harmless, so skip the ledger (the example does).
  • Actions that are naturally idempotent. "Set status to shipped" and PUT with a full resource body are already safe to repeat. A key adds nothing.
  • When repeats are the point, like polling or sampling. Use a nonce per intended repetition, or leave those tools out.

Trade-offs

  • A durable ledger on the hot path. Every side-effecting call needs two writes (started, done) to storage that survives a crash. An in-memory dict, as in the example, only protects within one process.
  • Choosing the key is a product decision. Too coarse (just the tool name) and legitimate second actions are swallowed. Too fine (a timestamp in the arguments) and nothing is ever deduplicated. Argument canonicalization matters: {"a":1,"b":2} and {"b":2,"a":1} must produce one key.
  • Reconciliation needs an owner. The "started, no result" cases are rare and need a status lookup or a person. If nobody looks at them, they pile up as silently skipped actions.

Failure Modes

Volatile values in the arguments. The model includes "sent at 10:42" or a fresh UUID in the arguments, so each retry gets a new key and the deduplication never fires. Exclude volatile fields from the key, or have the tool schema take only stable inputs.

Record after acting, not before. The executor writes the ledger only after success. A crash between the side effect and the write leaves no trace, and the replay does it again. Write "started" first.

Treating every error as retryable. A timeout after the request reached the provider is not the same as a refused connection. Retry with the same key, so the provider can tell you it already did it.

Key scoped too widely. Keys built only from the arguments, with no run ID, make two different customers' identical refund emails collide. Include the run or conversation in the key.

Implementation Example

An executor with a ledger keyed by run, tool and canonical arguments. Read-only tools skip it. Intent is recorded before running, the key is passed downstream, held calls raise NeedsReconciliation, and key reuse with different arguments is refused. The tests simulate a process dying after the email went out but before the result was recorded, and show the retry deduplicated downstream. They also show that the same crash against an API without key support is held, not repeated.

cd examples && pytest reliability/test_idempotent_tool_calls.py
"""Idempotent Tool Calls.
 
Agents retry. The model re-issues a call after a timeout, the loop restarts
after a crash, the user clicks "try again". For a tool that sends, charges or
writes, each retry can do the thing twice.
 
Each side-effecting call gets an idempotency key derived from the run and the
call itself. The executor records the call before running it and the result
after. A repeat of a completed call returns the stored result without running
the tool. A repeat of a call that started but never recorded a result (the
process died mid-call) is not re-run blindly: the key is passed to the
downstream API so it can deduplicate, or the call is held for reconciliation.
"""
 
from __future__ import annotations
 
import hashlib
import json
from collections.abc import Callable
from dataclasses import dataclass, field
from typing import Any
 
Tool = Callable[[dict, str], Any]  # (arguments, idempotency_key) -> result
 
 
class NeedsReconciliation(Exception):
    """A previous attempt started and never finished; we can't tell if it took effect."""
 
 
class KeyReuse(Exception):
    """The same explicit key was used with different arguments."""
 
 
@dataclass
class Record:
    key: str
    tool: str
    args_hash: str
    state: str  # "started" | "done" | "failed"
    result: Any = None
 
 
def canonical(args: dict) -> str:
    return json.dumps(args, sort_keys=True, separators=(",", ":"))
 
 
def make_key(run_id: str, tool: str, args: dict, nonce: str = "") -> str:
    """Same run + same tool + same arguments = same action. `nonce` separates
    actions that are genuinely meant to repeat (two identical reminders, a day apart)."""
    blob = f"{run_id}\x00{tool}\x00{canonical(args)}\x00{nonce}"
    return hashlib.sha256(blob.encode()).hexdigest()[:32]
 
 
@dataclass
class IdempotentExecutor:
    tools: dict[str, Tool]
    side_effecting: set[str]  # read-only tools skip all of this
    downstream_dedupes: set[str] = field(default_factory=set)  # APIs that honour an idempotency key
    store: dict[str, Record] = field(default_factory=dict)  # use a durable table in production
    executions: int = 0
 
    def call(self, run_id: str, tool: str, args: dict, key: str | None = None, nonce: str = "") -> Any:
        if tool not in self.side_effecting:
            return self._run(tool, args, "")
 
        key = key or make_key(run_id, tool, args, nonce)
        args_hash = hashlib.sha256(canonical(args).encode()).hexdigest()
        existing = self.store.get(key)
        if existing and existing.args_hash != args_hash:
            raise KeyReuse(f"key {key[:8]}… was first used with different arguments")
 
        if existing and existing.state == "done":
            return existing.result  # the retry is answered from the record; nothing runs
        if existing and existing.state == "started" and tool not in self.downstream_dedupes:
            # Crashed mid-call last time. Running again might do it twice; not running
            # might skip it. Only a person or a status lookup can say which.
            raise NeedsReconciliation(f"{tool} {key[:8]}… started earlier and has no result")
 
        # Record intent first, so a crash after the side effect still leaves a trace.
        self.store[key] = Record(key, tool, args_hash, "started")
        try:
            result = self._run(tool, args, key)
        except Exception:
            # A clean failure (the API said no) is safe to retry with the same key.
            self.store[key].state = "failed"
            raise
        self.store[key].state, self.store[key].result = "done", result
        return result
 
    def _run(self, tool: str, args: dict, key: str) -> Any:
        self.executions += 1
        return self.tools[tool](args, key)

Tool Landscape

ToolNotes
Stripe, Adyen, PayPal and similar APIsAccept an idempotency key header and replay the original response
Temporal, Restate, DBOS, InngestDurable execution records completed steps and doesn't re-run them on replay
Postgres / RedisA unique constraint or SET NX on the key is the core of a home-grown ledger
LangGraph checkpointersPersist completed node outputs so resumed graphs don't redo work
  • Semantic Rollback retries failed steps. This pattern keeps those retries from repeating side effects.
  • Human-in-the-Loop is where "needs reconciliation" calls should go.
  • Guardrails decide whether a tool may run at all. This pattern decides whether it already did.
  • Request Hedging for LLMs duplicates requests on purpose, so never hedge a side-effecting call without a key.

Further Reading

Spotted something wrong or have a production story? Edit this page on GitHub.