Idempotency & retries
Network failures happen mid-request. Without idempotency, retrying a
POST /v1/invoices could create two documents for one sale — and once both
are signed, two claves in Hacienda’s official record. EmiteCR gives you two
complementary layers.
Layer 1 — Idempotency-Key header (24h transport replay)
Section titled “Layer 1 — Idempotency-Key header (24h transport replay)”Protects POST /v1/invoices (and creating a customer or an item) against
retries of the same request.
curl -X POST https://api.emite.cr/v1/invoices \ -H "x-api-key: $EMITECR_API_KEY" \ -H "Idempotency-Key: 01a00c73-5c07-7bb5-8b9e-d20f16537e42" \ -H "Content-Type: application/json" \ -d '{ "docType": "04", "currency": "CRC", "lines": [/* … */] }'The server hashes the significant parts of the body and stores the key for 24h:
- First hit — processes and caches the response.
- Same key + same payload — returns the cached response, no re-processing.
- Same key + different payload (or another endpoint) —
422 IDEMPOTENCY_KEY_REUSED_DIFFERENT_PAYLOAD. You meant a new request; rotate the key. - Same key + still in flight —
409 IDEMPOTENCY_REQUEST_IN_PROGRESS. Wait 1–2s and retry. - The first attempt failed — nothing is cached: retrying with the same key runs the request again.
Rotate the key when the payload changes, when emitting a logically distinct document, or after fixing a 4xx. Don’t rotate on a network blip or timeout — retry with the same key so the server returns the committed response instead of creating a duplicate.
The window is 24h; sandbox and production keep separate slots for the same key.
The key is stored verbatim as varchar(255) — the server does not validate
UUID format. Any string up to 255 characters works: a UUID of any version (v4
from crypto.randomUUID(), v7, …) or your own correlation id such as
order-12345-attempt-1. UUIDv7 is a nice default because it is time-ordered.
Layer 2 — externalReference (permanent business identity)
Section titled “Layer 2 — externalReference (permanent business identity)”Idempotency-Key expires after 24h. For a durable link between your business
event and the EmiteCR document, set externalReference on the invoice — your
own id (a POS ticket uuid, an order number):
{ "docType": "04", "externalReference": "ticket-9f3b8c1d", "lines": [/* … */] }It’s unique per (company, environment) forever (up to 128 characters). A
duplicate returns 409 INVOICE_EXTERNAL_REFERENCE_EXISTS naming the existing
invoice. That makes a whole emission resumable: when a step fails, look the
sale up and continue from where it stopped instead of creating it again:
curl "https://api.emite.cr/v1/invoices?externalReference=ticket-9f3b8c1d" \ -H "x-api-key: $EMITECR_API_KEY"- not found → create it;
status: draft→ sign/submit it;signedor later → it already has its number; read the verdict.
A deliberate re-emission (e.g. a corrected document after a rejection) uses an
attempt suffix: ticket-9f3b8c1d:2, :3, …
Signing and submitting are idempotent by resource
Section titled “Signing and submitting are idempotent by resource”POST /v1/invoices/:id/sign and POST /v1/hacienda/submit/:invoiceId don’t use
the header — their idempotency comes from the document: signing a signed
document returns the same consecutivo and clave, and submitting one that is
already at Hacienda returns its current state without sending it again. Re-call
them freely; only the step that failed runs again. The retry pattern is simply:
retry on 502 / 503 / 504 with exponential backoff.
HTTP status → retry guidance
Section titled “HTTP status → retry guidance”| Status | Retry? | How |
|---|---|---|
| 2xx | No | — |
| 400 | No | Fix payload, rotate key, resend |
| 401 | After reauth | Refresh JWT / check the API key |
| 402 | No | The company’s plan — see errors |
403 INSUFFICIENT_SCOPE |
No | Give the key the scope in params.required |
409 …IN_PROGRESS |
Yes (1–2s) | First call is finishing |
422 …DIFFERENT_PAYLOAD |
No — rotate key | New key |
422 ATV_REJECTED / …TOTALS_MISMATCH |
No | Permanent; fix + new document |
| 424 | No | Hacienda refused (credentials or the request) — read the error |
| 429 | Yes | Honor Retry-After |
| 502/503/504 | Yes | Backoff 1–5s, double, cap 60s, ~5 attempts |
Recommended retry loop
Section titled “Recommended retry loop”async function postWithRetry(url, payload, idempotencyKey) { // Retry on the STATUS, not on the code: `ATV_NETWORK_ERROR` is a 502 when // Hacienda did not answer (retry) but a 424 when it refused (don't). const TRANSIENT_HTTP = new Set([429, 502, 503, 504]); const TRANSIENT_CODE = new Set(['IDEMPOTENCY_REQUEST_IN_PROGRESS']);
for (let attempt = 0; attempt < 5; attempt++) { const res = await fetch(url, { method: 'POST', headers: { 'x-api-key': process.env.EMITECR_API_KEY, 'Content-Type': 'application/json', 'Idempotency-Key': idempotencyKey, }, body: JSON.stringify(payload), }); if (res.ok) return res.json();
const body = await res.json().catch(() => ({})); const code = body?.error?.code;
const retryAfter = res.headers.get('retry-after'); if (retryAfter) { await sleep(Number(retryAfter) * 1000); continue; }
if (TRANSIENT_HTTP.has(res.status) || TRANSIENT_CODE.has(code)) { await sleep(Math.min(60_000, 1_000 * 2 ** attempt + Math.random() * 500)); continue; } throw new Error(`${code ?? res.status}: ${body?.error?.message ?? res.statusText}`); } throw new Error('Retry budget exhausted');}GETs are always safe to retry. Retry a POST only when it carries an
Idempotency-Key (creating) or acts on an existing document (signing,
submitting).
Never retry CREATE in response to a SUBMIT failure
Section titled “Never retry CREATE in response to a SUBMIT failure”If POST /v1/invoices succeeded (you have the draft’s id) but sign or submit
failed, retry sign/submit on that id — never create. Re-creating would
make a second document for the same sale, and a second clave once it is
signed. If you set externalReference, a stray re-create is caught anyway
(409), but the correct action is to resume.