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

snippet
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;}