Practical engineering · December 2, 2026
How to Stop an AI Agent From Duplicating Actions After a Timeout
Give each authorized intention one stable idempotency key, store the side effect and its receipt in the same transaction, and make every retry look up that receipt before doing anything. A timeout only tells the agent that it did not hear back; the tool may already have committed.
If the agent retries with a fresh key, or with no key at all, the tool cannot tell a retry from a new request and applies the action again: a second refund, a second email, a second ticket. The fix lives at the boundary between the agent and the tool, not in the prompt.
Why the retry applies the action twice
Picture the sequence. The agent calls issue_credit for $10. The tool writes the credit, then the connection drops before the response reaches the agent. From the agent's side this is indistinguishable from a tool that never ran, so the framework retries. Without a way to recognize the second call, the tool writes another $10.
The transcript afterwards looks clean: one timeout, one success. The account is wrong. That gap between what the log says and what the system did is why duplicate actions are hard to spot in review.
Key the intention, not the attempt
The key has to identify what was authorized, so every retry of that decision carries the same value. Generating a new UUID inside the retry loop defeats the purpose. Build it from facts that define the action, for example the action name, the customer and the incident the agent was asked to resolve, and create it once, before the first attempt.
Stripe's API documentation describes the same contract: the client generates the key and the server uses it to recognize later retries of the same request. It also advises against putting sensitive data such as email addresses into keys, so prefer internal identifiers.
Store the effect and the receipt together
The tool must record "this key already produced this result" in the same transaction as the side effect. If the receipt is written separately, a crash between the two writes brings the duplicate back. This version uses only the Python standard library and SQLite:
import hashlib, json, sqlite3
class ConflictingRetry(Exception):
pass
def intention_key(customer_id, incident_id, action):
# One authorized intention -> one key. Never a new random key per attempt.
return f"{action}:{customer_id}:{incident_id}"
def fingerprint(payload):
return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest()
def setup(db):
db.execute("CREATE TABLE IF NOT EXISTS credits (id INTEGER PRIMARY KEY, customer TEXT, cents INTEGER)")
db.execute("CREATE TABLE IF NOT EXISTS receipts (key TEXT PRIMARY KEY, fingerprint TEXT, credit_id INTEGER)")
def issue_credit(db, key, payload):
fp = fingerprint(payload)
with db: # effect and receipt commit together, or not at all
row = db.execute("SELECT fingerprint, credit_id FROM receipts WHERE key = ?", (key,)).fetchone()
if row:
if row[0] != fp:
raise ConflictingRetry(f"key {key} was already used with a different payload")
return {"credit_id": row[1], "replayed": True}
cur = db.execute("INSERT INTO credits (customer, cents) VALUES (?, ?)",
(payload["customer"], payload["cents"]))
db.execute("INSERT INTO receipts (key, fingerprint, credit_id) VALUES (?, ?, ?)",
(key, fp, cur.lastrowid))
return {"credit_id": cur.lastrowid, "replayed": False}
db = sqlite3.connect(":memory:")
setup(db)
key = intention_key("customer-42", "incident-7", "credit")
payload = {"customer": "customer-42", "cents": 1000}
first = issue_credit(db, key, payload) # commits; imagine the response is lost here
retry = issue_credit(db, key, payload) # the agent retries after the timeout
print(first, retry, db.execute("SELECT SUM(cents) FROM credits").fetchone()[0])
Running it prints {'credit_id': 1, 'replayed': False} {'credit_id': 1, 'replayed': True} 1000: one credit, and the retry gets the original receipt back.
Reject a different payload under the same key
Sometimes the retry is not identical. The model regenerates the arguments and asks for $15 instead of $10 under the same key. The safe answer is to refuse, not to apply the new amount and not to mint a new key automatically. In the code above the fingerprint check raises ConflictingRetry. The IETF draft for the Idempotency-Key HTTP header models the same case: a key must not be reused across different payloads of an operation, and the draft includes an error response for it.
When the tool is a remote API
A local transaction covers a tool that writes to your own database. It does not give exactly-once behavior across a third-party provider and your database. For remote writes, pass your key to the provider's idempotency mechanism when it has one. Stripe, for instance, accepts an Idempotency-Key header on POST requests and returns the saved result of the first request for later retries with the same key. Its documentation also notes that keys can be removed once they are at least 24 hours old, so a retry that arrives much later needs a lookup or a reconciliation step instead of a blind resend.
Two limits belong in the same design. Cap the number of attempts and the total elapsed time, and give the transport a timeout that fits the remaining budget, because a deadline check before the call cannot interrupt a request that is already blocked.
A checklist for your agent's write tools
- Every tool with a side effect accepts an idempotency key and refuses to run without one.
- The key is derived from the authorized intention and created before the first attempt.
- The side effect and the receipt are committed in one transaction.
- A repeated key with the same payload returns the stored receipt; with a different payload it is rejected.
- Remote calls forward the key to the provider, and uncertain outcomes go to reconciliation.
- Retries have a maximum count and a total deadline.
FAQ
Can I just tell the model not to retry?
No. Retries often come from the framework, the HTTP client or a job queue, not from the model. The tool has to be safe to call twice.
Should the agent generate the idempotency key?
Generate it in deterministic code from the approved action, not in the model's output. A model asked to repeat a key can change it between attempts.
Does this make the action exactly-once?
Inside one database transaction, a repeated delivery is applied once. Across a remote provider and your database you need the provider's idempotency support or a reconciliation step.
What about reads?
Reads have no side effect to duplicate. Stripe's documentation says the same about its GET and DELETE requests: they are idempotent by definition, so sending a key there has no effect.
This topic is part of AI Agent Reliability Engineering, a book I am writing around executable failures and verified corrections. The book is not yet released. The free lab reproduces this incident in Python with regression tests.
Harness Engineering for AI Coding Agents: build reliable Claude Code, Codex and Python agent workflows with guardrails, tests, CI gates and production controls.
Pydantic AI in Production: building robust LLM agents for enterprise.
See Harness Engineering for AI Coding AgentsSources
- Stripe API reference: Idempotent requests
- Stripe docs: Advanced error handling
- IETF draft: The Idempotency-Key HTTP Header Field
- Why Retries Create Duplicate Agent Actions (the incident this simulator reproduces)