• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..03-May-2022-

LICENSEH A D03-Oct-20191.1 KiB

README.mdH A D03-Oct-20192.3 KiB

backoff.goH A D03-Oct-20192.4 KiB

backoff_test.goH A D03-Oct-20193.2 KiB

go.modH A D03-Oct-201944

README.md

1# Backoff
2
3A simple exponential backoff counter in Go (Golang)
4
5[![GoDoc](https://godoc.org/github.com/jpillora/backoff?status.svg)](https://godoc.org/github.com/jpillora/backoff) [![Circle CI](https://circleci.com/gh/jpillora/backoff.svg?style=shield)](https://circleci.com/gh/jpillora/backoff)
6
7### Install
8
9```
10$ go get -v github.com/jpillora/backoff
11```
12
13### Usage
14
15Backoff is a `time.Duration` counter. It starts at `Min`. After every call to `Duration()` it is  multiplied by `Factor`. It is capped at `Max`. It returns to `Min` on every call to `Reset()`. `Jitter` adds randomness ([see below](#example-using-jitter)). Used in conjunction with the `time` package.
16
17---
18
19#### Simple example
20
21``` go
22
23b := &backoff.Backoff{
24	//These are the defaults
25	Min:    100 * time.Millisecond,
26	Max:    10 * time.Second,
27	Factor: 2,
28	Jitter: false,
29}
30
31fmt.Printf("%s\n", b.Duration())
32fmt.Printf("%s\n", b.Duration())
33fmt.Printf("%s\n", b.Duration())
34
35fmt.Printf("Reset!\n")
36b.Reset()
37
38fmt.Printf("%s\n", b.Duration())
39```
40
41```
42100ms
43200ms
44400ms
45Reset!
46100ms
47```
48
49---
50
51#### Example using `net` package
52
53``` go
54b := &backoff.Backoff{
55    Max:    5 * time.Minute,
56}
57
58for {
59	conn, err := net.Dial("tcp", "example.com:5309")
60	if err != nil {
61		d := b.Duration()
62		fmt.Printf("%s, reconnecting in %s", err, d)
63		time.Sleep(d)
64		continue
65	}
66	//connected
67	b.Reset()
68	conn.Write([]byte("hello world!"))
69	// ... Read ... Write ... etc
70	conn.Close()
71	//disconnected
72}
73
74```
75
76---
77
78#### Example using `Jitter`
79
80Enabling `Jitter` adds some randomization to the backoff durations. [See Amazon's writeup of performance gains using jitter](http://www.awsarchitectureblog.com/2015/03/backoff.html). Seeding is not necessary but doing so gives repeatable results.
81
82```go
83import "math/rand"
84
85b := &backoff.Backoff{
86	Jitter: true,
87}
88
89rand.Seed(42)
90
91fmt.Printf("%s\n", b.Duration())
92fmt.Printf("%s\n", b.Duration())
93fmt.Printf("%s\n", b.Duration())
94
95fmt.Printf("Reset!\n")
96b.Reset()
97
98fmt.Printf("%s\n", b.Duration())
99fmt.Printf("%s\n", b.Duration())
100fmt.Printf("%s\n", b.Duration())
101```
102
103```
104100ms
105106.600049ms
106281.228155ms
107Reset!
108100ms
109104.381845ms
110214.957989ms
111```
112
113#### Documentation
114
115https://godoc.org/github.com/jpillora/backoff
116
117#### Credits
118
119Forked from [some JavaScript](https://github.com/segmentio/backo) written by [@tj](https://github.com/tj)
120