Last active
November 27, 2021 01:36
-
-
Save BondAnthony/82467930b192b6777bc876b5588fb942 to your computer and use it in GitHub Desktop.
Exponential backoff sample code written in Go.
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
package main | |
import ( | |
"fmt" | |
"math/rand" | |
"time" | |
"github.com/cenkalti/backoff/v4" | |
) | |
const ( | |
MaxElapsedTime = 15 * time.Minute | |
MaxInterval = 120 * time.Second | |
JitterRange = 5 | |
) | |
func fail() error { | |
// Sample code that would normally make the request | |
// to the api would go here. | |
return fmt.Errorf("request failed") | |
} | |
func main() { | |
// jitter the initial interval | |
rand.Seed(time.Now().UnixNano()) | |
randomJitter := rand.Intn(JitterRange) + 1 | |
// override default values for NewExponentialBackOff() | |
exp := backoff.NewExponentialBackOff() | |
exp.MaxElapsedTime = MaxElapsedTime | |
exp.InitialInterval = time.Duration(randomJitter) * time.Second | |
exp.MaxInterval = MaxInterval | |
// notify function that will log when an error occurs. | |
notify := func(err error, time time.Duration) { | |
fmt.Printf("connection error %+v, retrying in %s\n", err, time) | |
} | |
// connect function that will run our request code. | |
connect := func() error { | |
return fail() | |
} | |
// backoff.RetryNotify() call that brings it altogether and handles the backoff. | |
err := backoff.RetryNotify(connect, exp, notify) | |
if err != nil { | |
fmt.Printf("backoff %+v\n", err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment