Created
November 2, 2021 19:22
-
-
Save efontan/8855d14b6dc9eb97f52bd717409bae28 to your computer and use it in GitHub Desktop.
Golang simply retrier with exponential backoff
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package retrier | |
import ( | |
"time" | |
"github.com/pkg/errors" | |
) | |
type backoffRetrier struct { | |
initialDelay time.Duration | |
maxRetries int | |
} | |
func NewExponentialBackoff(initialDelay time.Duration, maxRetries int) *backoffRetrier { | |
return &backoffRetrier{ | |
initialDelay: initialDelay, | |
maxRetries: maxRetries, | |
} | |
} | |
func (r *backoffRetrier) Retry(f func(attempt int) error) error { | |
var err error | |
retryDelay := r.initialDelay | |
for attempt := 0; attempt < r.maxRetries; attempt++ { | |
err = f(attempt) | |
if err == nil { | |
return nil | |
} | |
time.Sleep(retryDelay) | |
retryDelay = retryDelay * 2 | |
} | |
return errors.Wrap(err, "max retries reached") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment