Backoff provides exponential backoff algorithms for retrying operations that may fail. It offers multiple backoff strategies including exponential backoff (which multiplicatively increases wait times between retries), constant backoff, zero backoff (immediate retry), and stop backoff (no retry), with configurable parameters like initial interval, randomization factor, multiplier, and maximum interval.
go get github.com/cenkalti/backoff/v4import "github.com/cenkalti/backoff/v4"import (
"errors"
"log"
"github.com/cenkalti/backoff/v4"
)
func main() {
operation := func() error {
// Your operation that may fail
return nil // or return an error
}
err := backoff.Retry(operation, backoff.NewExponentialBackOff())
if err != nil {
log.Fatal(err)
}
}import (
"context"
"time"
"github.com/cenkalti/backoff/v4"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
operation := func() error {
// Your operation
return nil
}
b := backoff.WithContext(backoff.NewExponentialBackOff(), ctx)
err := backoff.Retry(operation, b)
if err != nil {
// Handle error
}
}import (
"time"
"github.com/cenkalti/backoff/v4"
)
func main() {
b := backoff.NewExponentialBackOff(
backoff.WithInitialInterval(1*time.Second),
backoff.WithMaxInterval(30*time.Second),
backoff.WithMaxElapsedTime(5*time.Minute),
backoff.WithMultiplier(2.0),
backoff.WithRandomizationFactor(0.5),
)
operation := func() error {
// Your operation
return nil
}
err := backoff.Retry(operation, b)
if err != nil {
// Handle error
}
}Execute operations with automatic retry logic using various backoff policies. Supports simple retry, retry with data return, retry with notifications, and retry with custom timers. All retry functions guarantee at least one execution attempt and handle permanent errors that should not be retried.
// Retry the operation until it succeeds or backoff stops
func Retry(o Operation, b BackOff) error
// Retry and return data along with error
func RetryWithData[T any](o OperationWithData[T], b BackOff) (T, error)// Function type for operations executed by Retry()
type Operation func() error
// Generic function type for operations that return data
type OperationWithData[T any] func() (T, error)Different strategies for calculating wait times between retry attempts. Includes exponential backoff (multiplicatively increasing intervals with jitter), constant backoff (fixed delay), zero backoff (immediate retry), and stop backoff (never retry). Policies can be wrapped with context support or maximum retry limits.
// Core backoff interface
type BackOff interface {
NextBackOff() time.Duration
Reset()
}
// Create exponential backoff with optional configuration
func NewExponentialBackOff(opts ...ExponentialBackOffOpts) *ExponentialBackOff
// Create constant backoff with fixed interval
func NewConstantBackOff(d time.Duration) *ConstantBackOff// ExponentialBackOff configuration options
type ExponentialBackOffOpts func(*ExponentialBackOff)
func WithInitialInterval(duration time.Duration) ExponentialBackOffOpts
func WithMaxInterval(duration time.Duration) ExponentialBackOffOpts
func WithMaxElapsedTime(duration time.Duration) ExponentialBackOffOpts
func WithMultiplier(multiplier float64) ExponentialBackOffOpts
func WithRandomizationFactor(randomizationFactor float64) ExponentialBackOffOptsChannel-based retry mechanism using Go channels for backoff timing. Provides a ticker that sends time values at intervals determined by a backoff policy, allowing integration with channel-based workflows and select statements.
// Ticker holds a channel that delivers ticks at backoff intervals
type Ticker struct {
C <-chan time.Time
// Has unexported fields
}
// Create ticker with specified backoff policy
func NewTicker(b BackOff) *Ticker
// Stop the ticker
func (t *Ticker) Stop()Wrap any backoff policy to automatically stop retrying when a context is canceled or times out. Essential for implementing timeouts and cancellation in retry logic.
// BackOff with context cancellation support
// This interface embeds BackOff, so it includes NextBackOff() and Reset() methods
// plus the Context() method for accessing the associated context
type BackOffContext interface {
BackOff
Context() context.Context
}
// Wrap backoff to stop on context cancellation
func WithContext(b BackOff, ctx context.Context) BackOffContextLimit the maximum number of retry attempts by wrapping any backoff policy. Useful for preventing infinite retry loops and implementing circuit breaker patterns.
// Wrap backoff to limit maximum retry attempts
func WithMaxRetries(b BackOff, max uint64) BackOffSignal that an operation should not be retried by wrapping errors. When a permanent error is returned, all retry functions immediately stop retrying and return the wrapped error.
// Error type signaling no retry should be attempted
type PermanentError struct {
Err error
}
// Wrap error to prevent retries
func Permanent(err error) error// Constant returned by NextBackOff() to indicate no more retries
const Stop time.Duration = -1
// Default configuration for ExponentialBackOff
const (
DefaultInitialInterval = 500 * time.Millisecond
DefaultRandomizationFactor = 0.5
DefaultMultiplier = 1.5
DefaultMaxInterval = 60 * time.Second
DefaultMaxElapsedTime = 15 * time.Minute
)Permanent() to wrap errors that should not trigger retries