Quickstart

Quickstart: add timeouts and retries to a Node.js API client

A production API client needs a timeout and a retry policy. In Node, an AbortController bounds every request and a small retry wrapper handles transient 429/5xx — combined with an idempotency key, this turns a naive fetch into a resilient client.

2 min read

AbortControllerBound every request
retry 429/5xxOnly transient errors
idempotentRetries stay safe

Timeout every call

async function fetchWithTimeout(url, init = {}, ms = 8000) {
  const ac = new AbortController();
  const t = setTimeout(() => ac.abort(), ms);
  try {
    return await fetch(url, { ...init, signal: ac.signal });
  } finally {
    clearTimeout(t);
  }
}

Retry only what's safe

async function resilient(url, init) {
  for (let attempt = 0; attempt < 4; attempt++) {
    try {
      const res = await fetchWithTimeout(url, init);
      if (res.status < 500 && res.status !== 429) return res;
    } catch (e) {
      if (e.name !== 'AbortError' && attempt === 3) throw e;
    }
    await new Promise(r => setTimeout(r, 2 ** attempt * 200 + Math.random() * 200));
  }
  throw new Error('exhausted retries');
}

Retry 429 and 5xx and network aborts; never retry a 4xx other than 429 — a 400 will fail identically no matter how many times you send it. Pair retries with an idempotency key so a retried POST is safe.

Frequently asked questions

What timeout should I set?

Public reads are fast; 5–8 seconds is generous. Set it low enough that a hung request fails fast and your own request cycle stays responsive.

Is it safe to retry a POST?

Only with an idempotency key. Without one, a retried POST could create a duplicate. With one, the API returns the original result.

Funding for UK limited companies

Credicorp lends to your company, not to you personally — short-term working capital with no personal guarantee. See what your business could access.