Skip to main content

Idempotency and safe retries

Every POST that creates a resource — a message, a call, a contact, a campaign, a top-up — accepts an Idempotency-Key header. This page is the contract you design retry hardening against: what Orbit guarantees on a replay, which failures deserve a retry at all, how long to wait between attempts, and how your send-retry loop composes with the two loops on Orbit’s side (upstream dispatch and webhook delivery). For the error codes referenced here (IDEMPOTENCY_KEY_REUSED, IDEMPOTENCY_KEY_REQUIRED, INVALID_IDEMPOTENCY_KEY, DEDUCT_IN_FLIGHT, BALANCE_SERVICE_UNAVAILABLE), see Error codes.

1. The contract: same key, same result

Send any POST that creates with an Idempotency-Key header set to a value you choose:
Orbit stores the completed response against that key for 24 hours. Within that window:
  • Same key + same body → the cached response. You get the original result back, exactly as it was first returned — no duplicate send, no second charge. Use this to recover the response after a timeout, a connection drop, or a 5xx where you can’t tell whether the request landed.
  • Same key + different body → 409 IDEMPOTENCY_KEY_REUSED. Reusing a key against different arguments is a bug in your client, and Orbit refuses it loudly rather than guess which request you meant.
Pick keys that are unique per logical action. A natural identifier from your own domain — order-conf-98421, invoice-run-2026-08-26-acme — is easier to debug than a random UUID, because the key shows up in your logs alongside the event that produced it. After 24 hours the cache entry expires and the same key is treated as fresh, so don’t build workflows that depend on longer retention. Idempotency-Key guards the creation handshake. It is not a substitute for webhook delivery semantics, which is the at-least-once contract for events flowing the other way; both rely on deduplication, but each direction has its own window and its own key.

2. Money-moving endpoints: the key is required

On endpoints that move money — top-up checkout and the endpoints that follow the same pattern — the Idempotency-Key header is required, not optional:
  • Missing the header entirely → IDEMPOTENCY_KEY_REQUIRED.
  • Sending a key that fails shape validation (length or charset) → INVALID_IDEMPOTENCY_KEY.
The rule of thumb: anywhere a retry could silently double-charge you or your customer, Orbit refuses to run the mutation until you make the retry intent explicit by naming it with a key.

3. Wallet-level concurrency: the second line of defense

The API-level cache answers “did I already run this request?” Balance mutations additionally guard “is this exact balance change already in flight right now?” — two callers racing with the same idempotency key at the same moment. Orbit deduplicates concurrent balance operations in a short window and reports the collisions:
  • DEDUCT_IN_FLIGHT — another request holding the same idempotency key is still running and hasn’t posted its final result within the poll window. Your key is in use right now; wait for the in-flight request to finish and replay, rather than firing a parallel attempt.
  • BALANCE_SERVICE_UNAVAILABLE (503) — the dedup layer itself is temporarily unreachable, so balance changes are refused instead of running unguarded. Retry with exponential backoff; the SDKs already classify 503 as retryable.
You normally never see either: dedup collisions resolve within the poll window, and the SDK retry loop covers the 503. Both exist so that even under concurrency, a wallet charge happens once per named key.

4. SDK behavior: keys you don’t have to think about

Every Orbit SDK auto-generates an Idempotency-Key (UUIDv4) on every non-GET request. A blind retry — the SDK’s own 3-attempt backoff on 429/5xx, or your catch-block re-call — therefore never produces a duplicate even if you never set a key yourself. See SDKs for the status and per-language override syntax; the override is always a single option or argument named idempotencyKey / idempotency_key. The one place you should supply your own key is when retries leave the process that mints the auto key — for example, when a send job sits in your own queue (BullMQ, SQS, Resque) and a worker crash re-runs the job in a fresh process. Generate one stable key per job, store it with the job payload, and pass it on every attempt:
Retry the job with the same key and body — Orbit returns the original response instead of a second send. If the body changed between attempts, the guard answers:
That 409 is the guard telling you your queue mutated the payload between attempts — fix the job so every attempt carries identical arguments.

