Idempotency keys for USDT payouts: retry without paying twice
A request for energy that times out leaves a payout job unable to tell what happened. The request may never have reached the API, or it may have reached the API and created an order whose answer was lost. Sent again with the same Idempotency-Key and the same bytes, the request leaves at most one order and at most one reserve, whichever happened. The key is paired with the raw bytes of the body, so a retry that serializes its JSON a second time can be refused.
A timeout after the order was created
Suppose a payout job has 200 transfers of USDT to send. The job posts all 200 as one order in mode A, where your own code broadcasts each transfer, and the job's HTTP client stops waiting after ten seconds. By then we may have created the order, placed the reserve on your balance and started buying energy. The job would see the same timeout if the request had never arrived.
If the job then posts the same 200 transfers under a new key, the API cannot know that the second request repeats the first one, so the API creates a second order. With a balance that covers both orders, we buy energy for the same transfers twice, and in mode A we charge for delivered energy whether or not a transfer uses it before send_before.
If the job instead posts the same bytes under the same key, we buy nothing a second time. POST /v1/orders requires the header, and a retry under the same key returns the original order and creates no new one. One key covers the whole order, up to 500 transfers (how a batch is run).
The key is paired with the bytes of the body
We decide whether two requests are the same request by hashing the raw bytes of each body. Two bodies that parse to the same object and differ in the order of their fields, in whitespace or in the formatting of a number are different bodies, and the second body under the same key gets 409 idempotency_conflict.
A client that passes an object to its HTTP library has the object serialized again at every call, and a job restarted after a crash may rebuild the body from its database, so a retry can carry different bytes. Serialize the body once, store the bytes beside the key before the first send, and send the stored bytes on every retry.
Four answers about the key
| What you send | Answer | What exists afterwards |
|---|---|---|
| The same key with a byte-identical body | 202 and the original order | One order; nothing reserved or charged a second time |
| The same key with a different body | 409 idempotency_conflict | The first order only |
| A body that is refused before an order is created | The refusal: 400, 402, 422, 429 or 503 | No order; the key is still unused |
| An empty key, or no header | 400 invalid_request | No order |
A replay returns the original order as that order stands when the replay arrives. The status code is 202 again and the Location header names the original order. We read the order at that moment, so a replay that arrives after the energy is delivered shows the order with send_before filled in.
The key is bound only to an order that was created. A request refused for its form (400), for its addresses (422) or for the balance (402) leaves the key unused: fix the body, activate the wallet or top up the balance, and send again under the same key (the failures behind these refusals).
We refuse an empty string as a key, and a request with no header as well. If we accepted an empty key, all requests sent with one would share a single key: a request that repeated the bytes of the first body would get the first order back with a success code, and any other body would get 409 idempotency_conflict.
The contract names no period after which a key is forgotten, so treat a used key as used for good. An idempotency key is a string of 1 to 128 characters, and the account is its scope. A request sent with another API key of the same account under the same idempotency key gets the first order back, or 409 idempotency_conflict if its bytes differ.
What to do after a timeout
Send the stored bytes again under the same key. The retry returns the order if the first request created it, and creates the order if the first request never arrived, unless the retry itself is refused.
429 rate_limited gives the number of seconds to wait in Retry-After, and 503 capacity_unavailable means the request can be sent again later. 500 internal_error is a fault on our side, and repeating the request under the same key is safe.
A refusal that follows an unanswered attempt settles nothing about that attempt. When a 400, 402, 422 or 503 answers a retry, an earlier attempt that got no answer may still have been running: its order can be committed after your client stopped waiting, and a 402 can come from a balance already reduced by the reserve of the earlier attempt. Before you give the payout a new key, send the stored bytes once more, or look for the order with GET /v1/orders?client_ref= and the client_ref you wrote into the body.
Give a payout a new key only for a new attempt, after the order of the previous attempt has reached a final status. An idempotency key stays bound to its order after the order is canceled or fails, so the same key with the same bytes returns that old order. The client documentation describes a key built from the payout's own name and an attempt number, and warns that a fresh UUID for every HTTP call buys the energy a second time at the first timeout.
# Python, standard library only. API_KEY, SENDER and RECIPIENT are yours.
import http.client, json, os, time, urllib.error, urllib.request
BASE = "https://sandbox.nrg.market/v1"
payout = "payout-7731"
stored = payout + ".request"
if not os.path.exists(stored): # first run: serialize once
with open(stored + ".tmp", "wb") as out:
out.write(json.dumps({"mode": "a", "client_ref": payout, "transfers": [
{"from": SENDER, "to": RECIPIENT}]}).encode())
os.replace(stored + ".tmp", stored) # a crash leaves no half-written body
with open(stored, "rb") as kept: # every run, a restart included,
body = kept.read() # sends the stored bytes
headers = {"Authorization": "Bearer " + API_KEY, "Content-Type": "application/json",
"Idempotency-Key": payout + ":1"} # ":2" only when order ":1" is final
def place_order():
for _ in range(4):
request = urllib.request.Request(BASE + "/orders", data=body, headers=headers)
try:
with urllib.request.urlopen(request, timeout=10) as answer:
return json.load(answer) # 202: the order, new or replayed
except urllib.error.HTTPError as refusal:
if refusal.code == 429 and b"too_many_auth_failures" in refusal.read():
raise # a refused API key: waiting will not help
if refusal.code not in (429, 500, 503):
raise # 400, 402, 409, 422: read the answer first
time.sleep(int(refusal.headers.get("Retry-After", 2)))
except (OSError, ValueError, http.client.HTTPException):
time.sleep(2) # no answer, or a cut one: same key and bytes
raise RuntimeError("no answer; run again with the stored bytes")
Which requests take a key
Three operations require the header: POST /v1/orders in all three modes, POST /v1/queue-sessions and POST /v1/queue-sessions/{session_id}/items. A replayed session creation returns the original session with 201, as the first answer did, and a replayed append appends nothing: it returns added as it was, with the session's counters as they are now. The idempotency key of an append is bound to its session as well as to the account: the same key sent to the items of another session gets 409 idempotency_conflict even when the body is identical.
Four other write operations answer a repeat from the state of the object they name. POST /v1/orders/{order_id}/cancel succeeds while the order is created, funded or awaiting_funds; from purchasing on, and on an order that is already canceled, the answer is 409 order_not_cancelable. Start on a queue session that is already running or paused answers 200 and changes nothing, and so does Stop on a session that is already stopped. A second POST /v1/auto-refill-rules for a wallet on which your account has an active rule is refused with 409. Other writes have no such guard: a repeated POST /v1/webhooks registers a second endpoint with a second secret.
Duplicates the key does not cover
The key identifies a request to our API and knows nothing of the payout behind the request. In mode B you hand us a signed transaction and we broadcast it. One signed transaction can be carried by one position at a time. A copy of it in the same batch is refused with 400 invalid_request, and so is a transaction that a position of another order already carries in any status except failed; details.index names the copy in your body. Sending it under a new idempotency key does not get around the refusal. A transaction is free again once its position closes as failed, which includes every position of a canceled order, and it can then go into a new order. The one exception is a failed position with transaction_reverted, whose transaction is already in a block. A transaction from an expired position stays used.
Neither the key nor the rule on signed transactions recognizes a payout that your code builds and signs a second time. A transaction built again normally differs from the first in its expiration or its reference block, so the rebuilt transaction has another hash, and the API treats it as another transfer. Your own records have to keep at most one open attempt for each payout.
In mode A the transfer never passes through us, so no check of ours can stop your own code from broadcasting the same transfer twice.
Webhook deliveries repeat too. When your receiver answers an attempt with an error, or too slowly, we deliver the event again, and every attempt carries the same event_id. Dropping the repeats by that id is the receiver's job (the delivery headers).
What we did not run
Nothing here was measured: the rules come from the API contract and the client documentation. We read five rules in the code behind the contract, because the contract does not spell them out: the current status in a replay, a key that stays bound to a canceled or failed order, the account-wide scope of a key, the answer to a repeated cancel and the refusal of a missing header. We ran the example against a local stand-in that creates the order and withholds the first answer. We did not run it against production or against the sandbox, where idempotency behaves as it does in production, over test money.
Withdraw an order that is still in created, funded or awaiting_funds, and we release the reserve of a funded order whole: POST /v1/orders/{order_id}/cancel in the API reference →