README.md
1# backoff
2## Go implementation of "Exponential Backoff And Jitter"
3
4This package implements the backoff strategy described in the AWS
5Architecture Blog article
6["Exponential Backoff And Jitter"](http://www.awsarchitectureblog.com/2015/03/backoff.html). Essentially,
7the backoff has an interval `time.Duration`; the *n<sup>th</sup>* call
8to backoff will return an a `time.Duration` that is *2 <sup>n</sup> *
9interval*. If jitter is enabled (which is the default behaviour), the
10duration is a random value between 0 and *2 <sup>n</sup> * interval*.
11The backoff is configured with a maximum duration that will not be
12exceeded; e.g., by default, the longest duration returned is
13`backoff.DefaultMaxDuration`.
14
15## Usage
16
17A `Backoff` is initialised with a call to `New`. Using zero values
18causes it to use `DefaultMaxDuration` and `DefaultInterval` as the
19maximum duration and interval.
20
21```
22package something
23
24import "github.com/cloudflare/backoff"
25
26func retryable() {
27 b := backoff.New(0, 0)
28 for {
29 err := someOperation()
30 if err == nil {
31 break
32 }
33
34 log.Printf("error in someOperation: %v", err)
35 <-time.After(b.Duration())
36 }
37
38 log.Printf("succeeded after %d tries", b.Tries()+1)
39 b.Reset()
40}
41```
42
43It can also be used to rate limit code that should retry infinitely, but which does not
44use `Backoff` itself.
45
46```
47package something
48
49import (
50 "time"
51
52 "github.com/cloudflare/backoff"
53)
54
55func retryable() {
56 b := backoff.New(0, 0)
57 b.SetDecay(30 * time.Second)
58
59 for {
60 // b will reset if someOperation returns later than
61 // the last call to b.Duration() + 30s.
62 err := someOperation()
63 if err == nil {
64 break
65 }
66
67 log.Printf("error in someOperation: %v", err)
68 <-time.After(b.Duration())
69 }
70}
71```
72
73## Tunables
74
75* `NewWithoutJitter` creates a Backoff that doesn't use jitter.
76
77The default behaviour is controlled by two variables:
78
79* `DefaultInterval` sets the base interval for backoffs created with
80 the zero `time.Duration` value in the `Interval` field.
81* `DefaultMaxDuration` sets the maximum duration for backoffs created
82 with the zero `time.Duration` value in the `MaxDuration` field.
83
84