API Resilience, Retries, and Failure Handling

API Resilience, Retries, and Failure Handling

Any external API can be slow or down. Make resilience a per-call default — timeouts, jittered retries, idempotency keys, reconciliation — before the incident.

Any external API your site or storefront calls can be slow, flaky, or down, and the question is whether you decided what happens then before or after it does. Make resilience a per-call default, not per-incident improvisation: aggressive timeouts, bounded exponential backoff with jitter, idempotency keys on every retryable write, circuit breakers, and a defined degraded behavior — with commerce raising the bar through reconciliation. This article gives you a per-call resilience-default table and the small amount of code those defaults imply, including the api resilience patterns money movement makes mandatory.

External APIs fail — design for it

A third-party API is not a function call that occasionally throws. It is a network hop to a system you do not operate, with its own deploys, incidents, rate limits, and bad days. Latency spikes, partial failures, timeouts, and full outages are not exceptional events to handle as an afterthought — they are the normal operating envelope. The teams that get hurt are not the ones whose vendor went down; any vendor can go down. They are the ones who never decided what their own system does when it happens.

Reactive failure handling often produces the same shape. A vendor slows down, requests pile up waiting on it, the request pool exhausts, and an outage in one non-critical integration takes the whole site with it. Or a write times out, gets retried blindly, and the customer is charged twice. None of these are exotic. They follow from treating an external call like a local one and bolting on a try/catch after the first incident teaches you it was needed.

Resilience is a default decided per call before the build, not a library you add under pressure. For every external call you answer a small fixed set of questions up front: how long do we wait, do we retry, is this operation safe to retry, what does the user see while it fails, and — if money moved — how do we find out the true outcome later. The rest of this article is those answers and the patterns that implement them.

Timeouts and retries

A request with no explicit timeout can wait far longer than any user will — some clients, such as Python Requests, do not time out unless a timeout is set explicitly, and others, such as Node's undici HTTP client, default to timeouts measured in minutes — and a hung request is worse than a fast failure because it holds a connection, a thread, and a slot in your request pool while doing nothing. Set an aggressive, explicit timeout on every external call, tuned to the call's role: a few seconds as a starting point for anything on a user-facing path, longer only for background work that genuinely needs it. The goal is to fail fast and free the resource, not to wait politely for a vendor that is not coming back.

Retries recover transient failures, but only with discipline. The default is bounded exponential backoff with jitter: wait roughly twice as long after each attempt, cap the wait, stop after a small fixed number of attempts, and add randomness so that a fleet of clients does not retry in lockstep and turn a vendor's brief hiccup into a synchronized stampede. When the vendor tells you how long to wait, listen: a 429 Too Many Requests (defined in RFC 6585) that carries a Retry-After header (defined in RFC 9110) indicates how long the server says you ought to wait before a follow-up request — treat it as the server's requested delay, not an error to retry immediately. Honor Retry-After when present and fall back to jittered backoff when it is not. Structured error bodies following RFC 9457 Problem Details can identify the kind of problem with a type URI, and an API can define extension members for that problem type, so "is this retryable" can be a documented field you read rather than a string you parse. RFC 9457 itself defines no retryable member; a problem type definition may also specify use of the Retry-After header in appropriate circumstances.

The hard rule: retry only operations that are safe to repeat. Reads and naturally idempotent operations are safe. A non-idempotent write — create an order, capture a payment — is not safe to retry, and retrying one without an idempotency key is how a single timeout becomes a duplicate charge. RFC 9110 defines which HTTP methods are idempotent by design. For a request with any other method, it says a client SHOULD NOT retry automatically unless it has some means to know that the request semantics are actually idempotent, regardless of the method, or some means to detect that the original request was never applied. The idempotency key in the next section is one way to get that assurance, when the receiving system documents that it honors the key.

Idempotency for writes

