go-backoff

A library to retry callback using Exponential Backoff delay strategy.
Try imagine obvious situation. You app has to retrieve an Url, like for example:
resp, err := http.Get(url)
In an ideal world, you get your response and continue. In a real world, it might fail sometimes. In such a situation you probably want to retry the attempt, as internet might be down for a moment, or whatever else. That's exact situation where backoff.Try() helps. Let's see the example above in a new perspective:
var body []byte
err := backoff.Try(func() (err error) {
resp, err := http.Get("https://example.com")
if err != nil {
return
}
defer resp.Body.Close()
body, err = ioutil.ReadAll(resp.Body)
return
})
The Try() function will, wonder of wonders, tries to execute given callback until the result is successful (in other words, returned error is nil). It will not try it more than by default 3 attempts. It waits between each attempt 100ms * 2^attempt_counter + random_ms_not_bigger_than_100ms.
The amount of attempts as delay base unit is configurable, of course. Let's see it in action:
err := backoff.Try(
myRetriableFunc,
backoff.MaxAttempts(7),
backoff.DelayUnit(2 * time.Second),
)
For your convenience, there are few more options to use:
err := backoff.Try(
myRetriableFunc,
backoff.OnRetry(func (err error) {
log.Error(err)
}),
backoff.RetryIf(func (err error) bool {
return IsThereAReasonToContinueToTry()
}),
)
Hansate Rahen