Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix exponential backoff algorithm truncating exponential factor #14

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion backoff/backoff.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func Linear(factor time.Duration) Algorithm {
// calculated as the given base raised to the attempt number.
func Exponential(factor time.Duration, base float64) Algorithm {
return func(attempt uint) time.Duration {
return (factor * time.Duration(math.Pow(base, float64(attempt))))
return time.Duration(float64(factor) * math.Pow(base, float64(attempt)))
}
}

Expand Down
16 changes: 8 additions & 8 deletions backoff/backoff_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,13 @@ func TestLinear(t *testing.T) {

func TestExponential(t *testing.T) {
const duration = time.Second
const base = 3
const base = 1.5

algorithm := Exponential(duration, base)

for i := uint(0); i < 10; i++ {
result := algorithm(i)
expected := time.Duration(math.Pow(base, float64(i))) * duration
expected := time.Duration(math.Pow(base, float64(i)) * float64(duration))

if result != expected {
t.Errorf("algorithm expected to return a %s duration, but received %s instead", expected, result)
Expand Down Expand Up @@ -132,7 +132,7 @@ func ExampleLinear() {
}

func ExampleExponential() {
algorithm := Exponential(15*time.Millisecond, 3)
algorithm := Exponential(15*time.Millisecond, 1.5)

for i := uint(1); i <= 5; i++ {
duration := algorithm(i)
Expand All @@ -141,11 +141,11 @@ func ExampleExponential() {
}

// Output:
// #1 attempt: 45ms
// #2 attempt: 135ms
// #3 attempt: 405ms
// #4 attempt: 1.215s
// #5 attempt: 3.645s
// #1 attempt: 22.5ms
// #2 attempt: 33.75ms
// #3 attempt: 50.625ms
// #4 attempt: 75.9375ms
// #5 attempt: 113.90625ms
}

func ExampleBinaryExponential() {
Expand Down