
Backoff
Package backoff implements backoff logic for retry loops.
It provides a Generator that produces a sequence of time.Duration values
using configurable step functions: Fixed, Linear, Incremental,
Exponential, and Jitter.
Usage
Exponential Backoff
gen := backoff.New(time.Second, 30*time.Second, backoff.Exponential(2))
for attempt := range gen.Values() {
if err := doSomething(); err == nil {
break
}
time.Sleep(attempt)
}
With Jitter
Jitter is useful in distributed systems to avoid thundering herd problems.
gen := backoff.New(
time.Second,
30*time.Second,
backoff.Jitter(backoff.Exponential(2), 0.5),
)
for i := 0; i < maxRetries; i++ {
if err := doSomething(); err == nil {
break
}
time.Sleep(gen.Next())
}
Linear Backoff
gen := backoff.New(time.Second, 10*time.Second, backoff.Linear(2*time.Second))
Fixed Backoff
gen := backoff.New(time.Second, 0, backoff.Fixed(5*time.Second))
Step Functions
Fixed(d) | Always returns d |
Linear(d) | Adds d each iteration: base, base+d, base+2d, ... |
Incremental(m) | Multiplies base by count: base, base*m, base*2m, ... |
Exponential(f) | Exponential growth: base, base*f, base*f^2, ... |
Jitter(fn, factor) | Wraps any step function with randomized jitter in [d-factor*d, d] |
Contributions
Contributions are welcome via Pull Requests.