-
Notifications
You must be signed in to change notification settings - Fork 1
/
jitter.go
52 lines (41 loc) · 1.2 KB
/
jitter.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package helpers
import (
"math"
"math/rand"
"time"
)
// JitterBackoff Return capped exponential backoff with jitter. It is useful for http client when you want to retry request.
// http://www.awsarchitectureblog.com/2015/03/backoff.html
// An example use case:
// for i := 0; i <= retryCount; i++ {
// resp, err := http.Get("https://retail-ai.jp")
// if err == nil {
// return nil
// }
// // Don't need to wait when no retries left.
// if i == retryCount {
// return err
// }
// waitTime := helpers.JitterBackoff(time.Duration(100) * time.Millisecond, time.Duration(2000) * time.Millisecond, i)
// select {
// case <-time.After(waitTime):
// case <-c.Done():
// return c.Err()
// }
// }
func JitterBackoff(min, max time.Duration, attempt int) time.Duration {
base := float64(min)
capLevel := float64(max)
temp := math.Min(capLevel, base*math.Exp2(float64(attempt)))
ri := time.Duration(temp / 2)
result := randDuration(ri)
if result < min {
result = min
}
return result
}
func randDuration(center time.Duration) time.Duration {
var ri = int64(center)
var jitter = rand.Int63n(ri)
return time.Duration(math.Abs(float64(ri + jitter)))
}