Loading content…
Loading content…
Write an async fetch utility in TypeScript that loads records from an endpoint. If the HTTP request fails (due to status codes 5xx or network drops), retry the action up to 3 times, adding exponential backoff delays between attempts.
Expected Output
An async helper function `fetchWithRetry(url, options, retries, delay)` returning target payloads.
Click to toggle the recommended code solution
Architectural Explanation
The recursive function tracks retry counters. Exponential backoff is achieved by doubling the delay parameter on each subsequent attempt. It safely halts on client-side 4xx issues.Code Snippet
const sleep = (ms: number) => new Promise(res => setTimeout(res, ms));
export async function fetchWithRetry(
url: string,
options: RequestInit = {},
retries = 3,
delay = 1000
): Promise<any> {
try {
const res = await fetch(url, options);
if (!res.ok) {
if (res.status >= 500 && retries > 0) {
throw new Error(`Server error: ${res.status}`);
}
throw new Error(`Request failed with status ${res.status}`);
}
return await res.json();
} catch (err: any) {
if (retries > 0 && !err.message.includes("failed with status 4")) {
console.warn(`Attempt failed. Retrying in ${delay}ms...`);
await sleep(delay);
return fetchWithRetry(url, options, retries - 1, delay * 2);
}
throw err;
}
}How to pitch this solution during technical interviews
I design resilient API utilities by wrapping fetch in recursive try-catch blocks. If a request throws a network anomaly or 5xx code, I execute exponential delays using setTimeout promises, but halt retries on 4xx codes.