Setup

Idempotency keys for paid APIs: never pay twice

How an idempotency key stops a retry from charging you twice on a paid API, how to build one, and how to cap the cost of a call when a retry goes wrong.

Luisa · · 8 min read

On this page

An idempotency key is a unique value you send with a request so that the server can recognise a retry and return the first result instead of doing the work again. Most guides explain this with payments, where a retry could charge a card twice, but the same risk applies whenever you pay per API call. If your process times out after a paid lookup and simply tries again, you pay for the same answer twice, and a batch job that restarts can do that across thousands of rows before anyone notices.

By the end you will know how to build a key that holds up, what to do with each kind of answer when you retry, and how to limit what a single call can cost. The examples use looot, where every run takes a key, but the same thinking works on any paid API that supports one.

Why do paid APIs need idempotency keys?

POST requests are not idempotent by default. MDN's definition calls a method idempotent when sending it several times has the same effect as sending it once, and says POST is not guaranteed to be. A paid lookup is usually a POST, so an idempotent API has to add that guarantee itself, and the key is how it does it.

Stripe's model is the one most people learn first. Its idempotent requests reference says that for API v1 it saves the status code and body of the first request under a key and returns them to every retry, and that it errors when the same key arrives with different parameters. On a payment API a missing key risks a second charge on a customer's card. On a data API it means a second bill from a provider for an answer you already have.

What makes a good idempotency key?

A good key identifies the piece of work and not the attempt, so it should come from your own data. Something like `lead-4821-email` works well, because a retry after a crash builds the same key from the same record and finds the first run. Use your record's id rather than the person's email address. Stripe's reference also advises against putting personal data in keys.

A random value works only if you create it once and store it with the record before the first attempt. A UUID from a UUID generator is fine for that. A new UUID made inside the retry loop gives you no protection at all, since every attempt then looks like a new request to the server.

The key should also change when the work really is new. If you refresh the same lead's email next quarter and want a fresh answer, add the period to the key, as in `lead-4821-email-2027q1`, because reusing the old key would only bring back the old result.

What happens when you send the same idempotency key again?

The server compares the new request with the one it stored under that key. On looot, the same key with the same input returns the first run, marked `replayed: true`, with no second charge, even if the first run is still in flight. The same key with a different input is refused with a 409 `idempotency_conflict`, so a bug that reuses a key across two records gives you an error instead of the wrong person's data.

Copy bash code
curl -s -X POST "https://api.looot.ai/v1/runs?wait=20" \
  -H "Authorization: Bearer $LOOOT_TOKEN" \
  -H "content-type: application/json" \
  -d '{"endpointId":"job:people.email.find",
       "input":{"first_name":"Jane","last_name":"Doe","domain":"example.com"},
       "idempotencyKey":"lead-4821-email",
       "fallback":{"maxAttempts":3,"maxCostUsd":0.10}}'

When should you retry, and with which key?

The right move depends on whether the run started. Some requests are refused before the run starts, and those hold no key and cost nothing, so you send them again with the same key once the cause is gone. That covers a balance that was too low, a spend limit, and the 429 and 503 responses to `POST /v1/runs`, which carry a `Retry-After` header with the seconds to wait. A timeout or a lost connection means you do not know what happened, so you also retry with the same key and let the replay tell you.

Once a run has started, its key belongs to that run, and the same key returns it as it is. On looot you read the run's `outcome` field, which is judged from the data in the answer rather than from a status code. A miss means the lookup worked and found nothing, so the same key only returns the same miss. A new key asks a provider again, which can cost money if the provider bills for misses, so store the miss and move on unless your input has changed. For a bad input, fix it and use a new key, because a changed input under the old key gets the 409.

What came backRetry?Which key
Refused before start: balance too low or over a spend limitYes, once you top up or raise the limitThe same key
429 or 503 on `POST /v1/runs`Yes, after the `Retry-After` secondsThe same key
Timeout or lost connectionYesThe same key
`outcome: "hit"`No, save itNone
`outcome: "error"` with `retryable: true`YesA new key, because the same key returns the same failed run
`outcome: "miss"`Only with better inputA new key
409 `idempotency_conflict`Fix the bug in your keysA new key

How do you cap what a call can cost?

A key protects you from paying twice for one call, but it does nothing about a single call that costs more than you expected, which is the job of a cap. With provider fallback on, one run can try several providers, so you set `maxCostUsd` for the whole route and `maxAttempts` for the number of providers. looot skips any provider that would push the run past the cap and charges only for the attempts that ran. Each attempt in the run's `route` block shows `billed` and `chargedUsd`, so you can see where the money went.

Prices differ a lot between providers of the same job, so it helps to see them before you choose a cap. What 1,000 lookups cost shows how that adds up, and the work email finder page lists the providers for this job with their live prices.

How do you avoid paying again later?

An idempotency key covers retries of one request, not the same question asked again next week by another part of your system, so keep the answers you paid for. Save each result in your own database along with its cost and the date, and check there before you call. looot keeps your runs so you can read them back, but it is not meant to be your database, and your own table is what stops a second job from buying the same row. What your agent's data calls cost goes further into budgeting.

What idempotency keys cannot do

A key does not undo a charge you already accepted, and it cannot make a provider's answer correct, so a replay gives you the same answer whether it was good or bad. It also only works when the API supports it. If you call a provider directly and it has no idempotency support, your only protection is to record each call before you make it and check that record on restart.

Try it: make a retry safe

Prompt for your agent

Run a lookup with a safe retry

Run a lookup with a safe retry
Use looot to find a work email with a safe retry. 1. Set up https://looot.ai/skill.md. 2. Run job people.email.find with fallback maxAttempts 3 and maxCostUsd 0.10, for a person I give you, with an idempotency key built from their record. 3. Send the same request again with the same key, then show me that the run id matches, that replayed is true and what I was charged in total.

Questions

It is a unique value sent with a request so the server can recognise a retry and return the first result without repeating the work or the charge.

Build it from your own record id and the job, such as `lead-4821-email`, or create a UUID once and store it with the record. Avoid a new random value on each attempt, because the server would treat every retry as new work.

A retry sends a request again, and idempotency makes that safe. Without a key, a retry on a paid API can mean a second charge.

On looot the request is refused with a 409 `idempotency_conflict`. Stripe also returns an error when the parameters differ from the first request, but other APIs may behave differently, so check their docs.

Yes. On looot a request refused for a low balance, a spend limit, a 429 or a 503 keeps no key and costs nothing, so send it again with the same key after the `Retry-After` wait, the top-up or the higher limit.

A miss is free unless its provider bills for it, and each attempt's `billed` field says which.

On looot, set `maxCostUsd` on the run. Any provider that would pass the cap is skipped, and the route never spends more than that.
ShareXLinkedInEmail
Costs

AI agent cost: model tokens plus data calls

AI agent cost has two meters, model tokens and data calls. How to estimate each, why the data side is easier to cap, and how to read per-call prices first.

The looot team · · 7 min read

Try it with the agent you already use

Start your workspace, top up, and paste one prompt into your agent.