Skip to content

Instantly share code, notes, and snippets.

@lmas
Created February 25, 2017 13:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lmas/6d3ba904c691a3e10d966d09d1c20c34 to your computer and use it in GitHub Desktop.
Save lmas/6d3ba904c691a3e10d966d09d1c20c34 to your computer and use it in GitHub Desktop.
Increasing timeouts (linear or exponential) with optional jitter
package main
// Heavely based on: https://github.com/sethgrid/pester
import (
"fmt"
"math"
"math/rand"
"time"
)
func main() {
rand.Seed(time.Now().Unix())
for i := 0; i < 10; i++ {
//d := linearBackoff(i)
d := exponentialBackoff(i)
j := jitter(d)
fmt.Printf("%d\t %s\t %s\n", i, d, j)
}
}
func jitter(d time.Duration) time.Duration {
ms := int(d.Nanoseconds() / 1000000)
maxJitter := ms / 3
jitter := rand.Intn(maxJitter + 1)
if rand.Intn(2) == 1 {
ms += jitter
} else {
ms -= jitter
}
return time.Duration(ms) * time.Millisecond
}
func linearBackoff(i int) time.Duration {
return time.Duration(i) * time.Second
}
func exponentialBackoff(i int) time.Duration {
d := math.Pow(2, float64(i))
return time.Duration(d) * time.Second
}
//func linearBackoffJitter(i int) time.Duration {
//return jitter(linear(i))
//}
//func exponentialBackoffJitter(i int) time.Duration {
//return jitter(exp(i))
//}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment