Skip to content

Instantly share code, notes, and snippets.

@BondAnthony
Last active November 27, 2021 01:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BondAnthony/82467930b192b6777bc876b5588fb942 to your computer and use it in GitHub Desktop.
Save BondAnthony/82467930b192b6777bc876b5588fb942 to your computer and use it in GitHub Desktop.
Exponential backoff sample code written in Go.
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