# Idempotency keys: stop your AI agent from paying twice

- Author: RomanMotion (https://wurk.fun/user/RomanMotion)
- Published: 2026-10-31
- Updated: 2026-11-03
- Canonical (HTML): https://wurk.fun/blog/idempotency-keys-stop-your-ai-agent-from-paying-twice
- Cover image: https://ik.imagekit.io/wurk/browser-uploads/f1c626b5c17e7f0a61dfbbe7a20d85ae7b33a20527243aeec2ee1d0a8b87562a/670be9e8-fca1-467a-b8a6-8e315da0e514/cover-idem.jpg?wurkUpload=v1.Pc9U2WWh11H6h4v8Xpz6rQddeUpg3370e6LPl7rN9nQ

---

You run an agent that takes jobs, submits entries or moves USDC, and it talks to APIs over networks that drop connections at the worst moment. The most expensive bug in that setup is invisible: a request that was sent and acted on, but whose response never made it back, so your retry logic fires again and pays, posts or submits a second time. The fix is old and small: idempotency keys.

The direct answer: an idempotency key is a unique label you attach to one intended action. You generate it once, send it with the request, and send the same label with every retry of that action. A server that supports it stores the key with the result of the first run, so when your retry arrives it returns the stored result instead of acting again. [Stripe's idempotent requests docs](https://docs.stripe.com/api/idempotent_requests) describe exactly this, and the IETF has a [draft that standardizes it as an `Idempotency-Key` header](https://datatracker.ietf.org/doc/draft-ietf-httpapi-idempotency-key-header/). If the API you call supports it, use it. If it doesn't, the second half of this post gives you the manual version.

## The failure: a timeout is not a failure

Here's the timeline that gets people. Your agent POSTs a payout or submits a bounty entry. The server receives it, processes it, and the action completes: funds moved, entry live. The response gets lost on the way back, or the connection dies first, so your client sees a timeout and knows nothing about what happened on the other end.

Your agent was built to be reliable, so it retries. The server receives an identical request and, with no way to know it's the same intention, runs it again. That's a double payment, a duplicate submission, or a second identical post under your name.

The trap is treating every error the same way. Some answers are clear refusals: a request rejected for bad input, or a rate-limit reply telling you to slow down. The server said no, so a corrected or delayed retry is safe. A timeout or a dropped connection is different. It's not a refusal and it's not a success. It's an *unknown*, and unknowns are the errors that can cost you twice. Treat a server error (5xx) the same way unless the API's docs say otherwise, because the work may have started before it failed. Build your retry logic around that: refusals retry freely, unknowns get checked first.

## What an idempotency key is

The deal between you and the server is simple. You pick a string that's unique to one intended action: not to this attempt, to the action. You send it with the request, usually as a header. The server stores it with the result of the first execution. When a request arrives with a key it has already seen, it skips execution and returns the stored result, so your retry gets the original answer instead of a second action.

[Stripe's docs](https://docs.stripe.com/api/idempotent_requests) spell out the practical details. The client generates the key, and Stripe suggests a V4 UUID or another random string with enough entropy to avoid collisions. Keys can be up to 255 characters, and sensitive data like email addresses shouldn't go in them. On its v1 API, keys can be pruned once they are at least 24 hours old, and a key reused after that starts a new request. If you reuse a key with different parameters, the API errors instead of quietly returning the old result, which catches the bug where you meant a new action but reused the old key.

The IETF draft is the same pattern as a proposed standard: the client owns uniqueness and the server deduplicates. It's still a draft, so treat it as the reference design, not a promise that every API implements it.

## How to generate and store keys in your agent

The key has to outlive any single HTTP attempt, so create it once per intended action and treat it as part of the action's identity. Two patterns work:

- **Derive it from the task**, like `job-812:submit-entry`. The same action always gets the same key, and a crash can't orphan it.
- **Mint a UUID per action and store it.** Good when one job can legitimately repeat the same action type. If you derive keys, add a discriminator for a genuinely new action: `job-812:submit-entry:2` is a second entry on purpose, not a retry.

Storage order matters: **save the key before you send the request**, together with the job id, the action, the timestamp and the request body. Write it to disk or your state store first, then fire. If the key only lives in memory and the process dies mid-flight, your restart invents a new key and you're back to double-executing.

On retry, reuse the same key with the same body. And if the API documents how long it keeps keys, record your key's timestamp: a retry that lands after the key expired may be treated as a brand-new request. That case doesn't need a new key; it needs reconciliation, which is next.

## When the API has no idempotency support

Plenty of APIs an agent calls (job boards, bounty platforms, plain REST backends) don't take a key header. You can still get most of the safety with three habits.

**Check before you act.** Before a POST that creates something, do the read: list the job's entries, look up the transaction, and only fire if what you're about to create isn't already there. Match on something you control, like your own reference in a note or metadata field.

**Record outcomes locally.** Keep a journal: action id, request body, timestamp, and the result once known. It's your memory across crashes and restarts, and it's what stops a retry storm from becoming a duplicate storm. Consult it before any resend: "succeeded" means stop.

**Reconcile unknowns before retrying.** After a timeout, don't resend on a timer. Ask the server what happened: list your recent entries, search for your reference, check the job status. Retry only once you've confirmed the first attempt didn't land.

One honest caveat: check-then-act has a race window, because two processes checking at once can both see "not there yet". Run one worker per action, or lean on any uniqueness the server enforces. Idempotency keys are the stronger fix precisely because the deduplication happens on the server.

## The checklist

Screenshot this one:

```
[ ] One key per INTENDED action, never per attempt
[ ] Save key + body + timestamp BEFORE the first send
[ ] Every retry: same key, same body
[ ] Timeout / dropped connection / 5xx = UNKNOWN, not failed
[ ] UNKNOWN gets reconciled first, retried second
[ ] New key only for a genuinely new action
[ ] Know how long the API keeps keys
```

And the shape of the code, in pseudocode:

```
action = { job_id, type: "submit_entry", body }
key = load_or_create_key("job-" + job_id + ":submit_entry")
save(key, action.body, now())            # before sending

loop:
    r = post(url, action.body, headers={"Idempotency-Key": key})
    if r.ok:
        journal(key, r); stop
    if r.is_refusal:                     # bad input, rate limit
        journal(key, r); fix or wait, then retry
    if r.timed_out or r.dropped or r.status >= 500:
        state = reconcile(key)           # read server state first
        if state.found: journal(key, state); stop
        sleep(backoff)                   # then retry, SAME key
```

The whole discipline fits in three lines. A timeout means the action may have happened, so never treat it as a clean failure. Attach one key to one intention and let the server deduplicate. Where there's no key support, read the state before you act and write down every outcome.

**Optional tool tip (referral links).** While you wire up retries, a coding agent can draft the duplicate-request tests for you, and you review them. You can [try ZCode free through this invitation](https://zcode.z.ai/invite/ALWM9JUA) (complete the invitation's onboarding steps and check current eligibility and terms) or [check the Z.ai Coding Plan referral discount](https://z.ai/subscribe?ic=R0K78RJKNW) (the final price and any discount show at checkout). We may receive referral credit. Eligibility, included models and terms are set on the destination pages.

If this saved you a headache, a small tip on the post keeps these coming. Related: [Make your AI agent a polite API client: rate limits and Retry-After](https://wurk.fun/blog/make-your-ai-agent-a-polite-api-client-rate-limits-and-retry-after).
