Codebase list golang-github-go-kit-kit / 91c58cc
Add backoff package and fix Consul CPU usage (#635) * Add backoff package Justification for jitter and growth factor: https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/. Add backoff to the Consul instancer loop. Fixes https://github.com/go-kit/kit/issues/627. * Revert "Add backoff package" This reverts commit 924501ae1fcfadaa27593e9c019283412c513928. * Get rid of external package and update exponential * Add instancer backoff * Fix old exponential name * Add doc comment * Fixup & respond to review Nico Tonozzi authored 6 years ago Peter Bourgon committed 6 years ago
2 changed file(s) with 15 addition(s) and 2 deletion(s). Raw diff Collapse all Expand all
22 import (
33 "fmt"
44 "io"
5 "time"
56
67 consul "github.com/hashicorp/consul/api"
78
89 "github.com/go-kit/kit/log"
910 "github.com/go-kit/kit/sd"
1011 "github.com/go-kit/kit/sd/internal/instance"
12 "github.com/go-kit/kit/util/conn"
1113 )
1214
1315 const defaultIndex = 0
5860 var (
5961 instances []string
6062 err error
63 d time.Duration = 10 * time.Millisecond
6164 )
6265 for {
6366 instances, lastIndex, err = s.getInstances(lastIndex, s.quitc)
6669 return // stopped via quitc
6770 case err != nil:
6871 s.logger.Log("err", err)
72 time.Sleep(d)
73 d = conn.Exponential(d)
6974 s.cache.Update(sd.Event{Err: err})
7075 default:
7176 s.cache.Update(sd.Event{Instances: instances})
77 d = 10 * time.Millisecond
7278 }
7379 }
7480 }
11
22 import (
33 "errors"
4 "math/rand"
45 "net"
56 "time"
67
102103 case conn = <-connc:
103104 if conn == nil {
104105 // didn't work
105 backoff = exponential(backoff) // wait longer
106 backoff = Exponential(backoff) // wait longer
106107 reconnectc = m.after(backoff) // try again
107108 } else {
108109 // worked!
131132 return conn
132133 }
133134
134 func exponential(d time.Duration) time.Duration {
135 // Exponential takes a duration and returns another one that is twice as long, +/- 50%. It is
136 // used to provide backoff for operations that may fail and should avoid thundering herds.
137 // See https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/ for rationale
138 func Exponential(d time.Duration) time.Duration {
135139 d *= 2
140 jitter := rand.Float64() + 0.5
141 d = time.Duration(int64(float64(d.Nanoseconds()) * jitter))
136142 if d > time.Minute {
137143 d = time.Minute
138144 }
139145 return d
146
140147 }
141148
142149 // ErrConnectionUnavailable is returned by the Manager's Write method when the