Your agent will do it twice
An agent is a distributed systems client that retries, and almost nobody gives it idempotency keys. Adding one to the tool schema does not help: on the retry the model invents a new key, because to the model it is a new attempt.
By Harrison ItotiaNov 23, 20267 min read
An agent books a flight for a customer. It holds the seat, confirms the fare has not moved, and calls charge_card to issue the ticket.
One afternoon it calls charge_card and the connection times out after four seconds. No response comes back. The charge went through perfectly well — the timeout was on the return trip, not the outbound one. But the agent sees an error, concludes the step failed, and calls charge_card again.
Two charges. Two tickets, same passenger, same flight. One very reasonable customer email the next morning.
Nothing in that story is a model failure. The agent reasoned correctly from everything it could see. What was missing is something payments engineers have known about for twenty years, and which almost nobody has added to their agent tools.
Three retries, and none of them knows about the others
When an agent calls a tool, there are usually three independent things that can decide to try again. Most teams have only thought about one of them.
The transport retries. Your HTTP client resends on a timeout or a 5xx. This is on by default in most SDKs and it is the one people do know about.
The framework retries. Your agent runtime catches a tool error and re-issues the call. This is usually a default you never set, in a library you did not write.
The agent retries. This is the new one. The model reads a failure in its context, decides the action did not happen, and calls the tool again. It is not a retry policy. It is reasoning — which means no backoff setting, no max-attempts config and no circuit breaker anywhere in your stack will stop it.
Stack them and a single intent can reach your payment provider three times. Each layer is behaving correctly in isolation. None of them has any idea the others exist.
A tool call is just an RPC
This is an old problem wearing a new costume. The moment you give an agent a function that writes something, you are building a distributed system and the agent is a client — an unusually creative client with a habit of retrying, but a client.
Which means the rule is the one you already follow everywhere else: any operation that can be retried must be safe to run twice. It is the same rule as the one on your background jobs. It is the same rule as the one on your webhook handlers, where you dedupe by event ID inside a transaction. Nobody argues about it there. Somehow the discipline stops at the edge of the agent.
If a tool mutates state, it needs an idempotency key. The agent is not a special case; it is just a client you did not write.
The obvious fix does not work
The first instinct is to add the key to the tool schema and tell the model to reuse it on a retry.
// The trap. It looks right, it type-checks, and it fails exactly
// when you need it.
{
"name": "charge_card",
"parameters": {
"booking": { "type": "string" },
"amount_cents": { "type": "integer" },
"idempotency_key":{ "type": "string",
"description": "A unique key. Reuse it if you are retrying." }
}
}This does not work, and it is worth being precise about why, because the failure is subtle enough to survive a code review.
When the model retries, it generates a new key. Not out of carelessness — from its point of view this genuinely is a new attempt, a fresh tool call in a fresh turn, and a parameter described as "a unique key" should be unique. The model is following your instructions exactly.
So the field exists, it is populated, every call carries one, and the whole mechanism is inert. It protects you against the transport retry, which was never the dangerous one, and does nothing about the agent retry, which is. The schema looks right. The logs look right. You find out when a customer tells you.
Derive the key instead of asking for it
The key should not be an input the model chooses. It should be a fact about the intent, computed in your tool harness from the things that identify the action: which run, which tool, and the meaning of the arguments.
// The key is a fact about the intent, so compute it from the intent.
// The model never sees this field and cannot vary it.
func idempotencyKey(runID, tool string, args ToolArgs) string {
h := sha256.New()
h.Write([]byte(runID))
h.Write([]byte{0})
h.Write([]byte(tool))
h.Write([]byte{0})
// Canonical form, not the raw JSON: typed values, sorted fields,
// money as integer minor units. "2,400.00" and "2400" are the same
// instruction and must not produce two different keys.
h.Write(args.Canonical())
return hex.EncodeToString(h.Sum(nil))
}The important detail is in the comment. Hash the canonical arguments, not the raw JSON the model produced. A model that writes 2400 on the first call and "2,400.00" on the retry has expressed the same instruction twice, and a naive hash of the payload will cheerfully give you two different keys and two different charges. Parse to typed values, sort the fields, and put money in integer minor units before it reaches the hash.
Once the key is derived this way, all three retry layers collapse into one. The transport retry, the framework retry and the agent's own second attempt all produce the same key, and the second and third ones are replays.
Then compaction erases the agent's memory of acting
Here is the failure that catches people who have already done everything above.
Long runs get compacted. The history is summarised to fit the window, and somewhere in that summary charged 2,400.00, receipt r_8f21 becomes "handled the payment", or drops out entirely. The agent re-plans from what remains, cannot see that the charge happened, and acts.
If your only record that the action occurred lives in the context window, you do not have a record. You have a cache that is about to be evicted. The dedup store is the ledger; the context is a convenience.
This is the same class of problem as a failure that looks plausible enough to survive review — nothing errors, nothing alerts, and the system is confidently wrong.
Two agents, one tool
Multi-agent setups add the last twist. Two agents working the same booking will each check whether the fare has been charged, both see "no", and both charge it.
A check followed by a write is not a dedup mechanism. The claim and the side effect have to happen inside one transaction, against a store both agents share.
// Claim and act in one transaction. A check followed by a write is
// two agents charging the same card at the same moment.
func (s *Server) ChargeOnce(ctx context.Context, key string, c Charge) (Receipt, error) {
var r Receipt
_, err := s.spanner.ReadWriteTransaction(ctx,
func(ctx context.Context, txn *spanner.ReadWriteTransaction) error {
if prior, err := readReceipt(ctx, txn, key); err == nil {
r = prior // a replay, not a second charge
return nil
} else if !errors.Is(err, errNoRow) {
return fmt.Errorf("read receipt: %w", err)
}
// Claim the key before the side effect. A crash here loses a
// charge we can detect; the other order double-charges a
// customer, which we cannot take back.
if err := claim(ctx, txn, key); err != nil {
return fmt.Errorf("claim key: %w", err)
}
var err error
if r, err = s.psp.Charge(ctx, c, key); err != nil {
return fmt.Errorf("charge: %w", err)
}
return writeReceipt(ctx, txn, key, r)
})
return r, err
}Note the ordering, because it is a real decision and not a detail. Claiming the key before the side effect means a crash in between loses an action. Acting first means a crash in between repeats one. For money and for messages, claim first — a missing charge is something you can detect and reconcile, and a duplicate charge is something you have to apologise for.
The matching case study is worth reading. A four-agent pipeline looped for eleven days and spent about $47,000 before anyone noticed, and it was a billing dashboard that caught it rather than anything in the system. The postmortem's own summary of the lesson is hard to improve on: "The team had observability. They did not have enforcement."1The $47,000 LangChain A2A infinite loopDetection; root causes (system-level) Open source (opens in a new tab) A dedup check that runs after the call is observability. A claim inside the transaction is enforcement.
What you cannot make idempotent
Some actions have no key to send. An email, a Slack message, a webhook to a partner — the vendor offers you nothing to deduplicate against.
For those, the dedup lives entirely on your side. Derive the key the same way, claim it in your own table first, and only then send. You are not making the vendor's operation idempotent; you are making your decision to call it idempotent, which is the part you control and the part that is actually repeating.
The test
There is a cheap way to find out whether any of this works, and it is the only one worth trusting.
Run the same agent turn twice against the same starting state. Diff the side effects — rows written, charges created, emails queued. If the second run produces anything the first did not, you do not have idempotency. You have a hope.
That diff is a command that exits zero, which means it belongs in CI rather than in someone's memory. It is the same discipline as making "done" a thing a machine can check: a property nobody verifies automatically is a property you do not have.
None of this is about AI
That is the uncomfortable part, and also the useful one.
Every control here — derived keys, a transactional claim, a durable record of what was done, a test that runs the operation twice — is ordinary RPC hygiene. It was written down long before anyone was building agents. The only genuinely new element is the third retry, the one that comes from the model's reasoning rather than from a config file, and it is new mainly because it is invisible to every tool you currently use to control retries.
Agent engineering keeps rediscovering distributed systems one incident at a time. The teams that will ship this safely are not the ones with the best prompts. They are the ones who already know what happens when a write is retried, and who never stopped treating a tool call as what it has been all along.
Sources
- The $47,000 LangChain A2A infinite loop (opens in a new tab)
Detection; root causes (system-level)
Thinking about an agent like this for your team?
Describe the job you want automated and our Automation Architect blueprints it in seconds — or talk it through with the engineers who ship them.
