backoff: Index | Examples | Files

package backoff

import ""

Package backoff contains an implementation of an intelligent backoff strategy. It is based on the approach in the AWS architecture blog article titled "Exponential Backoff And Jitter", which is found at

Essentially, the backoff has an interval `time.Duration`; the nth call to backoff will return a `time.Duration` that is 2^n * interval. If jitter is enabled (which is the default behaviour), the duration is a random value between 0 and 2^n * interval. The backoff is configured with a maximum duration that will not be exceeded.

The `New` function will attempt to use the system's cryptographic random number generator to seed a Go math/rand random number source. If this fails, the package will panic on startup.



Package Files



var DefaultInterval = 5 * time.Minute

DefaultInterval is used when a Backoff is initialised with a zero-value Interval.

var DefaultMaxDuration = 6 * time.Hour

DefaultMaxDuration is maximum amount of time that the backoff will delay for.

type Backoff Uses

type Backoff struct {
    // contains filtered or unexported fields

A Backoff contains the information needed to intelligently backoff and retry operations using an exponential backoff algorithm. It should be initialised with a call to `New`.

Only use a Backoff from a single goroutine, it is not safe for concurrent access.

func New Uses

func New(max time.Duration, interval time.Duration) *Backoff

New creates a new backoff with the specified max duration and interval. Zero values may be used to use the default values.

Panics if either max or interval is negative.

func NewWithoutJitter Uses

func NewWithoutJitter(max time.Duration, interval time.Duration) *Backoff

NewWithoutJitter works similarly to New, except that the created Backoff will not use jitter.

func (*Backoff) Duration Uses

func (b *Backoff) Duration() time.Duration

Duration returns a time.Duration appropriate for the backoff, incrementing the attempt counter.

func (*Backoff) Reset Uses

func (b *Backoff) Reset()

Reset resets the attempt counter of a backoff.

It should be called when the rate-limited action succeeds.

func (*Backoff) SetDecay Uses

func (b *Backoff) SetDecay(decay time.Duration)

SetDecay sets the duration after which the try counter will be reset. Panics if decay is smaller than 0.

The decay only kicks in if at least the last backoff + decay has elapsed since the last try.


b := NewWithoutJitter(max, interval)

// try 0

// try 1

// try 2
duration := b.Duration()

// try 3, below decay
duration = b.Duration()

// try 4, resets
time.Sleep(duration + decay)



Package backoff imports 7 packages (graph) and is imported by 28 packages. Updated 2019-06-27. Refresh now. Tools for package owners.