Created
February 25, 2017 13:17
-
-
Save lmas/6d3ba904c691a3e10d966d09d1c20c34 to your computer and use it in GitHub Desktop.
Increasing timeouts (linear or exponential) with optional 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
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