10LOC

#backoff

Node.jsintermediate

Retrying a flaky async call with exponential backoff

export const retryWithBackoff = async <T>(fn: () => Promise<T>, maxAttempts = 5, baseDelayMs = 200): Promise<T> => {
  for (let attempt = 1; ; attempt++) {
    try {
      return await fn();
    } catch (err) {

Retry a failing async call with a delay that doubles each attempt plus random jitter, so retries don't pile onto a struggling service in lockstep.