AI agents retry. The model calls a tool, the request times out, the framework retries, or the model decides to call the same tool again a few steps later because it isn't sure the first call worked. For read-only tools that's harmless. For tools that send an email, create an invoice or charge a card, it means doing the thing twice.
The fix is old and boring: idempotency keys. Here's how to apply them to agent tool calls.
The problem in one example
Say your agent has a send_invoice tool. The agent calls it, your server sends the invoice, but the response is slow and the agent's HTTP client times out. From the agent's point of view, the call failed, so it tries again. The customer now has two invoices.
You can't fully prevent retries. Networks fail and models repeat themselves. What you can do is make repeated calls safe.
The idea
Every side-effecting action gets a key that identifies the intent, not the attempt. If the same key shows up again, you return the stored result instead of doing the work a second time.
The key should be built from things that define "the same action", for example the customer ID, the invoice period and the action type. Don't let the model invent the key. Build it in your own code from the tool's arguments, so two retries of the same intent always produce the same key.
A minimal implementation
import hashlib
import json
import sqlite3
db = sqlite3.connect("actions.db")
db.execute(
"CREATE TABLE IF NOT EXISTS actions ("
"key TEXT PRIMARY KEY, status TEXT, result TEXT)"
)
def make_key(action: str, **fields) -> str:
payload = json.dumps({"action": action, **fields}, sort_keys=True)
return hashlib.sha256(payload.encode()).hexdigest()
def run_once(key: str, fn):
# Try to claim the key. If it already exists, someone ran this before.
try:
db.execute("INSERT INTO actions (key, status) VALUES (?, 'pending')", (key,))
db.commit()
except sqlite3.IntegrityError:
row = db.execute(
"SELECT status, result FROM actions WHERE key = ?", (key,)
).fetchone()
if row[0] == "done":
return {**json.loads(row[1]), "already_done": True}
raise RuntimeError("action already in progress, try again later")
result = fn()
db.execute(
"UPDATE actions SET status = 'done', result = ? WHERE key = ?",
(json.dumps(result), key),
)
db.commit()
return result
def send_invoice_tool(customer_id: str, period: str, amount: float) -> dict:
key = make_key("send_invoice", customer_id=customer_id, period=period)
return run_once(key, lambda: actually_send_invoice(customer_id, period, amount))
The agent can call send_invoice_tool as many times as it likes for the same customer and period. Only the first call sends anything. Later calls get the original result back with already_done: True, which tells the model "this already happened" so it can move on.
A few details that matter
Pick the key fields carefully. Leave out anything that can vary between retries but doesn't change the intent, like timestamps or the model's wording of a note. Include everything that does change the intent. Here amount is left out on purpose, so a retry with a slightly different amount doesn't send a second invoice for the same period.
Handle the "pending" case. If a call crashes halfway, the key stays pending. Decide what that means for your system. Often the right answer is to flag it for a person instead of guessing whether the action went through.
Use the provider's keys when they exist. Many payment and email APIs accept an idempotency key on their side too. Pass yours through, so you're protected even if your own database write fails after the external call succeeds.
Tell the model. That's what the already_done flag is for. Models handle a clear "this was done already" much better than a generic error, and they're less likely to keep retrying.
Wrapping up
Agents make retries more common, not less. Treat every tool that changes something in the real world like a payment endpoint: give each intent a key, record the result, and make the second call a no-op. It's a small amount of code, and it removes a whole class of "why did the customer get this twice" problems.
I write about building reliable AI agents at Binate AI.
Top comments (0)