Idempotency: retry without doing it twice
A request is idempotent when sending it twice has the same effect as sending it once. Networks fail, so your code will sometimes not know whether a request reached Hardcount. Hardcount gives you two keys that make a retry safe:
| Requests | The key | Kept for |
|---|---|---|
| Usage events | The idempotency_ field in each event |
Forever |
Every other POST, PUT and PATCH under /v1, except the routes that ignore it |
The Idempotency-Key header |
24 hours |
The rule for both is the same: make the key once for each operation, and send the same key on every retry of it.
Usage events: the idempotency_key field
Section titled “Usage events: the idempotency_key field”Every usage event carries its own key. It names that one event, such as
"acme-1-call-8812:input".
{ "event_name": "tokens", "external_customer_id": "acme-1", "quantity": 1000000, "idempotency_key": "acme-1-call-8812:input", "dimensions": {"model": "claude-sonnet-4.5", "token_type": "input"}}- It is required. An event without one, or with only spaces, is refused
with
422andparam: idempotency_.key - It is at most 255 characters. A longer one is refused with
422. - It is unique for each account and mode (test or live), forever.
- A key that was used before keeps the first event. Hardcount drops the
new one without comparing the two. A single event gets
200, the first event, and the headerIdempotent-Replayed: true. A batch counts it indeduplicated, and itsresults[i].isstatus deduplicated. - A batch is stored all or nothing. If one event is refused, none is stored, so you can resend the whole batch.
Never reuse a key for a different event: that usage is dropped. Do not build keys from a batch position or a timestamp that can repeat. Build them from something your app already counts once, such as a request ID.
The usage routes (/ and /)
ignore the Idempotency-Key header. The event’s own key is their only
check.
Other writes: the Idempotency-Key header
Section titled “Other writes: the Idempotency-Key header”Send the header on every POST, PUT and PATCH you may retry, except on
the routes that ignore it, such as
creating a customer, granting credit or issuing a credit note. Make the key
once, before the first try, and keep it with the job:
IDEM_KEY=$(uuidgen)
curl -si -X POST "$HARDCOUNT/v1/customers" \ -H "Authorization: Bearer $HARDCOUNT_KEY" \ -H "Content-Type: application/json" \ -H "Idempotency-Key: $IDEM_KEY" \ -d '{"external_id": "cust_idem_1", "display_name": "Acme Inc"}'Send the same curl command again, with the same $IDEM_. You see:
the first answer again, with the header Idempotent-Replayed: true. No
second customer is made.
If a customer with that external_ already exists, the first call
answers 409 already_. A 409 is not stored, so the second call
runs again and gets 409 too. Use an external_ you have not used yet.
- Use a random UUID. Every API key and dashboard user of an account shares one set of keys in each mode, so make a key unpredictable, never a counter or a name.
- A key is at most 255 characters, as an event’s
idempotency_is. A longer one is refused withkey 422andparam: Idempotency-Key, and the request does not run. So is a key that isn’t UTF-8 text. - A key belongs to one account and one mode, and a retry must come from
the same caller: the API key, or the dashboard user, that made the
request. A retry from another API key or another user of the account gets
422idempotency_, never the stored answer and never a second run.error - A rotated API key is a new caller. A retry sent with the replacement
key gets
422idempotency_. Read the resource to see whether the change happened.error - Hardcount matches a retry on its caller, its method, its path, its query string and its body. The body must be the same byte for byte.
- A request sent with a key runs to its end, even if your client disconnects. Retry with the same key for its answer.
What a retry with the same key gets
Section titled “What a retry with the same key gets”| The first request | A retry with the same key gets |
|---|---|
Answered any status except 401, 403, 409, 422, 503 or 400 invalid JSON body, including other 4xx and 5xx answers |
The first status and body, plus Idempotent-Replayed: true. The request does not run again. |
Answered 401, 403, 409, 422, 503 or 400 invalid JSON body, and did not crash |
A new run. These answers are not stored, so the key is free again. |
| Crashed inside Hardcount | 500 internal_, plus Idempotent-Replayed: true, whatever it had begun to answer. The key keeps it for its 24 hours. Read the resource before you send the request again with a new key. |
| Is still running, and the retry is the same request from the same caller | 409 conflict_ at once. Hardcount does not wait for the first request: retry in a moment with the same key. |
| Is still running or has finished, and the retry’s caller, method, path, query string or body differs | 422 idempotency_ at once. The key was first used by another caller or for a different request: use a new key for a new request. |
| Started more than 15 minutes ago and never recorded an answer | 409 conflict_. See A key Hardcount could not finish. |
A replay sends the first response’s status and body only. The body’s
request_ is the first request’s. The Hardcount-Request-Id header is the
new request’s. No other header of the first response is sent again.
A stored 4xx comes back too. A 400 other than invalid JSON body,
or a 404 for a record that does not exist, is stored like any other
answer. Fix the request, then send it with a new key: the fixed request has
a different body, so the old key answers 422 idempotency_.
A refusal of the caller is never stored. A 401, or a 403 because the
caller may not call the route or do what it asks, frees the key: Hardcount
answers it before it changes anything. The next request with the key runs,
from this caller or another.
A 400 invalid JSON body is never stored. Hardcount refused the body
before it did anything. Fix the body, then send it with the same key.
A stored 500, 502 or 504 comes back on every retry with that key.
Hardcount stores it on purpose: the first request may have charged a card or
written data before it failed, and running it again could do that twice.
That includes the 500 internal_ of a request that crashed inside
Hardcount. After one of these:
- Read the resource to see whether the change happened, for example with
GET /.v1/ customers?external_ id=cust_ idem_ 1 - If it did not happen, send the request again with a new key.
A 503 is never stored. Hardcount answers 503 only when a second run
is safe: something the request needed failed, and nothing it did would be
done twice. For example, an invoice create that cannot read the
customer’s currency makes no invoice, and answers 503
currency_.
Wait the seconds in Retry-After when the answer has it, then send the same
request with the same key.
A 409 concurrent_ also means a second run is safe. Like every
409, it is not stored. Another change to the same records stopped the
request: Postgres broke a deadlock or ended the request’s wait for a lock,
or, on POST /, the subscription changed twice
while the cancel priced it. It is a 409, not a 503, because the same race
already answers 409 when it does not deadlock. Send the same request again
with the same key. Errors lists the routes that
answer it and what stays done.
Some answers come before the key is checked and are never stored. A retry with the same key runs normally after them:
401(no key or a bad key) and429rate_(the rate limit).limited 404and405for a path or a method no route serves: nothing can run there, so the request holds no key.403for a browser request from another site.413payload_for a body over 1 MB: Hardcount reads the body to match it, and stops there.too_ large 503authentication_.unavailable 503idempotency_: Hardcount could not record the key, so it ran nothing. Retry with the same key;unavailable Retry-Afteris1.
A key Hardcount could not finish
Section titled “A key Hardcount could not finish”If the server stops, or its database fails, between running the request and
storing the answer, the key stays reserved. A retry then gets 409
conflict_. Once 15 minutes have passed since the first request,
it gets 409 conflict_. That is longer
than any request that has a time limit. Some work after a saved change, such
as stopping a payment at Stripe after a void, has none, so the first request
may still be running. A retry with the key never runs it twice. Whether the first
one made its change is unknown:
- Read the resource to see whether the change happened.
- If it did not, send the request again with a new key.
How long a key lasts
Section titled “How long a key lasts”Hardcount keeps a key for 24 hours after the first request. After that the key is free: a request with it runs as a new request, even a retry of the first one. Before you retry a request more than 24 hours old, read the resource to see whether the change happened. Do not reuse a key for a new request, even after 24 hours.
Routes that ignore the header
Section titled “Routes that ignore the header”The header works on POST, PUT and PATCH requests to /v1 routes,
sent with an API key or from a dashboard session. These routes ignore it,
and run every time:
- The usage routes:
/andv1/ usage-events… /. Use each event’sv1/ integrations/ litellm… idempotency_.key - Sign-in, password reset and invites (
/) andv1/ auth… /.v1/ bootstrap - The public pages (
/).v1/ public/ … - The routes Stripe and Postmark call (
/).v1/ webhooks… - The requests whose answer carries a secret shown only once. Hardcount
does not keep that answer, so a retry runs the request again. If you lose
the answer:
- Create an API key (
POST /): list the keys, revoke the one you did not get, and create a new one.v1/ api-keys - Rotate an API key at once (
POST /with no grace period): the retry answersv1/ api-keys/ {id}/ rotate 409, because the old key is already revoked. List the keys, revoke the replacement you did not get, and create a new key. - Rotate an API key with a grace period: the retry makes a second replacement. Revoke the first one, which you did not get.
- Create a webhook endpoint (
POST /): the retry makes a second endpoint. Delete the first one, whose secret you did not get.v1/ webhook-endpoints/ endpoints - Rotate a webhook signing secret
(
POST /): rotate again and deploy the new secret right away. The second rotation stops the secret your receiver still uses, so its signatures no longer verify; deliveries that fail in between are retried on the delivery schedule.v1/ webhook-endpoints/ endpoints/ {id}/ rotate-secret - Rotate a customer’s cost dashboard token
(
POST /): rotate again.v1/ customers/ {id}/ rotate-cost-dashboard-token - Create a card setup session
(
POST /): create another.v1/ customers/ {customer_ id}/ payment-methods/ setup-session
- Create an API key (
GET and DELETE requests do not use it.
A retry loop
Section titled “A retry loop”- Make the key before the first attempt, and keep it with the job.
- On a network error or a timeout, send the same request with the same key.
- On
429, wait the seconds inRetry-After, then send it with the same key. See Rate limits. - On
409conflict_, the first request with the key is still running or did not finish. Wait a second or two, then send it with the same key. Wait longer before each later try.idempotency - On
503, wait the seconds inRetry-Afterwhen the answer has it, then send it with the same key. - On another
5xx, or409conflict_, read the resource first. Send the request with a new key only if the change is not there.idempotency_ unresolved - On another
4xx, do not retry as it is. Fix the request, then send it with a new key. Every code is in Errors.
Usage events are simpler. An event sent again with the same key is never counted twice, so after any error, send the same events with the same keys. The two calls page has a working retry loop in curl, Node, Python and Go.
Stuck, or found a bug? Ask in Discussions · Open an issue