Skip to content

Commit

Permalink
Add conditional backoff
Browse files Browse the repository at this point in the history
  • Loading branch information
jakubuid committed Aug 30, 2024
1 parent c14d289 commit 4b00662
Show file tree
Hide file tree
Showing 5 changed files with 32 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -106,15 +106,19 @@ internal class Connection(
transitionTo(Connected(session = session))
}
on<OnWebSocket.Terminate>() {
val backoffDuration = backoffStrategy.backoffDurationMillisAt(retryCount)
val timerDisposable = scheduleRetry(backoffDuration)
transitionTo(
WaitingToRetry(
timerDisposable = timerDisposable,
retryCount = retryCount,
retryInMillis = backoffDuration
if (backoffStrategy.shouldBackoff) {
val backoffDuration = backoffStrategy.backoffDurationMillisAt(retryCount)
val timerDisposable = scheduleRetry(backoffDuration)
transitionTo(
WaitingToRetry(
timerDisposable = timerDisposable,
retryCount = retryCount,
retryInMillis = backoffDuration
)
)
)
} else {
transitionTo(Disconnected)
}
}
}
state<Connected> {
Expand All @@ -135,15 +139,19 @@ internal class Connection(
transitionTo(Destroyed)
}
on<OnWebSocket.Terminate>() {
val backoffDuration = backoffStrategy.backoffDurationMillisAt(0)
val timerDisposable = scheduleRetry(backoffDuration)
transitionTo(
WaitingToRetry(
timerDisposable = timerDisposable,
retryCount = 0,
retryInMillis = backoffDuration
if (backoffStrategy.shouldBackoff) {
val backoffDuration = backoffStrategy.backoffDurationMillisAt(0)
val timerDisposable = scheduleRetry(backoffDuration)
transitionTo(
WaitingToRetry(
timerDisposable = timerDisposable,
retryCount = 0,
retryInMillis = backoffDuration
)
)
)
} else {
transitionTo(Disconnected)
}
}
}
state<Disconnecting> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,6 @@ interface BackoffStrategy {
* Returns a duration in milliseconds.
*/
fun backoffDurationMillisAt(retryCount: Int): Long

var shouldBackoff: Boolean
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,6 @@ class ExponentialBackoffStrategy(
initialDurationMillis.toDouble() * Math.pow(2.0, retryCount.toDouble())
)
.toLong()

override var shouldBackoff: Boolean = true
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ class ExponentialWithJitterBackoffStrategy(
return duration.withJitter()
}

override var shouldBackoff: Boolean = true

private fun Long.withJitter(): Long = (0..this).random()

private fun ClosedRange<Long>.random() = random.nextInt((endInclusive - start).toInt()) + start
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,6 @@ class LinearBackoffStrategy(
}

override fun backoffDurationMillisAt(retryCount: Int): Long = durationMillis

override var shouldBackoff: Boolean = true
}

0 comments on commit 4b00662

Please sign in to comment.