package backoff
Import Path
github.com/cenkalti/backoff/v5 (on go.dev)
Dependency Relation
imports 6 packages, and imported by one package
Involved Source Files
Package backoff implements backoff algorithms for retrying operations.
Use Retry function for retrying operations that may fail.
If Retry does not meet your needs,
copy/paste the function into your project and modify as you wish.
There is also Ticker type similar to time.Ticker.
You can use it if you need to work with channels.
See Examples section below for usage examples.
error.go
exponential.go
retry.go
ticker.go
timer.go
Code Examples
{
operation := func() (string, error) {
resp, err := http.Get("http://httpbin.org/get")
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode == 400 {
return "", backoff.Permanent(errors.New("bad request"))
}
if resp.StatusCode == 429 {
seconds, err := strconv.ParseInt(resp.Header.Get("Retry-After"), 10, 64)
if err == nil {
return "", backoff.RetryAfter(int(seconds))
}
}
return "hello", nil
}
result, err := backoff.Retry(context.TODO(), operation, backoff.WithBackOff(backoff.NewExponentialBackOff()))
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println(result)
}
{
operation := func() (string, error) {
return "hello", nil
}
ticker := backoff.NewTicker(backoff.NewExponentialBackOff())
defer ticker.Stop()
var result string
var err error
for range ticker.C {
if result, err = operation(); err != nil {
log.Println(err, "will retry...")
continue
}
break
}
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println(result)
}
Package-Level Type Names (total 11)
BackOff is a backoff policy for retrying an operation.
NextBackOff returns the duration to wait before retrying the operation,
backoff.Stop to indicate that no more retries should be made.
Example usage:
duration := backoff.NextBackOff()
if duration == backoff.Stop {
// Do not retry operation.
} else {
// Sleep for duration and retry operation.
}
Reset to initial state.
*ConstantBackOff
*ExponentialBackOff
*StopBackOff
*ZeroBackOff
func NewTicker(b BackOff) *Ticker
func WithBackOff(b BackOff) RetryOption
ConstantBackOff is a backoff policy that always returns the same backoff delay.
This is in contrast to an exponential backoff policy,
which returns a delay that grows longer as you call NextBackOff() over and over again.
Interval time.Duration
(*ConstantBackOff) NextBackOff() time.Duration
(*ConstantBackOff) Reset()
*ConstantBackOff : BackOff
func NewConstantBackOff(d time.Duration) *ConstantBackOff
ExponentialBackOff is a backoff implementation that increases the backoff
period for each retry attempt using a randomization function that grows exponentially.
NextBackOff() is calculated using the following formula:
randomized interval =
RetryInterval * (random value in range [1 - RandomizationFactor, 1 + RandomizationFactor])
In other words NextBackOff() will range between the randomization factor
percentage below and above the retry interval.
For example, given the following parameters:
RetryInterval = 2
RandomizationFactor = 0.5
Multiplier = 2
the actual backoff period used in the next retry attempt will range between 1 and 3 seconds,
multiplied by the exponential, that is, between 2 and 6 seconds.
Note: MaxInterval caps the RetryInterval and not the randomized interval.
Example: Given the following default arguments, for 9 tries the sequence will be:
Request # RetryInterval (seconds) Randomized Interval (seconds)
1 0.5 [0.25, 0.75]
2 0.75 [0.375, 1.125]
3 1.125 [0.562, 1.687]
4 1.687 [0.8435, 2.53]
5 2.53 [1.265, 3.795]
6 3.795 [1.897, 5.692]
7 5.692 [2.846, 8.538]
8 8.538 [4.269, 12.807]
9 12.807 [6.403, 19.210]
Note: Implementation is not thread-safe.
InitialInterval time.Duration
MaxInterval time.Duration
Multiplier float64
RandomizationFactor float64
NextBackOff calculates the next backoff interval using the formula:
Randomized interval = RetryInterval * (1 ± RandomizationFactor)
Reset the interval back to the initial retry interval and restarts the timer.
Reset must be called before using b.
*ExponentialBackOff : BackOff
func NewExponentialBackOff() *ExponentialBackOff
Notify is a function called on operation error with the error and backoff duration.
func WithNotify(n Notify) RetryOption
Type Parameters:
T: any
Operation is a function that attempts an operation and may be retried.
func Retry[T](ctx context.Context, operation Operation[T], opts ...RetryOption) (T, error)
PermanentError signals that the operation should not be retried.
Err error
Error returns a string representation of the Permanent error.
Unwrap returns the wrapped error.
*PermanentError : error
*PermanentError : golang.org/x/xerrors.Wrapper
RetryAfterError signals that the operation should be retried after the given duration.
Duration time.Duration
Error returns a string representation of the RetryAfter error.
*RetryAfterError : error
func WithBackOff(b BackOff) RetryOption
func WithMaxElapsedTime(d time.Duration) RetryOption
func WithMaxTries(n uint) RetryOption
func WithNotify(n Notify) RetryOption
func Retry[T](ctx context.Context, operation Operation[T], opts ...RetryOption) (T, error)
StopBackOff is a fixed backoff policy that always returns backoff.Stop for
NextBackOff(), meaning that the operation should never be retried.
(*StopBackOff) NextBackOff() time.Duration
(*StopBackOff) Reset()
*StopBackOff : BackOff
Ticker holds a channel that delivers `ticks' of a clock at times reported by a BackOff.
Ticks will continue to arrive when the previous operation is still running,
so operations that take a while to fail could run in quick succession.
C <-chan time.Time
Stop turns off a ticker. After Stop, no more ticks will be sent.
func NewTicker(b BackOff) *Ticker
ZeroBackOff is a fixed backoff policy whose backoff time is always zero,
meaning that the operation is retried immediately without waiting, indefinitely.
(*ZeroBackOff) NextBackOff() time.Duration
(*ZeroBackOff) Reset()
*ZeroBackOff : BackOff
Package-Level Functions (total 10)
func NewConstantBackOff(d time.Duration) *ConstantBackOff
NewExponentialBackOff creates an instance of ExponentialBackOff using default values.
NewTicker returns a new Ticker containing a channel that will send
the time at times specified by the BackOff argument. Ticker is
guaranteed to tick at least once. The channel is closed when Stop
method is called or BackOff stops. It is not safe to manipulate the
provided backoff policy (notably calling NextBackOff or Reset)
while the ticker is running.
Permanent wraps the given err in a *PermanentError.
Type Parameters:
T: any
Retry attempts the operation until success, a permanent error, or backoff completion.
It ensures the operation is executed at least once.
Returns the operation result or error if retries are exhausted or context is cancelled.
RetryAfter returns a RetryAfter error that specifies how long to wait before retrying.
WithBackOff configures a custom backoff strategy.
WithMaxElapsedTime limits the total duration for retry attempts.
WithMaxTries limits the number of all attempts.
WithNotify sets a notification function to handle retry errors.
Package-Level Constants (total 6)
Default values for ExponentialBackOff.
DefaultMaxElapsedTime sets a default limit for the total retry duration.
Default values for ExponentialBackOff.
Default values for ExponentialBackOff.
Default values for ExponentialBackOff.
Stop indicates that no more retries should be made for use in NextBackOff().
![]() |
The pages are generated with Golds v0.8.2. (GOOS=linux GOARCH=amd64) Golds is a Go 101 project developed by Tapir Liu. PR and bug reports are welcome and can be submitted to the issue list. Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds. |