Errors, idempotency, and retries
Build reliable API clients.
Handle a response in this order: inspect the HTTP status and headers, read the body defensively, then decide whether the operation can safely be repeated. A timeout after a write does not prove that the write failed.
Parse the response you received
REST application errors normally use an errors array:
{ "errors": ["changed_since query parameter is required"] }REST OAuth authorization failures can have an empty body. Inspect WWW-Authenticate for identifiers such as invalid_token or insufficient_scope. The token endpoint /oauth/token uses OAuth JSON with error and error_description instead.
The SDK HTTP API uses a different envelope, including for missing or invalid SDK credentials:
{
"error_identifier": "invalid_request",
"error_details": { "email": ["is invalid"] },
"meta": { "message": "Validation failed" }
}Optional keys may be omitted. A human-readable SDK message, when provided, is at meta.message. Branch on status and documented machine identifiers; treat translated validation messages as diagnostics. Routing, middleware, proxy, and unhandled-server failures can return text, HTML, or no body.
Decide what to do with a status
| Status | Typical meaning | Action |
|---|---|---|
400 | Missing/invalid parameter, malformed body, or a token type that the REST route does not accept. | Correct the request. Check token type separately from scopes. |
401 | Missing, invalid, expired, or revoked credential. | Check the credential and WWW-Authenticate; renew a known expired token once. Avoid an unbounded authentication loop. |
403 | Insufficient scope, origin restriction, disabled feature, or another access restriction. | Fix permission or configuration; identical retries will not help. The body depends on which layer rejected the request. |
404 | Unknown route, unsupported method, missing record, or a record outside the accessible scope. | Check method, path, identifier, and ownership/service/brand context. |
409 | A duplicate or conflicting state on an operation that uses this status. | Read current state and reconcile. A duplicate is not proof that the intended update succeeded. |
410 | An expired ticket-transfer operation. | Start the appropriate new flow rather than retrying the expired transfer. |
422 | Validation or business-rule failure. | Correct the payload or prerequisite state. |
429 | Rate limit or endpoint-specific cooldown. | Honor Retry-After, reduce concurrency, and back off. |
500, 502, 503, 504 or network failure | Server/infrastructure failure; a write's outcome can be unknown. | Retry safe reads with limits. Reconcile writes before deciding to resend. |

OAUTH APPLICATIONS — the Scopes tab of one application, grouped into Data, User Permissions, Admin, and Root. This list, not the token, is what a 403 is measured against · highlight on the assigned-scope count
For SDK sign-in, account_locked is a 401 and can mean either an administrator's persistent account lock or a temporary failed-attempt lockout. Respect a supplied cooldown such as meta.locked_for; administrative locks require an authorized administrator to resolve them. Do not respond by repeatedly attempting sign-in.
Retry safety depends on the operation and payload
The REST API does not provide a general Idempotency-Key contract. Repeating a method that looks idempotent can still repeat events or append child records.
| Operation | Retry considerations |
|---|---|
GET | Safe to repeat as a read, with bounded backoff. The next response can contain newer state. |
| Create or bulk-insert users, tickets, or subscriptions | Do not automatically resend after an ambiguous response. Resolve duplicates and partial results using identifiers and current state. |
| Transaction batch upsert | Use the documented business key consistently. Verify intended fields and keyed line items after uncertain outcomes; another update event may still be emitted. |
| Scalar field update | Reapplying the same values can converge, but check the operation's side effects and concurrent-write rules. This is not an exactly-once guarantee. |
| Transaction update with nested line items | An item with neither id nor external_id is created again on each request. Use stable supported item identifiers or reconcile before retrying. |
| Delete | Confirm the first outcome if the response was lost. A later 404 can mean the record is already gone or is inaccessible; do not ignore all 404 responses universally. |
| Invitations, confirmation, transfer, and other action endpoints | Treat as state transitions with possible email or event side effects. Follow that action's reconciliation rules. |
For transaction updates, keyed merge and replacement mode are different operations. Choose deliberately; replacement can remove omitted line items. skip_events_if_no_changes on supported transaction upserts reduces unchanged-update events but is not request deduplication. See Common REST workflows.
Rate limits and Retry-After
The standard REST API has these default limits:
| Bucket key | Declared default |
|---|---|
| Authenticated user, when the token has a resource owner | 10 requests per 2 seconds |
| Remote IP | 20 requests per second |
| Aggregate key | 200 requests per 10 seconds |
These counters can apply separately across API operation groups; they are not a promised single tenant-wide budget. Separately configured gateway source IPs use a shared bucket of 100 requests per second and skip the standard three buckets. Deployment configuration, cache behavior, and infrastructure can add constraints. SDK sign-in and other operations have additional limits; do not transfer a REST limit assumption to an SDK endpoint.
On a throttled REST request, the body is normally {"errors":["rate_limit_exceeded"]}. The Retry-After header contains seconds. It represents the full configured window, an upper bound on the remaining time in that window, so waiting at least that duration is conservative. After the wait another caller may consume the available capacity: cap total retries and apply jitter.
A bounded read helper
This helper retries GET requests only. It handles JSON, an empty successful response, and non-JSON failures. It has a per-attempt timeout, a retry limit, and a maximum delay per retry. It does not retry a long Retry-After early: it returns the error to the caller instead.
function retryAfterMs(value) {
if (!value) return 0;
const seconds = Number(value);
if (Number.isFinite(seconds)) return Math.max(0, seconds * 1000);
const date = Date.parse(value);
return Number.isNaN(date) ? 0 : Math.max(0, date - Date.now());
}
async function readRest(url, token, {
maxAttempts = 4,
timeoutMs = 15_000,
maxWaitMs = 30_000,
} = {}) {
if (!Number.isInteger(maxAttempts) || maxAttempts < 1) {
throw new Error('maxAttempts must be a positive integer');
}
const retryable = new Set([429, 500, 502, 503, 504]);
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
for (let attempt = 0; attempt < maxAttempts; attempt++) {
const backoff = Math.min(8_000, 500 * 2 ** attempt);
const jitter = Math.random() * 250;
let response;
let text;
try {
response = await fetch(url, {
method: 'GET',
headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },
signal: AbortSignal.timeout(timeoutMs),
});
text = await response.text();
} catch (cause) {
if (attempt + 1 === maxAttempts || backoff + jitter > maxWaitMs) throw cause;
await sleep(backoff + jitter);
continue;
}
let body = null;
if (text.trim()) {
try { body = JSON.parse(text); } catch { body = text; }
}
if (response.ok) return body;
const error = new Error(`Unidy request failed: HTTP ${response.status}`);
error.status = response.status;
error.body = body;
error.authenticate = response.headers.get('WWW-Authenticate');
error.retryAfter = response.headers.get('Retry-After');
const wait = Math.max(backoff, retryAfterMs(error.retryAfter)) + jitter;
if (!retryable.has(response.status) || attempt + 1 === maxAttempts || wait > maxWaitMs) {
throw error;
}
await sleep(wait);
}
}Store only necessary diagnostics. Never log authorization headers, client secrets, or complete customer payloads. A higher-level job should record which work remains pending when its retry budget expires.
Webhook delivery retries
Webhook retries are Unidy sending an event to your receiver. Your receiver must verify signatures and deduplicate accepted events; its response controls whether delivery is acknowledged. Use Retries and duplicate handling for that direction of traffic.