HomePremium · ₹1199
← All questions

Retry a failing API call with backoff

Medium
Asked at:UberRazorpay
Was this asked in an interview?

Retry a flaky async operation a limited number of times with exponential backoff before giving up.

Problem

Network calls fail transiently — a request times out, a server hiccups, a rate limit trips. Instead of failing instantly, resilient clients retry a few times with increasing delays (exponential backoff) so they don't stampede a struggling server.

Implement retry(fn, retries, delay) where:

  • fn is a function returning a promise (the operation to attempt).
  • On rejection, wait delay ms and try again, doubling the delay each time (backoff).
  • Give up after retries additional attempts and reject with the last error.
  • Resolve as soon as any attempt succeeds.

Note: the total number of calls is retries + 1 (the initial try plus the retries).

Input

let tries = 0;
const flaky = () =>
  new Promise((res, rej) => (++tries < 3 ? rej("fail " + tries) : res("ok")));

retry(flaky, 5, 100).then(console.log); // succeeds on the 3rd attempt

Expected output

  • Resolves with "ok" after 3 attempts.

Implement from scratch:

function retry(fn, retries = 3, delay = 500) {
  // Your code here
}
Retry a failing API call with backoff — JavaScript Interview Question | Mentoxis