An idempotency key makes a write safe to repeat. The client generates a stable, unique key for the logical operation and sends it on every attempt, including retries; the server recognizes a repeat of the same key (and, where it also checks a request fingerprint generated from payload data, a matching fingerprint) and, once the original request has completed, should respond consistently with the request having been completed as the user intended rather than performing the operation again. Under the IETF draft, a repeat that arrives before the original request has completed should get a resource conflict error instead, and what a provider stores and replays varies: Stripe's API v1, for example, saves the status code and body of the first request made with a key after endpoint execution begins and returns that saved response for retries, including 500 errors. The timeout-then-retry race — where you never learn whether the first attempt succeeded — stops being a double-write risk and becomes a no-op. The IETF Idempotency-Key header draft — an httpapi working-group Internet-Draft, not an RFC (revision -08, October 22, 2026, as of Nov 2026) — proposes standardizing the header that payment APIs such as Stripe and Adyen already expose under that name; other providers use their own names, such as PayPal's PayPal-Request-Id.

The key must be stable across retries of the same operation, not regenerated per attempt: generate a unique key once for the logical operation, following the uniqueness rules the receiving API defines — the IETF draft recommends a UUID or a similar random identifier — store it with that operation, and resend it on every retry. Under the draft, a key must not be reused with another request that has a different request payload. A freshly generated key per retry defeats the entire mechanism, because the server sees each attempt as a new operation. Server-side dedupe is the authoritative half — a client-generated key only protects you if the receiving system actually records and honors it — so confirm the vendor's idempotency semantics during scoping, not during an incident. Idempotency keys are mandatory, not optional, for any retryable write, and unconditionally mandatory for payments.

Sometimes you genuinely cannot tell whether a write landed: the request timed out before any response, the idempotency window expired, or the vendor's state is briefly inconsistent. That is what reconciliation is for. When the outcome is unknown, do not guess and do not blindly retry — record the operation as pending and resolve it against the vendor's own record of truth. This is where commerce raises the bar above a marketing site: an unknown form submission can be dropped; an unknown payment cannot.

Circuit breakers and bulkheads

When a dependency is clearly failing, continuing to call it makes things worse for everyone. A circuit breaker watches the failure rate of one integration and, once it crosses a threshold, stops sending requests for a cooldown period and fails fast instead — returning an immediate, cheap error rather than a slow timeout. After the cooldown it allows a trial request through; success closes the breaker, failure extends the cooldown. The point is not to hide the failure but to stop spending your own latency budget and connection pool hammering a system that is already down, and to give it room to recover instead of amplifying its outage with your retries.

Bulkheads isolate the blast radius so one failing integration cannot sink the rest. Give each integration its own bounded resource budget — its own connection pool, its own concurrency limit — so that a vendor consuming all available connections starves only its own calls, not the checkout path or the unrelated catalog service sharing the process. The combination is what keeps a single bad dependency local: the breaker stops the bleeding for that integration, the bulkhead keeps the bleeding from spreading. These are patterns, not products; the value is in the behavior, and any implementation that produces it is acceptable.

Degradation and dead-letter

Failing fast is only useful if you have decided what happens after the fast failure. Degraded behavior is a per-integration design decision made during scoping, and it has a small menu: serve stale-but-cached data, queue the work to complete later, hide the feature, or block the action. A store-locator map can show a cached result or quietly disappear; a marketing page tolerates an async widget that never loads. The choice follows directly from whether the integration was marked launch-blocking or degradable in the inventory — degradable integrations get a graceful fallback, launch-blocking ones get a hard, visible failure rather than a silent wrong answer.

Asynchronous work needs a dead-letter path and replay. When an event cannot be processed after bounded retries — a poison message, a permanently malformed payload — it goes to a dead-letter store rather than blocking the queue or being discarded. The dead-letter store is inspectable and replayable, so a fixed bug or a recovered dependency lets you reprocess what failed instead of reconstructing it from logs. For commerce the rule is absolute: an order or a payment event is never silently lost. If it cannot be processed now, it is persisted and visible until it is, and the reconciliation safety net catches anything that slips. A marketing site can afford to drop a degraded widget's request; a storefront cannot afford to drop a paid order, and the architecture has to make that impossible by construction, not by hope.

