Tweak backoff

This commit is contained in:
Vladimir Mihailenco 2020-07-28 15:42:38 +03:00
parent dd8e70ad43
commit 6e3d4a53c6
1 changed files with 7 additions and 10 deletions

View File

@ -6,20 +6,17 @@ import (
"golang.org/x/exp/rand" "golang.org/x/exp/rand"
) )
// Retry backoff with jitter sleep to prevent overloaded conditions during intervals
// https://www.awsarchitectureblog.com/2015/03/backoff.html
func RetryBackoff(retry int, minBackoff, maxBackoff time.Duration) time.Duration { func RetryBackoff(retry int, minBackoff, maxBackoff time.Duration) time.Duration {
if retry < 0 { if retry < 0 {
retry = 0 panic("not reached")
} }
backoff := minBackoff << uint(retry) d := minBackoff << uint(retry)
if backoff > maxBackoff || backoff < minBackoff { d = minBackoff + time.Duration(rand.Int63n(int64(d)))
backoff = maxBackoff
if d > maxBackoff || d < minBackoff {
d = maxBackoff
} }
if backoff == 0 { return d
return 0
}
return time.Duration(rand.Int63n(int64(backoff)))
} }