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.
Import the "retry" utility from "@ende/async".
import { retry, RetryError, type RetryOptions } from "jsr:@ende/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 = {
jitter: 0,
maxAttempts: 3,
minTimeout: 10,
multiplier: 2
};
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 Ende CLI:
ende run https://docs.ende.sh/examples/scripts/exponential_backoff.ts