Retry-After Header Backoff

Interpret a Retry-After header as seconds or an HTTP date and cap the delay before the next retry attempt.

JavascriptResilience

Code

javascriptsnippet
23 lines
export function retryDelay(header, { now = Date.now(), maxDelayMs = 60000, fallbackMs = 1000 } = {}) {
  if (header === undefined || header === null || String(header).trim() === '') return fallbackMs;
  const raw = String(header).trim();
  if (/^\d+$/.test(raw)) {
    return Math.min(Number(raw) * 1000, maxDelayMs);
  }
  const when = Date.parse(raw);
  if (Number.isNaN(when)) return fallbackMs;
  return Math.min(Math.max(when - now, 0), maxDelayMs);
}

export async function fetchWithRetry(url, options = {}, maxAttempts = 3) {
  let lastError;
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    const res = await fetch(url, options);
    if (res.status !== 429 && res.status < 500) return res;
    if (attempt === maxAttempts) return res;
    lastError = res;
    const delay = retryDelay(res.headers.get('retry-after'));
    await new Promise((resolve) => setTimeout(resolve, delay));
  }
  throw lastError;
}

What the code does

Structurally, expect the functions retryDelay and fetchWithRetry and nothing else.

Iteration happens inside for (let attempt = 1; attempt <= maxAttempts; attempt++) — everything outside it runs once. Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

What to watch for

  • Uses fetch, so it needs a browser context — it will not run as-is in Node without shims.
  • The guard res.status !== 429 && res.status < 500 short-circuits the flow with an early return when its condition holds.

Applying it

Signature: export function retryDelay(header, { now = Date.now()

Import retryDelay from the file and call it — the rest of the code is implementation detail.

Statements that matter

await new Promise((resolve) => setTimeout(resolve, delay));
if (header === undefined || header === null || String(header).trim() === '') return fallbackMs;
if (res.status !== 429 && res.status < 500) return res;

Interactive Tools for This Topic

FAQ

Does this work in a bare project with no dependencies file?
Yes — a bare project runs it as-is, since nothing needs declaring. The file defines `retryDelay`, `fetchWithRetry` at load time.