-
Notifications
You must be signed in to change notification settings - Fork 0
/
backoff.go
37 lines (32 loc) · 1.05 KB
/
backoff.go
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
package utils
import (
"math/rand"
"time"
)
// BackOff computes the next back-off duration
type BackOff func(currentRetryCount int) time.Duration
// ExponentialBackOff computes an exponential back-off
func ExponentialBackOff(minTimeout time.Duration) BackOff {
return func(currentRetryCount int) time.Duration {
jitter := rand.Float64()
jitterMax := 200 * time.Millisecond
if currentRetryCount < 1 {
currentRetryCount = 1
}
strategy := 1 << (currentRetryCount - 1)
backoff := (float64(strategy) * float64(minTimeout.Nanoseconds())) + (jitter * float64(jitterMax.Nanoseconds()))
return time.Duration(backoff)
}
}
// LinearBackOff computes a linear back-off
func LinearBackOff(minTimeout time.Duration) BackOff {
return func(currentRetryCount int) time.Duration {
jitter := rand.Float64()
jitterMax := 200 * time.Millisecond
if currentRetryCount < 1 {
currentRetryCount = 1
}
backoff := (float64(currentRetryCount) * float64(minTimeout.Nanoseconds())) + (jitter * float64(jitterMax.Nanoseconds()))
return time.Duration(backoff)
}
}