Retry-After Header Backoff
Interpret a Retry-After header as seconds or an HTTP date and cap the delay before the next retry attempt.
Code
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 < 500short-circuits the flow with an earlyreturnwhen 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
HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.