Skip to content
Hands-on6 min readPublished 2026-11-30Reviewed 2027-11-30

Four retries, four refunds: where the idempotency key belongs, and why it still leaks ​

Environment: Python 3.12.11, standard library http.server and http.client, loopback only. The server is deliberately built as the worst case — commit the side effect first, then answer slowly — which models "the money is already out and the response got lost on the way back". The client retries serially, four attempts maximum. Checked on 2026-11-30.

The most expensive class of bug in tool calling is not in the model. It is here: the model calls refund once, the gateway times out, the framework retries on "failure", and four refunds go out. Every line in the log says the request failed.

Twelve configurations, and duplication is deterministic ​

The server appends a record every time it actually executes. The client retries on timeout, up to four attempts:

Client timeoutServer workNo idempotency key: attempts / side effectsWith key: attempts / side effectsClient outcome
1.0s0.5s1 / 11 / 1success
1.0s1.5s4 / 42 / 1no key: gives up; with key: success
1.0s2.5s4 / 42 / 1no key: gives up; with key: success
2.0s0.5s1 / 11 / 1success
2.0s1.5s1 / 11 / 1success
2.0s2.5s4 / 42 / 1no key: gives up; with key: success

Three things are visible at once.

One: the number of duplicates equals the number of attempts, not a probability. As long as server work consistently exceeds the client timeout, every attempt executes the whole operation. Four attempts, four side effects, no luck involved. The only way to duplicate less is to retry less.

Two: "the client thinks it failed" and "the server already did it" are separate facts. In both rows with a 1-second timeout (1.5s and 2.5s of server work), the client gave up after 4.21 seconds and reported an error while the server already held four records. What the product side sees is "refund failed, please retry" — and one tap from the user sends four more.

Three: the idempotency key turns "retry until you give up" into "succeed on the second attempt". In all four keyed rows, the second request hits the first result and returns the same refund_id, with side effects still at 1. The first side effect was committed long before; all that was missing was a key to find it again.

Which layer holds the key: the call, not the arguments ​

The tempting place for an idempotency key is a hash of the arguments — hash {amount, user_id} and use that. That merges two genuinely separate refunds into one, which is its own incident.

The right place is this tool call itself: the call_id the model emitted, or a UUID your application mints for this intent. However many times the same call_id is replayed, it should produce exactly one side effect. This lines up with the structure of function calling: the call_id is supplied by the model and unique within the turn, which makes it a natural carrier for the key.

One easily confused point: schema compliance is not business safety. The official docs are explicit that strict mode constrains "completed, non-refusal" output to your JSON Schema, and that your application still needs to handle refusals, incomplete responses and API errors, and validate any business rules the schema does not express. "Has this refund already been executed" is exactly such a rule.

A key can still leak: the check and the write must be atomic ​

Now add concurrency. Ten threads replay the same call_id at once, with a 50 ms round-trip window between "is the key present" and "write the side effect" — in real systems those two steps are usually a cache lookup and a database write:

ImplementationSide effects across 5 roundsDistinct refund_ids
Check then write (not atomic)9 / 10 / 10 / 10 / 89 / 10 / 10 / 10 / 8
Check and write under one lock (atomic)1 / 1 / 1 / 1 / 11 / 1 / 1 / 1 / 1

The non-atomic version pays out 8 to 10 refunds under ten concurrent replays. This is not sloppy coding; it is the window that necessarily exists between two steps: every request sees "absent", then every request writes. Closing it does not come from checking once more — it comes from letting the store enforce uniqueness at write time: a unique index, a conditional write (INSERT ... WHERE NOT EXISTS), or an atomic create guarded by If-None-Match. Check-then-write is an optimization, not a guarantee.

What the spec says ​

RFC 9110 is clear about intent: a method is idempotent when the intended effect of multiple identical requests is the same as that of a single one. And then:

A client SHOULD NOT automatically retry a request with a non-idempotent method unless it has some means to know that the request semantics are actually idempotent, regardless of the method, or some means to detect that the original request was never applied.

In engineering terms: for something like POST, either you can show it is idempotent or you can confirm it never ran — otherwise do not retry automatically. The spec adds two firmer rules: a proxy MUST NOT automatically retry non-idempotent requests, and a client SHOULD NOT automatically retry a failed automatic retry.

That last one is exactly what many frameworks do by default — exponential backoff, four attempts — which is precisely where the four side effects in the table come from.

When a human has to take over ​

Not every write deserves an idempotency key. Three criteria; hitting any one of them means stopping and waiting for confirmation:

  1. Irreversible with a countable impact: refunds, transfers, voucher issuance, SMS. One duplicate converts directly into money or a complaint.
  2. A side effect in an external system that offers no idempotent endpoint: placing an order, issuing an invoice, changing an address. You cannot know whether the other side executed it, so the only option is not to retry and route it to a human.
  3. The retry has already failed twice. The spec's "do not retry a failed retry" is the basis — the expected value of a third attempt is far below the risk of a duplicate execution.

In product terms, the hand-off entry point must carry the full context: call_id, arguments, attempts made, and the raw error from the last attempt. Without the call_id, even a support agent cannot tell whether the operation ran.

Reproducing it ​

  1. Start a ThreadingHTTPServer with POST /refund: append a side-effect record, sleep(server work), then return 200.
  2. Use http.client on the client with a 1-second or 2-second timeout, retrying serially up to four times.
  3. Run the 2×3 matrix with and without an Idempotency-Key header, recording "requests received" and "side effects written".
  4. Concurrent version: ten threads hitting the same key at once, a 50 ms delay between check and write, comparing locked against unlocked.

The whole thing is under 80 lines and finishes in about 30 seconds locally. It is worth putting straight into CI — it needs no real model and no real payment gateway.

OpenAIChat · Full-stack engineering for LLM-powered conversations and apps