Skip to content

Instantly share code, notes, and snippets.

@nstogner
Last active September 30, 2024 11:50
Show Gist options
  • Save nstogner/b4e1344a27cbaadfca5beb6d0fc2c113 to your computer and use it in GitHub Desktop.
Save nstogner/b4e1344a27cbaadfca5beb6d0fc2c113 to your computer and use it in GitHub Desktop.
Go: Simple retry function with jitter
func init() {
rand.Seed(time.Now().UnixNano())
}
func retry(attempts int, sleep time.Duration, f func() error) error {
if err := f(); err != nil {
if s, ok := err.(stop); ok {
// Return the original error for later checking
return s.error
}
if attempts--; attempts > 0 {
// Add some randomness to prevent creating a Thundering Herd
jitter := time.Duration(rand.Int63n(int64(sleep)))
sleep = sleep + jitter/2
time.Sleep(sleep)
return retry(attempts, 2*sleep, f)
}
return err
}
return nil
}
type stop struct {
error
}
@nstogner
Copy link
Author

nstogner commented Nov 21, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment