Documentation
¶
Overview ¶
Package retry provides functionality for retrying operations with configurable backoff and jitter.
This package implements a flexible retry mechanism that can be used to retry operations that may fail due to transient errors. It supports:
- Configurable maximum retry attempts
- Exponential backoff with configurable initial and maximum durations
- Jitter to prevent thundering herd problems
- Customizable retry conditions
- Integration with OpenTelemetry for tracing
- Comprehensive logging of retry attempts
The package distinguishes between two types of errors related to retries:
- RetryError: Used internally by this package to indicate that all retry attempts have been exhausted.
- RetryableError: Used by external systems to indicate that an error should be retried.
Example usage:
// Define a function to retry
retryableFunc := func(ctx context.Context) error {
// Some operation that might fail transiently
return callExternalService(ctx)
}
// Define a function to determine if an error is retryable
isRetryable := func(err error) bool {
return errors.IsTransientError(err)
}
// Configure retry parameters
config := retry.DefaultConfig().
WithMaxRetries(5).
WithInitialBackoff(100 * time.Millisecond).
WithMaxBackoff(2 * time.Second)
// Execute with retry
err := retry.Do(ctx, retryableFunc, config, isRetryable)
if err != nil {
// Handle error after all retries have failed
}
Package retry provides functionality for retrying operations with configurable backoff and jitter.
This package uses RetryError from the errors/infra package to represent errors that occur during retry operations. This is different from RetryableError in the errors/wrappers package, which is used to wrap errors that should be retried by external systems.
RetryError: Used internally by this package to indicate that all retry attempts have been exhausted. RetryableError: Used by external systems to indicate that an error should be retried.
Index ¶
- func Do(ctx context.Context, fn RetryableFunc, config Config, ...) error
- func DoWithOptions(ctx context.Context, fn RetryableFunc, config Config, ...) error
- func IsNetworkError(err error) booldeprecated
- func IsTimeoutError(err error) booldeprecated
- func IsTransientError(err error) booldeprecated
- type Config
- func (c Config) WithBackoffFactor(backoffFactor float64) Config
- func (c Config) WithInitialBackoff(initialBackoff time.Duration) Config
- func (c Config) WithJitterFactor(jitterFactor float64) Config
- func (c Config) WithMaxBackoff(maxBackoff time.Duration) Config
- func (c Config) WithMaxRetries(maxRetries int) Config
- func (c Config) WithRetryableErrors(retryableErrors []error) Config
- type IsRetryableError
- type Options
- type RetryableFunc
- type Span
- type Tracer
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Do ¶
func Do(ctx context.Context, fn RetryableFunc, config Config, isRetryable IsRetryableError) error
Do executes the given function with retry logic using default options. This is a convenience wrapper around DoWithOptions that uses DefaultOptions().
Parameters:
- ctx: The context for the operation. Can be used to cancel the retry operation.
- fn: The function to execute with retry logic.
- config: The retry configuration parameters.
- isRetryable: A function that determines if an error is retryable.
Returns:
- The error from the last execution of the function, or nil if successful.
func DoWithOptions ¶
func DoWithOptions(ctx context.Context, fn RetryableFunc, config Config, isRetryable IsRetryableError, options Options) error
DoWithOptions executes the given function with retry logic and custom options. It will retry the function according to the provided configuration and retry condition. The function will be retried if it returns an error and the isRetryable function returns true. The retry operation can be canceled by canceling the context.
Parameters:
- ctx: The context for the operation. Can be used to cancel the retry operation.
- fn: The function to execute with retry logic.
- config: The retry configuration parameters.
- isRetryable: A function that determines if an error is retryable.
- options: Additional options for the retry operation, such as logging and tracing.
Returns:
- The error from the last execution of the function, or nil if successful.
func IsNetworkError
deprecated
IsNetworkError checks if an error is a network-related error.
Deprecated: Use errors.IsNetworkError instead. This function is maintained for backward compatibility and will be removed in a future version.
Parameters:
- err: The error to check.
Returns:
- true if the error is a network-related error, false otherwise.
func IsTimeoutError
deprecated
IsTimeoutError checks if an error is a timeout error.
Deprecated: Use errors.IsTimeout instead. This function is maintained for backward compatibility and will be removed in a future version.
Parameters:
- err: The error to check.
Returns:
- true if the error indicates a timeout, false otherwise.
func IsTransientError
deprecated
IsTransientError checks if an error is a transient error that may be resolved by retrying.
Deprecated: Use errors.IsTransientError instead. This function is maintained for backward compatibility and will be removed in a future version.
Parameters:
- err: The error to check.
Returns:
- true if the error is likely transient and may be resolved by retrying, false otherwise.
Types ¶
type Config ¶
type Config struct {
// MaxRetries is the maximum number of retry attempts that will be made.
// The total number of attempts will be MaxRetries + 1 (including the initial attempt).
MaxRetries int
// InitialBackoff is the duration to wait before the first retry attempt.
// This value will be multiplied by BackoffFactor for subsequent retries.
InitialBackoff time.Duration
// MaxBackoff is the maximum duration to wait between retry attempts.
// The backoff duration will not exceed this value, regardless of the BackoffFactor.
MaxBackoff time.Duration
// BackoffFactor is the factor by which the backoff duration increases after each retry.
// For example, a BackoffFactor of 2.0 will double the backoff duration after each retry.
BackoffFactor float64
// JitterFactor is a factor for adding random jitter to the backoff duration.
// It should be a value between 0 and 1, where 0 means no jitter and 1 means maximum jitter.
// Jitter helps prevent multiple retries from occurring simultaneously (thundering herd).
JitterFactor float64
// RetryableErrors is a list of specific errors that should be considered retryable.
// If an error matches one of these errors (using errors.Is), it will be retried.
RetryableErrors []error
}
Config contains retry configuration parameters. It defines how retry operations should behave, including the number of retries, backoff durations, and jitter factors.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns a default retry configuration with reasonable values. The default configuration includes:
- 3 maximum retry attempts (4 total attempts including the initial one)
- 100ms initial backoff
- 2s maximum backoff
- 2.0 backoff factor (doubles the backoff after each retry)
- 0.2 jitter factor (adds up to 20% random jitter to the backoff)
Returns:
- A Config instance with default values.
func (Config) WithBackoffFactor ¶
WithBackoffFactor sets the factor by which the backoff duration increases after each retry. If a non-positive value is provided, it will be set to 1.0 (no increase).
Parameters:
- backoffFactor: The factor by which the backoff increases.
Returns:
- A new Config instance with the updated BackoffFactor value.
func (Config) WithInitialBackoff ¶
WithInitialBackoff sets the initial backoff duration. If a non-positive value is provided, it will be set to 1ms.
Parameters:
- initialBackoff: The duration to wait before the first retry attempt.
Returns:
- A new Config instance with the updated InitialBackoff value.
func (Config) WithJitterFactor ¶
WithJitterFactor sets the factor for adding random jitter to the backoff duration. The value should be between 0 and 1, where 0 means no jitter and 1 means maximum jitter. If a value outside this range is provided, it will be clamped to the valid range.
Parameters:
- jitterFactor: The factor for random jitter (0-1).
Returns:
- A new Config instance with the updated JitterFactor value.
func (Config) WithMaxBackoff ¶
WithMaxBackoff sets the maximum backoff duration. If a non-positive value is provided, it will be set to the initial backoff duration.
Parameters:
- maxBackoff: The maximum duration to wait between retry attempts.
Returns:
- A new Config instance with the updated MaxBackoff value.
func (Config) WithMaxRetries ¶
WithMaxRetries sets the maximum number of retry attempts. If a negative value is provided, it will be set to 0 (no retries).
Parameters:
- maxRetries: The maximum number of retry attempts.
Returns:
- A new Config instance with the updated MaxRetries value.
func (Config) WithRetryableErrors ¶
WithRetryableErrors sets the list of specific errors that should be considered retryable. If an error matches one of these errors (using errors.Is), it will be retried.
Parameters:
- retryableErrors: A slice of errors that should be considered retryable.
Returns:
- A new Config instance with the updated RetryableErrors value.
type IsRetryableError ¶
IsRetryableError is a function that determines if an error is retryable. It takes an error parameter and returns a boolean indicating whether the error should be retried. Return true to retry the operation, false to stop retrying and return the error.
type Options ¶
type Options struct {
// Logger is used for logging retry operations.
// If nil, a no-op logger will be used.
Logger *logging.ContextLogger
// Tracer is used for tracing retry operations.
// It provides integration with OpenTelemetry for distributed tracing.
Tracer telemetry.Tracer
}
Options contains additional options for the retry operation. These options are not directly related to the retry behavior itself, but provide additional functionality like logging and tracing.
func DefaultOptions ¶
func DefaultOptions() Options
DefaultOptions returns default options for retry operations. The default options include:
- No logger (a no-op logger will be used)
- A no-op tracer (no OpenTelemetry integration)
Returns:
- An Options instance with default values.
func (Options) WithOtelTracer ¶
WithOtelTracer returns Options with an OpenTelemetry tracer. This allows users to opt-in to OpenTelemetry tracing if they need it.
Parameters:
- tracer: An OpenTelemetry trace.Tracer instance.
Returns:
- A new Options instance with the provided OpenTelemetry tracer.
type RetryableFunc ¶
RetryableFunc is a function that can be retried. It takes a context.Context parameter and returns an error. If the function returns nil, it is considered successful. If it returns an error, the retry mechanism will determine whether to retry based on the IsRetryableError function.
type Span ¶
type Span interface {
// End completes the span
End()
// SetAttributes sets attributes on the span
SetAttributes(attributes ...attribute.KeyValue)
// RecordError records an error on the span
RecordError(err error)
}
Span represents a tracing span