-
Notifications
You must be signed in to change notification settings - Fork 366
Expand file tree
/
Copy pathexponential_backoff.ts
More file actions
45 lines (41 loc) · 1.59 KB
/
Copy pathexponential_backoff.ts
File metadata and controls
45 lines (41 loc) · 1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* @title Exponential backoff
* @difficulty intermediate
* @tags cli, deploy, web
* @run <url>
* @resource {https://en.wikipedia.org/wiki/Exponential_backoff} Wikipedia: Exponential backoff
* @resource {https://jsr.io/@std/async/doc/~/retry} Doc: @std/async > retry
* @group Advanced
*
* 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 '@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);
}
}