Deviopath › Node.js

Retry with Exponential Backoff

Medium · Async

Network calls from a Node server fail now and then, so we retry them. The starter has createFlakyTask(failTimes): it returns an async task() that rejects on its first failTimes calls (with Error("Attempt <n> failed")) and then resolves with "success on call <n>".

Write async withRetry(failTimes, maxAttempts) that creates one task and calls it until it succeeds or maxAttempts calls were made.

- Between attempts, wait with exponential backoff: 1 ms after the first failure, then 2, 4, 8... (use the sleep helper). Real apps use bigger delays, often with random jitter.

- Do not wait after the last attempt.

Return { ok: true, attempts, value, waits } on success or { ok: false, attempts, error, waits } where error is the last error message and waits lists the delays you used.

Next: Timeout with Cleanup