├── .github └── workflows │ └── go-test.yml ├── LICENSE ├── README.md ├── backo.go ├── backo_test.go ├── go.mod └── go.sum /.github/workflows/go-test.yml: -------------------------------------------------------------------------------- 1 | name: Go Test 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | test: 7 | name: Run go test 8 | runs-on: ubuntu-latest 9 | 10 | steps: 11 | - name: Checkout code 12 | uses: actions/checkout@v2 13 | 14 | - name: Set up Go 15 | uses: actions/setup-go@v2 16 | with: 17 | go-version: 1.21 18 | 19 | - name: Run tests 20 | run: go test -v ./... 21 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Segment, Inc. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Backo [![GoDoc](http://godoc.org/github.com/segmentio/backo-go?status.png)](http://godoc.org/github.com/segmentio/backo-go) 2 | ----- 3 | 4 | > **Note** 5 | > Segment has paused maintenance on this project, but may return it to an active status in the future. Issues and pull requests from external contributors are not being considered, although internal contributions may appear from time to time. The project remains available under its open source license for anyone to use. 6 | 7 | Exponential backoff for Go (Go port of segmentio/backo). 8 | 9 | 10 | Usage 11 | ----- 12 | 13 | ```go 14 | import "github.com/segmentio/backo-go" 15 | 16 | // Create a Backo instance. 17 | backo := backo.NewBacko(milliseconds(100), 2, 1, milliseconds(10*1000)) 18 | // OR with defaults. 19 | backo := backo.DefaultBacko() 20 | 21 | // Use the ticker API. 22 | ticker := b.NewTicker() 23 | for { 24 | timeout := time.After(5 * time.Minute) 25 | select { 26 | case <-ticker.C: 27 | fmt.Println("ticked") 28 | case <- timeout: 29 | fmt.Println("timed out") 30 | } 31 | } 32 | 33 | // Or simply work with backoff intervals directly. 34 | for i := 0; i < n; i++ { 35 | // Sleep the current goroutine. 36 | backo.Sleep(i) 37 | // Retrieve the duration manually. 38 | duration := backo.Duration(i) 39 | } 40 | ``` 41 | 42 | License 43 | ------- 44 | 45 | ``` 46 | WWWWWW||WWWWWW 47 | W W W||W W W 48 | || 49 | ( OO )__________ 50 | / | \ 51 | /o o| MIT \ 52 | \___/||_||__||_|| * 53 | || || || || 54 | _||_|| _||_|| 55 | (__|__|(__|__| 56 | 57 | The MIT License (MIT) 58 | 59 | Copyright (c) 2015 Segment, Inc. 60 | 61 | Permission is hereby granted, free of charge, to any person obtaining a copy 62 | of this software and associated documentation files (the "Software"), to deal 63 | in the Software without restriction, including without limitation the rights 64 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 65 | copies of the Software, and to permit persons to whom the Software is 66 | furnished to do so, subject to the following conditions: 67 | 68 | The above copyright notice and this permission notice shall be included in all 69 | copies or substantial portions of the Software. 70 | 71 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 72 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 73 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 74 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 75 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 76 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 77 | SOFTWARE. 78 | ``` 79 | 80 | 81 | 82 | [1]: http://github.com/segmentio/backo-java 83 | [2]: http://repository.sonatype.org/service/local/artifact/maven/redirect?r=central-proxy&g=com.segment.backo&a=backo&v=LATEST 84 | -------------------------------------------------------------------------------- /backo.go: -------------------------------------------------------------------------------- 1 | package backo 2 | 3 | import ( 4 | "math" 5 | "math/rand" 6 | "time" 7 | ) 8 | 9 | type Backo struct { 10 | base time.Duration 11 | factor uint8 12 | jitter float64 13 | cap time.Duration 14 | } 15 | 16 | // Creates a backo instance with the given parameters 17 | func NewBacko(base time.Duration, factor uint8, jitter float64, cap time.Duration) *Backo { 18 | return &Backo{base, factor, jitter, cap} 19 | } 20 | 21 | // Creates a backo instance with the following defaults: 22 | // base: 100 milliseconds 23 | // factor: 2 24 | // jitter: 0 25 | // cap: 10 seconds 26 | func DefaultBacko() *Backo { 27 | return NewBacko(time.Millisecond*100, 2, 0, time.Second*10) 28 | } 29 | 30 | // Duration returns the backoff interval for the given attempt. 31 | func (backo *Backo) Duration(attempt int) time.Duration { 32 | duration := float64(backo.base) * math.Pow(float64(backo.factor), float64(attempt)) 33 | 34 | if backo.jitter != 0 { 35 | random := rand.Float64() 36 | deviation := math.Floor(random * backo.jitter * duration) 37 | if (int(math.Floor(random*10)) & 1) == 0 { 38 | duration = duration - deviation 39 | } else { 40 | duration = duration + deviation 41 | } 42 | } 43 | 44 | duration = math.Min(float64(duration), float64(backo.cap)) 45 | return time.Duration(duration) 46 | } 47 | 48 | // Sleep pauses the current goroutine for the backoff interval for the given attempt. 49 | func (backo *Backo) Sleep(attempt int) { 50 | duration := backo.Duration(attempt) 51 | time.Sleep(duration) 52 | } 53 | 54 | type Ticker struct { 55 | done chan struct{} 56 | C <-chan time.Time 57 | } 58 | 59 | func (b *Backo) NewTicker() *Ticker { 60 | c := make(chan time.Time, 1) 61 | ticker := &Ticker{ 62 | done: make(chan struct{}, 1), 63 | C: c, 64 | } 65 | 66 | go func() { 67 | for i := 0; ; i++ { 68 | select { 69 | case t := <-time.After(b.Duration(i)): 70 | c <- t 71 | case <-ticker.done: 72 | close(c) 73 | return 74 | } 75 | } 76 | }() 77 | 78 | return ticker 79 | } 80 | 81 | func (t *Ticker) Stop() { 82 | t.done <- struct{}{} 83 | } 84 | -------------------------------------------------------------------------------- /backo_test.go: -------------------------------------------------------------------------------- 1 | package backo 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | "testing" 7 | "time" 8 | 9 | "github.com/stretchr/testify/assert" 10 | ) 11 | 12 | // Tests default backo behaviour. 13 | func TestDefaults(t *testing.T) { 14 | backo := DefaultBacko() 15 | 16 | assert.Equal(t, milliseconds(100), backo.Duration(0)) 17 | assert.Equal(t, milliseconds(200), backo.Duration(1)) 18 | assert.Equal(t, milliseconds(400), backo.Duration(2)) 19 | assert.Equal(t, milliseconds(800), backo.Duration(3)) 20 | } 21 | 22 | // Tests backo does not exceed cap. 23 | func TestCap(t *testing.T) { 24 | backo := NewBacko(milliseconds(100), 2, 0, milliseconds(600)) 25 | 26 | assert.Equal(t, milliseconds(100), backo.Duration(0)) 27 | assert.Equal(t, milliseconds(200), backo.Duration(1)) 28 | assert.Equal(t, milliseconds(400), backo.Duration(2)) 29 | assert.Equal(t, milliseconds(600), backo.Duration(3)) 30 | } 31 | 32 | // Tests that jitter adds randomness. 33 | func TestJitter(t *testing.T) { 34 | defaultBacko := NewBacko(milliseconds(100), 2, 1, milliseconds(10*1000)) 35 | jitterBacko := NewBacko(milliseconds(100), 2, 1, milliseconds(10*1000)) 36 | 37 | // TODO: Check jittered durations are within a range. 38 | assert.NotEqual(t, jitterBacko.Duration(0), defaultBacko.Duration(0)) 39 | assert.NotEqual(t, jitterBacko.Duration(1), defaultBacko.Duration(1)) 40 | assert.NotEqual(t, jitterBacko.Duration(2), defaultBacko.Duration(2)) 41 | assert.NotEqual(t, jitterBacko.Duration(3), defaultBacko.Duration(3)) 42 | } 43 | 44 | func ExampleBacko_BackoffDefault() { 45 | b := DefaultBacko() 46 | ticker := b.NewTicker() 47 | 48 | for i := 0; i < 6; i++ { 49 | start := time.Now() 50 | select { 51 | case t := <-ticker.C: 52 | fmt.Println(nearest10Millis(t.Sub(start))) 53 | } 54 | } 55 | 56 | ticker.Stop() 57 | 58 | // Output: 59 | // 100 60 | // 200 61 | // 400 62 | // 800 63 | // 1600 64 | // 3200 65 | } 66 | 67 | func nearest10Millis(d time.Duration) float64 { 68 | // Typically d is something like 11 or 21, so do some magic to round the 69 | // durations to the nearest 10. We divide d by 10, floor it, and multiply it 70 | // by 10 again. 71 | return math.Floor(float64(d/time.Millisecond/10) * 10) 72 | } 73 | 74 | // Returns the given milliseconds as time.Duration 75 | func milliseconds(ms int64) time.Duration { 76 | return time.Duration(ms * 1000 * 1000) 77 | } 78 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/segmentio/backo-go 2 | 3 | go 1.21 4 | 5 | require github.com/stretchr/testify v1.9.0 6 | 7 | require ( 8 | github.com/davecgh/go-spew v1.1.1 // indirect 9 | github.com/pmezard/go-difflib v1.0.0 // indirect 10 | gopkg.in/yaml.v3 v3.0.1 // indirect 11 | ) 12 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 2 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 3 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 4 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 5 | github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= 6 | github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= 7 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 8 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 9 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 10 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 11 | --------------------------------------------------------------------------------