Skip to content

Commit

Permalink
Updated backoff
Browse files Browse the repository at this point in the history
  • Loading branch information
alexkonst committed Sep 4, 2024
1 parent c5a905a commit 4acf46a
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 25 deletions.
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

0 comments on commit 4acf46a

Please sign in to comment.