Skip to content
This repository has been archived by the owner on Nov 11, 2024. It is now read-only.

Exponential backoff does the exact opposite of what it should do #127

Open
the80srobot opened this issue Dec 11, 2022 · 3 comments
Open

Comments

@the80srobot
Copy link

the80srobot commented Dec 11, 2022

Exponential backoff is supposed to wait longer each successive time it's used. Instead, your implementation returns progressively shorter intervals.

For example, when used this way, NextBackoff will return first 500 ms and then 100 ms which is obviously wrong.

expb := backoff.NewExponentialBackOff()
expb.InitialInterval = 100 * time.Millisecond
expb.MaxInterval = 15 * time.Second
expb.Multiplier = 2
expb.RandomizationFactor = 0
@craigpastro
Copy link

I remember seeing in the following issue #30 that InitialInterval should not be set after ExponentialBackOff is created. I assume that it is still relevant. It is certainly not obvious though.

@Likhi
Copy link

Likhi commented May 11, 2023

With v4.2.1:

func back() {
	ctx, cancel := context.WithTimeout(context.TODO(), 20*time.Second)
	defer cancel()

	expb := backoff.NewExponentialBackOff()

	expb.InitialInterval = 1000 * time.Millisecond
	expb.MaxInterval = 15 * time.Second
	expb.Multiplier = 1.2
	expb.RandomizationFactor = 0

	fmt.Println("first backoff", expb.NextBackOff(), "\n")

	err := backoff.Retry(func() error {
		fmt.Println("elapsed", expb.GetElapsedTime())
		fmt.Println("next backoff", expb.NextBackOff(), "\n")

		select {
		case <-ctx.Done():
			return nil
		default:
			return errors.New("timeout not met")
		}

	}, expb)

	if err != nil {
		//something
	}
}

Results in:

first backoff 500ms

elapsed 0s
next backoff 1s

elapsed 1.2044503s
next backoff 1.44s

elapsed 2.9426398s
next backoff 2.0736s

elapsed 5.443746s
next backoff 2.985984s

elapsed 9.0350991s
next backoff 4.29981696s

elapsed 14.203882s
next backoff 6.191736422s

elapsed 21.6420095s
next backoff 8.916100447s

@stevenh
Copy link

stevenh commented Jul 24, 2024

I believe you need to Reset() see: https://go.dev/play/p/jgS8nvUDh5z

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants