backoff

package
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 20, 2026 License: Apache-2.0 Imports: 8 Imported by: 0

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

Constants

This section is empty.

Variables

View Source
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

func NewBackoff(opts ...Option) *Backoff

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

type DelayStrategy func(attempt int) time.Duration

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

func WithDeterministic(enabled bool) Option

WithDeterministic enables deterministic delay behavior for reproducible tests.

func WithFactor

func WithFactor(f float64) Option

WithFactor sets the exponential growth factor for delays.

func WithJitter

func WithJitter(enabled bool) Option

WithJitter enables or disables jitter for backoff delays.

func WithLogger

func WithLogger(logger logger.Logger) Option

WithLogger attaches a logger function to observe retry attempts.

func WithMaxDelay

func WithMaxDelay(d time.Duration) Option

WithMaxDelay sets the maximum backoff delay.

func WithMaxRetries

func WithMaxRetries(n int) Option

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

func WithMinDelay(d time.Duration) Option

WithMinDelay sets the minimum backoff delay.

func WithPerAttemptTimeout

func WithPerAttemptTimeout(timeout time.Duration) Option

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

type RetryContext struct {
	Attempt   int
	DelayUsed time.Duration
	Error     error
}

RetryContext holds metadata about a retry attempt, including the attempt number, delay used, and the error returned by the function.

type RetryPredicate

type RetryPredicate func(err error) bool

RetryPredicate determines whether an error is retryable.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL