Retry Exponential Backoff With Jitter

Retry an async function with exponential backoff full jitter and max attempts cap to handle transient errors without thundering herd.

JavascriptResilience

Code

javascriptsnippet
1 line
export async function retryWithBackoff(fn,{maxAttempts=5,baseDelay=100,maxDelay=30000,shouldRetry=()=>true}={}){let attempt=0,lastErr;while(attempt<maxAttempts){try{return await fn(attempt);}catch(e){lastErr=e;attempt++;if(attempt>=maxAttempts||!shouldRetry(e))break;const exp=Math.min(maxDelay,baseDelay*2**attempt);await new Promise(r=>setTimeout(r,Math.random()*exp));}}throw lastErr;}

What the code does

Count the function retryWithBackoff as the entire surface area of Retry Exponential Backoff With Jitter.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

Applying it

Entry signature: export async function retryWithBackoff(fn,{maxAttempts=5,baseDelay=100,maxDelay=30000,shouldRetry=()

Callers only need retryWithBackoff — everything else stays internal.

Interactive Tools for This Topic

FAQ

What does the package manager see?
An empty dependency file. The snippet imports nothing that needs fetching. The file defines `retryWithBackoff` at load time.