Building reliably
Idempotency
A network can lose a response after the server has done the work. An idempotency key lets you send the request again without doing the work twice.
The header#
Every POST, PUT, PATCH and DELETE needs an Idempotency-Key header. A request without one is refused with 400 and the code idempotency_key_required. GET requests do not need one: reading twice changes nothing.
The key is any string of your choosing, up to 255 characters, unique to the operation. A random UUID is the usual choice. Keys are scoped to your organisation, so they cannot collide with anybody else’s.
Both SDKs generate a key for every request that changes something, and send the same key and the same body when they retry. You only need to think about keys when you want a retry to be safe across a restart of your own process.
What a repeated key does#
ExportFlow remembers each key together with a fingerprint of the request it was used for: the method, the path and the body.
| Situation | Answer |
|---|---|
| Same key, same request, and the first one finished | The original response, replayed with its original status. The work is not done again. |
| Same key, same request, and the first one is still running | 409 request_in_progress. Wait briefly and send it again. |
| Same key, different request | 409 idempotency_key_reused. A bug in the caller: use a new key for a new request. |
| The first request failed with a 5xx | The key is released, so the retry runs as a new request. A server fault never uses a key up. |
A refusal that depends on the request itself is remembered too. If a request was answered 422 or 409 not_confirmed, sending it again with the same key returns that same answer. Fix the request, or confirm the record, and send it with a new key.
A 429 is never remembered, whatever its code (rate_limited, quota_exceeded, too_many_documents_in_progress). It means “not now”: wait as the answer says, then retry with the same key.
Choosing your own keys#
A random key protects one attempt and its immediate retries. If your process can crash between sending a request and recording the result, derive the key from something of your own that identifies the operation, so the retry after a restart carries the same key:
client.documents.upload(
file="bl.pdf",
shipment_id=sid,
idempotency_key=f"upload-{erp_document_id}",
)When an SDK uploads a document without a shipment, it creates the shipment with a key derived from the upload’s key. A retried upload therefore finds the shipment the first attempt made instead of creating another.
Two related guarantees#
- Duplicate files. Uploading the same file to the same shipment again, even with a new key, returns the first document with
duplicate: true. See Documents. - Billing. Usage is recorded once for each thing that happened, not once for each request that asked for it. A retried upload or a repeated verification request cannot be charged twice. See Billing.