Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updated backoff #159

Merged
merged 1 commit into from
Sep 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@ulms/api-clients",
"version": "7.16.0",
"version": "7.17.0",
"description": "JavaScript API clients for ULMS platform",
"keywords": [],
"homepage": "https://github.com/foxford/ulms-api-clients-js#readme",
Expand Down
32 changes: 10 additions & 22 deletions src/backoff.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,10 @@
const FACTOR = 2
const MIN_DELAY = 500 // 500ms
const MAX_DELAY = 5 * 60 * 1000 // 5m
const RANDOM_ADDITIVE_MAX = 1000 // 1s
const MAX_RANDOM_ADDITIVE = 2000 // 2s

// get milliseconds as value
const MILLISECONDS_IN_SECOND = 1000

function getRandomIntInclusive(min, max) {
const minValue = Math.ceil(min)
const maxValue = Math.floor(max)

// The maximum is inclusive and the minimum is inclusive
return Math.floor(Math.random() * (maxValue - minValue + 1) + minValue)
}

class Backoff {
constructor() {
this.counter = 0
Expand All @@ -26,18 +18,14 @@ class Backoff {
}

next() {
if (this.delay < MAX_DELAY) {
const randomAdditive = getRandomIntInclusive(0, RANDOM_ADDITIVE_MAX)

// first delay always equals to randomAdditive
this.delay =
this.counter === 0
? randomAdditive
: Math.min(
MILLISECONDS_IN_SECOND * FACTOR ** this.counter + randomAdditive,
MAX_DELAY,
)
}
this.delay = Math.min(
Math.round(
MIN_DELAY +
MILLISECONDS_IN_SECOND * Math.expm1(this.counter) +
MAX_RANDOM_ADDITIVE * Math.random(),
),
MAX_DELAY,
)

this.counter += 1
}
Expand Down