The resilience defaults summary

The deliverable is a table you fill in once per call class during scoping, so resilience is a default the code inherits rather than a decision made mid-incident. The timeout values in it are starting points to tune per integration, not measured benchmarks.

Call classTimeoutRetry policyIdempotencyDegraded behavior
Read, non-critical (store locator)Short (1–3s)Bounded backoff + jitterN/ACached or hidden
Read, critical (live price, stock)Short (1–3s)Bounded backoff + jitterN/ACached with staleness, or block buy
Write, non-payment (create order)ModerateOnly with idempotency keyKey requiredQueue and retry; never silent loss
Payment authorization / captureTight, single-pathOnly with idempotency keyKey mandatoryBlock; reconcile on unknown
Async event consumerPer handlerBounded, then dead-letterDedupe by event idDead-letter + replay + reconcile

The code those defaults imply is small. A bounded retry with full jitter that honors Retry-After, wrapping only safe-to-retry calls, plus a stable idempotency key on the write it protects:

typescript
const sleep = (ms: number) => new Promise<void>(r => setTimeout(r, ms))
const BASE = 'https://api.payments.example' // your provider's base URL

// Bounded retry with full jitter. Wrap only idempotent calls,
// or non-idempotent calls that carry an idempotency key.
async function withRetry(
  call: (signal: AbortSignal) => Promise<Response>,
  opts = { attempts: 4, baseMs: 200, capMs: 8_000, timeoutMs: 3_000 },
): Promise<Response> {
  for (let attempt = 0; ; attempt++) {
    const ctrl = new AbortController()
    const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs)
    try {
      const res = await call(ctrl.signal)
      if (res.status === 429 || res.status >= 500) {
        if (attempt >= opts.attempts - 1) return res
        // Retry-After may be seconds or an HTTP-date; this sketch reads the seconds form and otherwise falls back to backoff.
        const retryAfter = Number(res.headers.get('Retry-After')) * 1000
        const backoff = Math.min(opts.capMs, opts.baseMs * 2 ** attempt)
        // Full jitter: honor Retry-After, else random within the ceiling.
        await sleep(retryAfter || Math.random() * backoff)
        continue
      }
      return res
    } catch (err) {
      if (attempt >= opts.attempts - 1) throw err
      await sleep(Math.random() * Math.min(opts.capMs, opts.baseMs * 2 ** attempt))
    } finally {
      clearTimeout(timer)
    }
  }
}

// A retryable write MUST carry a key stable across retries: generate it once per capture (e.g. crypto.randomUUID()), store it with the order, and reuse it on every retry.
function capturePayment(orderId: string, amount: number, captureKey: string) {
  return withRetry(signal =>
    fetch(`${BASE}/payments/capture`, {
      method: 'POST',
      signal,
      headers: {
        'Content-Type': 'application/json',
        'Idempotency-Key': captureKey, // check your provider's key format (the IETF draft defines the value as a quoted string)
      },
      body: JSON.stringify({ orderId, amount }),
    }),
  )
}

That is the resilience surface for a well-designed integration: a timeout and a bounded jittered retry on safe calls, an idempotency key on every retryable write, a breaker and a bulkhead around the dependency, and a defined degraded behavior. Commerce raises the bar by adding one non-negotiable on top — reconciliation against the vendor's source of truth — because a missed read is a refresh and a missed payment is a dispute.

Diagnostic checklist for the next planning cycle

  • Set an explicit, aggressive timeout on every external call — no unbounded waits
  • Make bounded exponential backoff with jitter the retry default, and honor Retry-After on 429
  • Confirm which operations are safe to retry; never retry a non-idempotent write without an idempotency key
  • Add a stable idempotency key, generated once per operation and reused on every retry, to every retryable write and all payments
  • Put a circuit breaker and a bounded resource budget around each integration
  • Decide and document the degraded behavior per integration — cached, queued, hidden, or blocked
  • Define dead-letter, replay, and payment reconciliation so a money event can never be silently lost
Project Inquiry