Skip to content

Commit

Permalink
Bugfix/jitter (#66)
Browse files Browse the repository at this point in the history
* bugfix: Update jitter time on error

Previously the jitter time was never updated, which means that it was
always 1 ns.

* Switch jitter to use time.Duration

This makes it clear that the jitter is tiny, between 1 and 10 ns.

* Change jitter times to be (50ms, 5s)

* Let decorrelatedJitter.calc() return Duration
  • Loading branch information
ecksun authored and brian-brazil committed Dec 5, 2019
1 parent d946edf commit 8f4561f
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 13 deletions.
26 changes: 16 additions & 10 deletions client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"crypto/x509"
"fmt"
"io/ioutil"
"math"
"math/rand"
"net"
"net/http"
Expand Down Expand Up @@ -191,26 +190,33 @@ func loop(c Coordinator, client *http.Client) error {

// decorrelated Jitter increases the maximum jitter based on the last random value.
type decorrelatedJitter struct {
duration float64 // sleep time
min float64 // min sleep time
cap float64 // max sleep time
duration time.Duration // sleep time
min time.Duration // min sleep time
cap time.Duration // max sleep time
}

func newJitter() decorrelatedJitter {
rand.Seed(time.Now().UnixNano())
return decorrelatedJitter{
duration: 1,
min: 1,
cap: 10,
min: 50 * time.Millisecond,
cap: 5 * time.Second,
}
}

func (d *decorrelatedJitter) calc() {
d.duration = math.Min(d.cap, d.min+rand.Float64()*(d.duration*3-d.min))
func (d *decorrelatedJitter) calc() time.Duration {
change := rand.Float64() * float64(d.duration*time.Duration(3)-d.min)
d.duration = d.min + time.Duration(change)
if d.duration > d.cap {
d.duration = d.cap
}
if d.duration < d.min {
d.duration = d.min
}
return d.duration
}

func (d *decorrelatedJitter) sleep() {
time.Sleep(time.Duration(d.duration))
time.Sleep(d.calc())
}

func main() {
Expand Down
8 changes: 5 additions & 3 deletions client/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@ import (

func TestJitter(t *testing.T) {
jitter := newJitter()
jitter.calc()
if !(jitter.min <= jitter.duration || jitter.duration <= jitter.cap) {
t.Fatal("invalid jitter value: ", jitter.duration)
for i := 0; i < 100000; i++ {
duration := jitter.calc()
if !(jitter.min <= duration || duration <= jitter.cap) {
t.Fatal("invalid jitter value: ", duration)
}
}
}

Expand Down

0 comments on commit 8f4561f

Please sign in to comment.