Implement a retry policy object
Implement a retry policy object in JavaScript: a reusable description of attempts and delays that wraps any async call. Node.js 24.
Retry logic scattered in several places drifts apart. A policy object holds the rules once, and run applies them to any async function.
const policy = {
attempts: 3,
delayMs: (attempt) => 100 * 2 ** attempt,
shouldRetry: (error) => error.retryable === true,
};
async function run(task, { attempts, delayMs, shouldRetry }) {
for (let attempt = 0; ; attempt++) {
try {
return await task(attempt);
} catch (error) {
if (attempt + 1 >= attempts || !shouldRetry(error)) throw error;
console.log(`attempt ${attempt + 1} failed, waiting ${delayMs(attempt)}ms`);
await new Promise((resolve) => setTimeout(resolve, delayMs(attempt)));
}
}
}
const result = await run(async (attempt) => {
if (attempt < 2) throw Object.assign(new Error('busy'), { retryable: true });
return 'done';
}, policy);
console.log(result);attempt 1 failed, waiting 100ms
attempt 2 failed, waiting 200ms
doneThe delays double with each attempt, and shouldRetry lets a validation error fail at once. The task receives the attempt number, which helps logging.
Add random jitter to the delay when many clients retry together, or they all retry in the same instant. Retry only calls that are safe to repeat. The example uses top-level await, so it needs an ES module.