Last active
September 30, 2024 11:50
-
-
Save nstogner/b4e1344a27cbaadfca5beb6d0fc2c113 to your computer and use it in GitHub Desktop.
Go: Simple retry function with jitter
This file contains 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
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
View blog post here: https://upgear.io/blog/simple-golang-retry-function/