Developers
Guides

Idempotency and retries

Retry a creation without ever creating twice: the Idempotency-Key header and the retry algorithm.

A creation request whose response gets lost — timeout, network cut, restart — leaves a question unanswered: was the invoice created? Retrying blindly risks a duplicate; not retrying risks a miss. The Idempotency-Key header removes the dilemma.

The principle

Generate one key per operation (a UUID v4), keep it with the operation, and send it unchanged on every attempt:

POST/sales/invoices

# One key per operation, reused as is on every retry.
curl -X POST 'https://quosuite.com/api/public/v1/quosuite/sales/invoices' \
  -H "Authorization: Bearer $QUOSUITE_API_KEY" \
  -H 'Idempotency-Key: 3f1c2a9e-5b7d-4e8a-9c1f-2d6b8e4a7c30' \
  -H 'Content-Type: application/json' \
  -d '{
  "partnerId": "11111111-1111-4111-8111-111111111111",
  "reference": "CMD-778",
  "lines": [
    {
      "articleId": "aaaaaaaa-0000-4000-8000-000000000010",
      "quantity": 2
    }
  ]
}'
SituationResponse
first requestprocessed normally; Idempotent-Replayed: false
same key, same body, first one finished (within 24 h)the first call’s response is replayed, nothing is created again; Idempotent-Replayed: true, same status (201)
same key, first one still in progress409 IDEMPOTENCY_IN_PROGRESS, Retry-After: 1
same key, different body or route422 IDEMPOTENCY_KEY_REUSED (detail.firstUsedAt)
first request failedthe key is released: the retry runs
malformed key400 IDEMPOTENCY_KEY_INVALID

The guarantee is durable: the key is kept in the database and a unique index decides between two simultaneous attempts — on the same API instance or on two different ones, including after a restart. Two attempts never create two invoices.

Which routes?

Every creation accepts it — the reference marks them “Idempotent”: documents (quotes, orders, delivery notes, invoices, credit notes, purchases), conversions, deliveries and receipts, payments, stock movements, expenses, articles, categories, partners, contacts.

Key rules

  • 1 to 255 printable ASCII characters; a UUID v4 is the right choice.
  • One key per operation, not per request: replay comes from reusing it unchanged.
  • It is specific to the API key: two integrations never get mixed up.
  • It covers the route and the body: reused for something else, it is refused (422).
  • The replayed result is kept 24 hours; only the key’s fingerprint is stored.

Retry algorithm

Texte
key = uuid4()                        # once, kept with the operation
for attempt from 1 to 6:
    response = POST …  (Idempotency-Key: key)
    if 2xx                           → done (replayed or not)
    if 409 IDEMPOTENCY_IN_PROGRESS   → wait Retry-After, retry
    if 429 / 503                     → wait Retry-After, retry
    if 5xx, timeout, network         → wait 2^attempt s (+ jitter), retry
    otherwise (400, 401, 403, 404, 409, 422) → do not retry: fix
Node.js
import { randomUUID } from 'node:crypto';

async function createWithRetry(url, body, maxAttempts = 6) {
  const key = randomUUID(); // once for the whole operation
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    let response;
    try {
      response = await fetch(url, {
        method: 'POST',
        headers: {
          Authorization: `Bearer ${process.env.QUOSUITE_API_KEY}`,
          'Content-Type': 'application/json',
          'Idempotency-Key': key,
        },
        body: JSON.stringify(body),
        signal: AbortSignal.timeout(30_000),
      });
    } catch {
      await sleep(2 ** attempt * 1000 + Math.random() * 500); // network, timeout
      continue;
    }
    if (response.ok) return (await response.json()).data;
    const retryable = [409, 429, 503].includes(response.status) || response.status >= 500;
    const payload = await response.json();
    if (response.status === 409 && payload.error.code !== 'IDEMPOTENCY_IN_PROGRESS') {
      throw new Error(`${payload.error.code}: ${payload.error.message}`);
    }
    if (!retryable) throw new Error(`${payload.error.code}: ${payload.error.message}`);
    const retryAfter = Number(response.headers.get('Retry-After'));
    await sleep(retryAfter ? retryAfter * 1000 : 2 ** attempt * 1000);
  }
  throw new Error('Giving up after several attempts — the same key can be replayed later.');
}

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));