Skip to content

Commit

Permalink
prevent math overflow in backoff calculation (#21)
Browse files Browse the repository at this point in the history
  • Loading branch information
eli-darkly authored Mar 28, 2020
1 parent 1caf281 commit a78f536
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
7 changes: 2 additions & 5 deletions retry_delay.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,8 @@ func newDefaultBackoff(maxDelay time.Duration) backoffStrategy {
}

func (s defaultBackoffStrategy) applyBackoff(baseDelay time.Duration, retryCount int) time.Duration {
d := time.Duration(int64(baseDelay) * int64(math.Pow(2, float64(retryCount))))
if d > s.maxDelay {
return s.maxDelay
}
return d
d := math.Min(float64(baseDelay)*math.Pow(2, float64(retryCount)), float64(s.maxDelay))
return time.Duration(d)
}

type defaultJitterStrategy struct {
Expand Down
17 changes: 17 additions & 0 deletions retry_delay_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,3 +87,20 @@ func TestBackoffResetInterval(t *testing.T) {
d3 := r.NextRetryDelay(t5)
assert.Equal(t, d0, d3)
}

func TestBackoffAndJitterWorkWithHighRetryCount(t *testing.T) {
// This test verifies that we do not get numeric overflow errors due to using a very high exponential
// backoff number in calculations before it has been pinned to the maximum value. The jitter algorithm
// uses 63-bit values, so it will fail if there is a time.Duration value greater than about 292 years,
// which is unlikely to be a desirable backoff interval.
d0 := time.Second
max := 365 * 200 * 24 * time.Hour // 200 years
retryCount := 35 // 2^35 seconds exceeds a 63-bit count of nanoseconds

backoff := newDefaultBackoff(max)
jitter := newDefaultJitter(0.5, 1)

d1 := backoff.applyBackoff(d0, retryCount)
_ = jitter.applyJitter(d1)
// No assertion - the test just needs to not panic.
}

0 comments on commit a78f536

Please sign in to comment.