Build / Idempotency
Retries and idempotency
Networks fail. A timeout on a create request does not tell you whether the customer was charged. The Idempotency-Key header lets you repeat the request safely and get the original order back.
The rule
Every POST /v1/orders must carry an Idempotency-Key header. Use one key per sale, and use the same key every time you retry that sale.
- 8 to 100 characters: letters, digits,
_ . : -. - Unique within your account. Your own sale or invoice ID works well, for example
sale-3-000187. A random UUID created when the sale starts and saved with it also works. - Kept forever. A key that created an order always refers to that order. Do not reuse a key for a different sale, even months later.
What Vukia does with the key
| You send | Vukia returns |
|---|---|
| A new key | Creates the order: 201. |
| A key that already created an order, with the same body | The existing order, as it is now: 200 with the header Idempotent-Replayed: true. No second order and no second charge. |
| A key that already created an order, with a different body | 409 idempotency_conflict. Nothing is created. |
| A key whose first request is still running | 409 request_in_progress. Wait a few seconds and send it again. |
| A key whose earlier request was rejected before an order existed (validation, limits, temporary unavailability) | The request is judged again from scratch. You may correct the body and reuse the key. |
"Same body" means the same order details after normalisation. 0712345678 and +254712345678 count as the same phone number, so a retry that formats the number differently still matches.
{
"error": {
"code": "idempotency_conflict",
"message": "This Idempotency-Key was already used with different order details.",
"request_id": "req_93c0652331804191539c13f4"
}
}
When to retry
| Result | Retry with the same key? |
|---|---|
| Timeout, connection reset, no response | Yes. You do not know whether the order exists. The retry returns it if it does. |
409 request_in_progress | Yes, after 2 to 5 seconds. |
502 upstream_unavailable, 503 service_unavailable | Yes, with backoff: 2 s, 5 s, 15 s, then ask the cashier. |
429 rate_limited | Yes, after a minute. |
503 rate_unavailable, liquidity_unavailable, service_paused | Not immediately. Tell the customer it is unavailable right now. A later retry with the same key is safe. |
Any 400 or 422 | Not unchanged. Fix the input first, for example ask the customer for a different Lightning address. |
201, then the order becomes payment_failed | No. Use a new key. The old key will always return the failed order. |
A safe create function
// Creates the order for a sale, or returns the one that already exists.
// saleId must be stored with the sale before this is called.
async function createOrder(saleId, details) {
const delays = [0, 2000, 5000, 15000];
let lastError;
for (const wait of delays) {
if (wait) await new Promise(r => setTimeout(r, wait));
try {
const res = await fetch('https://api.vukia.app/v1/orders', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.VUKIA_API_KEY}`,
'Content-Type': 'application/json',
'Idempotency-Key': `sale-${saleId}`,
},
body: JSON.stringify(details),
signal: AbortSignal.timeout(40_000),
});
const body = await res.json();
if (res.ok) return body; // 201 created or 200 replayed
const retry = res.status === 429 || res.status === 502 || ['request_in_progress', 'service_unavailable'].includes(body.error.code);
if (!retry) throw Object.assign(new Error(body.error.message), { code: body.error.code, param: body.error.param });
lastError = body.error;
} catch (err) {
if (err.code) throw err; // a definite API answer
lastError = err; // network failure: retry the same key
}
}
throw Object.assign(new Error('Vukia did not answer. Retry this sale later; it is safe.'), { cause: lastError });
}
import os, time, requests
RETRY_CODES = {"request_in_progress", "service_unavailable", "upstream_unavailable", "rate_limited"}
def create_order(sale_id: str, details: dict) -> dict:
"""Creates the order for a sale, or returns the one that already exists."""
last = None
for wait in (0, 2, 5, 15):
time.sleep(wait)
try:
res = requests.post(
"https://api.vukia.app/v1/orders",
headers={
"Authorization": f"Bearer {os.environ['VUKIA_API_KEY']}",
"Idempotency-Key": f"sale-{sale_id}",
},
json=details,
timeout=40,
)
except requests.RequestException as e: # network failure: retry the same key
last = e
continue
body = res.json()
if res.ok:
return body # 201 created or 200 replayed
if body["error"]["code"] not in RETRY_CODES:
raise ValueError(f"{body['error']['code']}: {body['error']['message']}")
last = body["error"]
raise RuntimeError(f"Vukia did not answer. Retrying this sale later is safe. Last error: {last}")
Write the sale and its key to your database before calling Vukia. If your process crashes mid-request, the restarted process can resend with the same key and find the order.
Other requests
Reads (GET) are always safe to repeat. POST /v1/quotes creates nothing. POST /v1/webhook replaces your endpoint and issues a new secret each time, so repeating it is harmless but changes the secret. Use the secret from the last successful response.