Retry with full jitter
When an API goes down, every client fails at once and, with fixed backoff, retries at the same instant — a thundering herd that keeps the service down. AWS's 'full jitter' fix is to pick a random wait between zero and the backoff ceiling.
Implement retryWithJitter(task, options) where options may contain attempts (default 3), baseDelay (default 100) and random (default Math.random). Call task(attemptIndex) with the zero-based attempt number. Resolve with its value as soon as an attempt succeeds. After a failed attempt at index i, if further attempts remain, call random() exactly once and wait Math.floor(random() * baseDelay * 2 ** i) milliseconds before the next attempt. After the final attempt fails, reject with that last error and do not call random again.
What it has to do
- Call
taskwith the zero-based attempt index. - Resolve as soon as an attempt succeeds, without waiting again.
- Call
randomexactly once per wait, and never after the final attempt. - Wait
Math.floor(random() * baseDelay * 2 ** attemptIndex)milliseconds between attempts. - Reject with the error from the final attempt.
Your workspace
Ready to check it?
5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.
AI Crack & Solution Assist
Stuck? Get instant AI hints or break down the optimal solution.
Stuck? The javascript course covers everything this challenge needs.