5. Pause and recovery gates: when a retry is the wrong tool

Before you size a backoff schedule, separate failures that are blips from failures that are gates. Orbit’s send-admission gates — the wallet pause, quiet hours, frequency caps, and throughput ceilings — refuse with a specific signal, and each one has a recovery path that is not “retry the send”:

Why shared recovery aids reconciliation

The pause state is org-level state that every party can read. Your workers, your ops tooling, and the Orbit dashboard all observe the same outbound_paused flag and outbound_block_reason on GET /billing/balance. That shared readout is what makes recovery orderly:
  • One flip, every waiter wakes. Recovery is a single state transition, not N private cooldown guesses. Every worker that polls the balance endpoint resumes on the same flip, so sends restart once, in submission order, instead of staggering back in at whichever backoff deadline each client happened to pick.
  • No retry budget burned against a closed gate. A blind retry loop aimed at a paused org spends its whole schedule on responses that cannot differ from the first one, and its logs then mix “still paused” with genuine outages. A poll loop keeps the two signals separate: the balance endpoint tells you about the pause, the send endpoint stays clean for real failures.
  • A reconcilable ledger. Nothing executed while the org was paused — no message rows, no quota claims, no charges. Resubmitting after the flip therefore creates each send exactly once, and your outbox reconciles against Orbit’s ledger with no dedup or refund cleanup. A hot retry loop that eventually lands mid-resume is safe too (the key dedups it), but the poll shape is what keeps reconciliation trivial.
The same logic applies per recipient: a quiet-hours 422 carries next_allowed_at, and a frequency-cap 429 carries retry_after_seconds — the gate hands you the exact instant its verdict changes, so you schedule instead of guess. The full gate chain, its admission order, and the exact 402/422/429 bodies are on Outbound send gating.

6. Sender-side retry semantics: the four classifications

Every failure your client can see falls into one of four classes, and the class fixes the retry shape: Read the body, not just the status. A 503 whose error code names an account or configuration fault — a billing hold on the upstream account, a suspended or unapproved sender, a policy block — is a verdict wearing a blip’s status code. Retrying cannot clear it, and on some networks repeated sends against a policy block extend the block. Branch on the error code and its guidance; treat those 503s as class 3 until the account state changes. DEDUCT_IN_FLIGHT sits in class 2 with a footnote: it means your own parallel attempt holds the key right now. The correct move is to wait and then replay into the cached result — never to fire a third concurrent attempt.

7. Exponential backoff with jitter

For classes 1 and 2, wait on a doubling schedule with jitter. The nominal schedule is 1s → 2s → 4s → 8s → 16s; apply ±20% jitter to each wait so concurrent clients don’t wake in lockstep and re-trip the same ceiling together: Five retries after the initial attempt (six attempts total) is a sound budget for a send path: ~31 seconds of wall time covers the vast majority of transient blips, and anything still failing after it needs a queue-and-alert posture, not a longer hot loop. Retry-After is a floor, not a suggestion. When a response carries Retry-After, wait max(nominal, header). Orbit sends the header on throttled and guarded responses — Retry-After: 1 on per-second MPS ceilings, Retry-After: 2 on idempotency-guard 503s — and honoring it puts your next attempt after the state that refused you has reset, instead of on top of it.

Retry budget per class

8. The idempotency window, enumerated

The 24-hour replay cache resolves every combination of key and body exactly one way: The 409 body names the key it refused:
Two consequences worth designing around:
  • Store the key with the job, not in process memory. If a worker crashes and a fresh process re-runs the job, the key must survive the crash — that is the only way attempt two in the new process replays attempt one’s result.
  • Expiry is a boundary, not a bug. If a workflow might replay a request more than 24 hours after the first attempt (a dead-letter queue that sits over a weekend, a manual re-run), the replay is a new send. Mint the key at the moment the logical action is created, and treat anything past the window as a decision to send again.

