Documentation
¶
Overview ¶
Package backoff provides a configurable, production-grade exponential backoff implementation with support for jitter, selective retries, per-attempt timeout, metrics hooks, and pluggable strategies.
Index ¶
- Variables
- type Backoff
- type DelayStrategy
- type MetricsHook
- type Option
- func WithDelayStrategy(strategy DelayStrategy) Option
- func WithDeterministic(enabled bool) Option
- func WithFactor(f float64) Option
- func WithJitter(enabled bool) Option
- func WithLogger(logger logger.Logger) Option
- func WithMaxDelay(d time.Duration) Option
- func WithMaxRetries(n int) Option
- func WithMetrics(hook MetricsHook) Option
- func WithMinDelay(d time.Duration) Option
- func WithPerAttemptTimeout(timeout time.Duration) Option
- func WithRetryIf(predicate RetryPredicate) Option
- type RetryContext
- type RetryPredicate
Constants ¶
This section is empty.
Variables ¶
var ( // ErrMaxRetriesExceeded is returned when all retry attempts have been exhausted. ErrMaxRetriesExceeded = errors.New("max retries exceeded") MinimumDelay = 100 * time.Millisecond // Default minimum delay for backoff MaximumDelay = 10 * time.Second // Default maximum delay for backoff MaximumRetries = 5 // Default maximum number of retry attempts ExponentialFactor = 2.0 // Default exponential factor for delay growth DeterministicJitter = true // Default deterministic mode for testing )
Functions ¶
This section is empty.
Types ¶
type Backoff ¶
type Backoff struct {
MinDelay time.Duration // Minimum delay between retries
MaxDelay time.Duration // Maximum delay between retries
MaxRetries int // Maximum number of retry attempts
Factor float64 // Exponential factor for delay growth
Jitter bool // Enables jitter to randomize delay
PerAttemptTimeout time.Duration // Optional timeout for each retry attempt
Logger logger.Logger // Optional logger hook
RetryIf RetryPredicate // Optional predicate to filter retryable errors
Metrics MetricsHook // Optional metrics callback
Strategy DelayStrategy // Optional custom delay strategy
Deterministic bool // Enables deterministic mode for testing
// contains filtered or unexported fields
}
Backoff represents a robust and configurable exponential backoff strategy. It supports jitter, delay customization, metrics, retry conditions, and more.
func NewBackoff ¶
NewBackoff creates a new Backoff instance with the provided options.
func (*Backoff) Reset ¶
func (b *Backoff) Reset()
Reset is retained for backwards compatibility. The crypto random source is stateless.
func (*Backoff) Retry ¶
func (b *Backoff) Retry(ctx context.Context, fn func(context.Context, ...any) (any, error), args ...any) (any, error)
Retry executes a given function with retry logic using exponential backoff.
The function `fn` should accept a context and a variadic list of arguments (any types). It must return a result of type `any` and an `error`. The retry mechanism only checks the error to determine if the function should be retried.
If the function succeeds (returns `nil` error), the value is returned immediately. If the function returns an error, it will be retried up to `MaxRetries` times, with delays between attempts determined by the backoff configuration.
The optional fields in Backoff (e.g., Logger, Metrics, RetryIf) can be used to control behavior.
Parameters:
- ctx: Context for cancellation or timeout of the overall retry operation.
- fn: Function to execute. Must be of the form: func(ctx context.Context, args ...any) (any, error).
- args: Variadic list of arguments to pass to fn.
Returns:
- Value of type `any` if successful.
- Error if retries are exhausted or context is canceled.
Example:
val, err := b.Retry(ctx, func(ctx context.Context, args ...any) (any, error) {
x := args[0].(int)
y := args[1].(string)
if x < 5 {
return nil, errors.New("x too small")
}
return fmt.Sprintf(\"Processed %d and %s\", x, y), nil
}, 10, \"hello\")
if err != nil {
log.Fatal(err)
}
fmt.Println(val)
type DelayStrategy ¶
DelayStrategy defines a pluggable delay calculation function for backoff.
type MetricsHook ¶
type MetricsHook func(ctx RetryContext)
MetricsHook defines a callback function to report retry metrics.
type Option ¶
type Option func(*Backoff)
Option is a functional option type for configuring a Backoff instance.
func WithDelayStrategy ¶
func WithDelayStrategy(strategy DelayStrategy) Option
WithDelayStrategy sets a custom delay calculation strategy.
func WithDeterministic ¶
WithDeterministic enables deterministic delay behavior for reproducible tests.
func WithFactor ¶
WithFactor sets the exponential growth factor for delays.
func WithJitter ¶
WithJitter enables or disables jitter for backoff delays.
func WithLogger ¶
WithLogger attaches a logger function to observe retry attempts.
func WithMaxDelay ¶
WithMaxDelay sets the maximum backoff delay.
func WithMaxRetries ¶
WithMaxRetries sets the maximum number of retry attempts.
func WithMetrics ¶
func WithMetrics(hook MetricsHook) Option
WithMetrics attaches a metrics reporting hook to retry attempts.
func WithMinDelay ¶
WithMinDelay sets the minimum backoff delay.
func WithPerAttemptTimeout ¶
WithPerAttemptTimeout sets a timeout for each individual retry attempt.
func WithRetryIf ¶
func WithRetryIf(predicate RetryPredicate) Option
WithRetryIf specifies a predicate to determine retryable errors.
type RetryContext ¶
RetryContext holds metadata about a retry attempt, including the attempt number, delay used, and the error returned by the function.
type RetryPredicate ¶
RetryPredicate determines whether an error is retryable.