Says what the reader will do, plus the limit
Our idempotency key was built from the tool call ID. New retry, new key, second refund.

Our support agent refunded 9 customers twice in 14 minutes, and every refund call had an idempotency key.
The payments API slowed down on a Friday evening. No deploy, no prompt change. A refund call timed out; the customer asked, "Did my refund go through?" and the agent called the refund tool again.
That second call got a new tool call ID. We had built the key from the tool call ID. New ID, new key, and the provider saw a brand-new request.
The key was there. It just identified the wrong thing.
TL;DR
- Agents retry from at least four layers: the model, the framework, the HTTP client, and the user. Stacked, one refund can become up to 18 calls.
- For a tool with side effects, an error means "unknown", not "failed".
- One idempotency key = one business intent (never one tool call or one attempt).
- Wrap every side-effecting tool: record the intent, lock it, call with the key, and check the provider before acting again.
- Return
done,already_doneorpending_unknownto the model, never a bareError: timeout. - Make duplicate side effects a hard fail in your eval gate, and reconcile against the provider every hour.
Part 2 of Shipping AI Agents to Production. Part 1 covered eval gates, smoke evals and the bad-day runbook, after one prompt line ("If a tool call fails, retry once") refunded 212 customers twice.
The first principle
A retry is only safe when the second attempt can be recognised as the same attempt.
Everything below is a way to make that true for every layer that might retry.
Why the default fix fails
After Part 1 we did the textbook thing: we added an idempotency key to every refund call. The tutorial version builds the key from whatever ID is lying around, and in an agent, that is the tool call ID.
That works for exactly one layer, the HTTP client, because it resends the same request. It fails for every layer above it, because each of those creates a new tool call.
- The model. A prompt line, or the model's own judgement, calls the tool again after an error.
- The agent framework. LangGraph, for example, lets you add a
RetryPolicyto a node. If you do, it defaults to 3 attempts and retries most exceptions. - The HTTP client. Many clients and SDKs retry timeouts and 5xx errors on their own.
- The user. "Did it go through?" is a retry. So is pressing the button again.
A model that retries once, a framework that tries 3 times and a client that tries 3 times can turn one refund request into up to 18 calls, before the customer has even asked again.
You won't remove every retry, and you shouldn't. The goal is that every retry, from any layer, lands on the same answer.
The five failure shapes
In 1987, Leslie Lamport described a distributed system as "one in which the failure of a computer you didn't even know existed can render your own computer unusable." An agent with tools is a distributed system, and the computers you don't control fail in specific shapes:
| Failure shape | What the agent sees | What actually happened |
|---|---|---|
| Slow success | Timeout | Done |
| Lost response | Network error | Done |
| Error after commit | 500 | Maybe done |
| Partial failure | Error | Half done (refund created, DB update or email failed) |
| Duplicate delivery | Success, twice | Done twice |
In four of the five rows, "error" does not mean "didn't happen". That is the core rule:
For a tool with side effects, an error means "unknown", not "failed".
Step 1: Classify every tool
Not every tool needs this machinery. Put each tool in one of three groups and store it as a field on the tool definition (effect: read | idempotent | side_effect):
- Read-only:
get_order,check_refund_status,search_faq. Retry freely. - Idempotent by nature:
set_ticket_status("resolved"),update_address. Retry with the same arguments. - Side-effecting:
refund_order,charge_card,send_email,create_ticket. Never retry blindly.
In our support agent, 9 of 14 tools were read-only, 2 were idempotent and 3 had side effects. The wrapper reads the field and applies the policy, so nobody has to remember which tools are dangerous.
Step 2: One key per business intent
Stripe's API is a good reference. Its docs say that with an Idempotency-Key header, "you can safely repeat the request without risk of creating a second object or performing the update twice." The details that matter for agents:
- Stripe saves the status code and response of the first request for a key and replays it for later requests with that key, including 500 errors.
- Reusing a key with different parameters returns an error. That's a useful safety net when an agent retries with a different amount.
- Keys can be removed after they're at least 24 hours old. After that, the same key can create a new request.
- Don't put sensitive data, like email addresses, in keys.
The key must mean one business intent: "refund $49.00 for order 8812". Derive it from the intent (refund:order_8812:49.00) or generate a random UUID once and store it with the intent. Either works, as long as it's created once per intent and never once per attempt.
Step 3: Wrap every side-effecting tool.
Every tool call goes through one wrapper that owns timeouts, retries and keys. For side-effecting tools, it follows six steps:
- Look up the intent. Already completed? Return
already_donewith the original refund ID and don't call the provider. This is what makes "did it go through?" safe. - Record the intent as
pending, with its key, before the request leaves your system. - Lock the intent. A concurrent call for the same intent waits, then reads the result.
- Call the provider with the key and a real timeout. Set it from the real API's p99. Part 1's mock answered in 50 ms; the real API's p95 was 4.8 seconds.
- On timeout or error, check before you act. Ask the provider whether the refund exists. If it does, mark the intent
done. - Still unclear? Stop. Mark it
pending_unknownand hand it to reconciliation. Don't retry, and don't guess.
Here is a Python-style sketch and intents stand-in for your payment client and your intent table:
def refund_order(order_id: str, amount: Decimal) -> dict:
# One key per business intent: created once, reused on every attempt
intent = intents.get_or_create(
kind="refund",
order_id=order_id,
amount=amount,
key=f"refund:{order_id}:{amount}",
)
if intent.status == "done":
return already_done(intent)
with intents.lock(intent.key): # concurrent calls for this intent wait here
intent.refresh()
if intent.status == "done":
return already_done(intent)
try:
refund = payments.refund(
order_id=order_id,
amount=amount,
idempotency_key=intent.key,
timeout=10, # from the real API's p99, not the mock's
)
intents.mark_done(intent, refund.id)
return {"status": "done", "refund_id": refund.id}
except (Timeout, ServerError):
# An error means "unknown", not "failed". Check before acting.
existing = payments.find_refund(order_id=order_id, amount=amount)
if existing:
intents.mark_done(intent, existing.id)
return {"status": "done", "refund_id": existing.id}
intents.mark_pending_unknown(intent)
return {
"status": "pending_unknown",
"message": "Refund may have gone through. Do not call refund_order "
"again for this order. Tell the customer it is being confirmed.",
}
def already_done(intent) -> dict:
return {
"status": "already_done",
"refund_id": intent.refund_id,
"message": "This refund was completed earlier. Tell the customer it went through.",
}
Bounded retries with the same key are still fine for errors that clearly happened before anything was processed, like a validation error or a rate limit. A new key for the same intent never is.
Step 4: Tell the model what happened
When a tool returns Error: timeout, the model has to guess, and a helpful model guesses "try again". So side-effecting tools return one of three statuses, each with a short instruction:
done: The refund was created. Here's the ID.already_done: completed earlier. Tell the customer it went through.pending_unknown: It may have gone through. Don't call this tool again for this order. Tell the customer it's being confirmed.
Two more changes go with it:
- Rewrite the prompt rule. "If a tool call fails, retry once" becomes "Never call
refund_ordermore than once for the same order. If it returnspending_unknown, tell the customer the refund is being confirmed." - Say it in the tool description. "Safe to call once per order. Repeated calls return the original result." The model reads tool descriptions as instructions.
The wrapper makes retries safe. The statuses make them unnecessary.
Step 5: Test the failure shapes on purpose.
Mocks never time out, so your tests have to.
- Inject faults below the wrapper. A fake payments server or fault-injecting proxy that can delay, drop the response after committing, return a 500 after committing, or deliver twice.
- Cover every shape from every entry point:
| First call | Customer re-asks | Two calls at once | |
|---|---|---|---|
| Slow success | 1 refund | 1 refund | 1 refund |
| Lost response | 1 refund | 1 refund | 1 refund |
| Error after commit | 1 refund | 1 refund | 1 refund |
| Partial failure | 1 refund | 1 refund | 1 refund |
| Duplicate delivery | 1 refund | 1 refund | 1 refund |
- That's 15 new eval cases, added to the 400 from Part 1.
- Make duplicates a hard fail. In Part 1, duplicate calls were counted inside the 98% tool-call threshold. That was a mistake. Duplicate side effects now sit next to policy violations: threshold 0, one duplicate fails the gate.
- Use the provider's sandbox. Stripe's test mode, nightly and before releases.
- Add a re-ask case to the smoke eval. Request a refund, ask "did it go through?", and assert exactly one refund exists. This single case would have caught our second incident.
One honest limit: a smoke eval only checks the environment when you deploy. Our incident happened with no deploy at all. Between releases, protection has to live in the tool layer.
Failure modes of this design
The wrapper is not magic. Three things will still bite:
- Key expiry. Stripe keys can be removed after 24 hours. A retry that arrives a day later is only stopped by step 1 (your own intent table) and step 5 (the provider check), not by the key.
- Partial failure. The refund succeeds, but your DB update or customer email fails. The intent table must be the source of truth, and the email must be its own idempotent step.
- Stuck intents. Some refunds will sit in
pending_unknown, and on a bad day a duplicate may still get through.
That last one is why you reconcile. Every hour, compare your intent table with the provider's records:
- Matched: one intent, one refund. Nothing to do.
- Duplicate: one intent, two refunds. Page on-call, open a finance ticket.
- Orphan: a refund with no intent, or
pending_unknownfor more than 30 minutes. Resolve by hand and update the customer.
When a duplicate shows up: flip a flag that disables refund_order and routes refunds to human support, take the blast radius from reconciliation, let finance recover the money and support message the customers, then add the exact shape as a new eval case.
On our second bad day, the duplicate-call alert fired at 14 minutes, the refund tool was off at 16, and reconciliation had confirmed all 9 duplicates within the hour. Compare that with 212 customers and a manual rebuild in Part 1.
What to keep, what to drop
Decision rule: keep the full wrapper only for tools whose second call does a second thing. Read-only and naturally idempotent tools get plain retries. Spend the complexity where a duplicate costs money or trust.
Checklist
Design
- Every tool is classified as read-only, idempotent or side-effecting
- Keys are created once per business intent, never per attempt or tool call
- Intents are recorded before the request goes out
- Timeouts come from the real API's latency, not the mock's
What the model sees
- Side-effecting tools return
done,already_doneorpending_unknown - No prompt line tells the model to retry a side-effecting tool
- Tool descriptions say "safe to call once"
Testing
- All 5 failure shapes are injected below the wrapper, from all 3 entry points
- Duplicate side effects = 0 is a hard fail in the eval gate
- The smoke eval includes a "did it go through?" case
Bad day
- Reconciliation runs hourly and routes duplicates to an owner
- A flag can disable one side-effecting tool without stopping the agent
- Finance and support know their part before an incident
The rule
A retry is only safe when the second attempt is recognized as the same attempt. For a tool with side effects, an error means "unknown", not "failed".
Get those two right, and it stops mattering how many layers decide to retry.
Which of your tools would refund, charge or email twice if the response got lost today? Tell me in the comments.
About the author
- AI Developer at Genpact, previously a backend engineer building high-volume systems for Shutterfly. I build production RAG and AI agent systems with a focus on security, grounding, and reliability. My current project, GroundedDocs, is a document Q&A service that answers only with exact citations or abstains. Here I write the "Grounded RAG in Production" series: practical design notes from shipping real systems.
Comments
Join the discussionNo comments yet. Be the first to comment.
AI Engineering in Production
Production RAG and agent systems that have to stay up: auth, retrieval, agents with brakes, evaluation and observability. Every post comes from a system I actually built and measured, and I only keep the complicated piece when a simpler one loses on a real metric.