9. Provider-side retries and deduplication

A 200 from POST /messages/sms means Orbit accepted the send; settlement is a separate, later event. Between acceptance and settlement, Orbit handles transient upstream faults on its side — retrying a refused handoff or cascading to an alternate path before the message row settles — and those attempts are deliberately invisible to you. What you see is one API response per accepted send and, later, one settled outcome per message, delivered as webhooks through the delivery lifecycle. That division is the at-least-once contract on the send side, with deduplication at two layers:
  • Your key makes acceptance idempotent. Any number of replays of the same key + body yields exactly one accepted send. Orbit’s upstream retry layer then operates on that one accepted send; its attempts can never turn one key into two messages.
  • Settlement is reported, not inferred. The delivery outcome (delivered, failed, undeliverable) arrives as an event, so you never need to re-send to “check” whether something went out. Querying the message or listening for its event is how you learn the outcome; re-sending without the original key is how duplicates happen.
The practical rule: a failed or timed-out send response with a key attached is “accepted at most once, replay-safe” — never “maybe sent twice”. And a duplicate webhook about that send is the delivery loop re-reporting, not a duplicate send; the next section covers the token that dedups it.

10. Webhook retries: a separate loop from send retries

Events flowing Orbit → you run on their own delivery loop, independent of your send-retry loop. Do not size one against the other:
  • Schedule. One initial attempt plus 9 retries — 10 attempts total — on exponential backoff starting at 30s and doubling (30s → 60s → … → 7680s), with 0–20% jitter. Exhausted retries land the event in the dead-letter queue, roughly 4.3 hours after the first attempt, replayable for 7 days.
  • Dedup token. The envelope id (evt_...). Persist every event id you have processed and drop re-deliveries whose id you have seen; keep seen ids for at least 7 days, long enough to span the retry schedule plus dead-letter replays.
  • Proven-dead responses. 401, 403, 404, and 410 skip the schedule entirely and disable the endpoint — return 2xx for events you choose to ignore, and reserve those statuses for “this URL is dead”.
The two loops meet in exactly one place: both are at-least-once, and both hand you a stable dedup token (your Idempotency-Key outbound, the envelope id inbound). The windows differ on purpose — 24 hours for your replays into Orbit, 7 days for Orbit’s deliveries into you — so never assume one buffer covers the other. The full delivery model, including ordering and auto-disable, is on Webhook delivery semantics.

11. Retry wrappers: Python, Node, and Go

Three reference wrappers that implement the contract above: one stable Idempotency-Key per logical action, passed unchanged on every attempt; retries only for class 1 and 2 signals; Retry-After as a floor; jittered doubling waits; terminal return on any 4xx verdict.

Python

Node (Node 18+)

Go

Adapt the shape to your queue of record: mint the key when the logical action is created, persist it with the job payload, and let every worker attempt reuse it.

12. Failure-mode matrix: retry vs. give up

The ambiguous middle — “it timed out, I don’t know if it landed” — is not a row of its own on purpose: with a key attached it is class 4, and the replay resolves the ambiguity for you. That is the entire point of the header.

Putting it together

  1. On every creating POST, send an Idempotency-Key — natural identifiers from your domain beat random ones for debuggability; store it with the job when retries cross process boundaries.
  2. Classify before you retry: transient network and 429/5xx blips get the jittered doubling schedule; 4xx verdicts and pause gates get a fix, a schedule, or a poll — never a hot loop.
  3. Treat Retry-After as a floor and 5 retries (~31s cumulative) as the hot-loop budget; beyond that, queue and alert.
  4. Read pause state off GET /billing/balance and quiet-hours/frequency-cap hints off the 422/429 details — the gates publish their recovery instant, so schedule against it.
  5. On the way back in, dedupe webhooks on the envelope id for at least 7 days; that loop is separate from everything above and has its own window.

See also