Skip to main content

Exponential backoff

Exponential backoff is a technique used in computer systems to handle retries and avoid overwhelming services. We can easily implement this by using the `retry` utility provided by the standard library.

Edit on Github
Import the 'retry' utility from '@std/async'.
import { retry, RetryError, type RetryOptions } from "jsr:@std/async";
A function that logs 'hello world' to the console and returns a rejected Promise.
const fn = () => {
  console.log("hello world");
  return Promise.reject("rejected");
};
Configuration for retry options which will make sure that the function will be called at max 3 times before throwing an error. The first call to the function will be made immediately, the second call will happen after a delay of 10ms and the third/final call will be made after a delay of 20ms.
const options: RetryOptions = {
  maxAttempts: 3,
  minTimeout: 10,
  multiplier: 2,
  jitter: 0,
};

try {
Wrap the function with the 'retry' utility along with the retry configuration.
  await retry(fn, options);
} catch (err) {
When max attempts are exhausted, a RetryError is thrown containing the original rejection reason 'rejected' as its cause property.
  if (err instanceof RetryError) {
    console.log("Retry error :", err.message);
    console.log("Error cause :", err.cause);
  }
}

Run this example locally using the Deno CLI:

deno run https://docs.deno.com/examples/exponential-backoff.ts