snippetjavascriptModeratepending
Retry async function with exponential backoff — reusable wrapper
Viewed 0 times
retryexponential backoffjitterasync retrynetwork retrytransient error
browsernodejs
Problem
Need a reusable retry wrapper for async functions that implements exponential backoff with jitter. Should be configurable for max retries, base delay, and which errors to retry.
Solution
Generic retry wrapper that works with any async function. Implements exponential backoff with optional jitter and configurable retry predicate.
Code Snippets
Configurable retry with exponential backoff
async function retry(fn, opts = {}) {
const {
retries = 3,
baseDelay = 1000,
maxDelay = 30000,
jitter = true,
shouldRetry = () => true,
} = opts;
let lastError;
for (let attempt = 0; attempt <= retries; attempt++) {
try {
return await fn(attempt);
} catch (err) {
lastError = err;
if (attempt === retries || !shouldRetry(err, attempt)) throw err;
let delay = Math.min(baseDelay * 2 ** attempt, maxDelay);
if (jitter) delay += Math.random() * baseDelay;
await new Promise(r => setTimeout(r, delay));
}
}
throw lastError;
}
// Usage
const data = await retry(
() => fetch('/api/data').then(r => {
if (!r.ok) throw new Error(`HTTP ${r.status}`);
return r.json();
}),
{
retries: 3,
shouldRetry: (err) => !err.message.includes('HTTP 4'),
}
);Revisions (0)
No revisions yet.