The retry package provides a generic, context-aware way to retry fallible operations with configurable backoff strategies and timeout handling.
Options
MaxAttempts uint: Total number of times the operation will be tried before giving up.
TotalTimeout time.Duration: Maximum time allowed across all attempts, including backoff delays.
Backoff func(attempt uint) time.Duration: Returns how long to wait before the next attempt. attempt is zero-indexed.
ShouldRetry func(err error) bool: Reports whether the given error is retryable. Return false to abort immediately.
Functions
Do[T any](ctx context.Context, opts Options, fn RetryFunc[T]) (T, error):
Calls fn repeatedly until it succeeds, ShouldRetry returns false, MaxAttempts is reached, or TotalTimeout elapses.
DoVoid(ctx context.Context, opts Options, fn func(ctx context.Context) error) error:
Convenience wrapper around Do for operations that return no value.
Backoff Strategies
FixedBackoff(d time.Duration) func(attempt uint) time.Duration:
Waits exactly d between every attempt.
TotalTimeout is enforced via a derived context passed to every attempt. If the deadline is exceeded mid-backoff, Do returns context.DeadlineExceeded immediately. A value of 0 means no timeout is applied.
A non-retryable error returned from ShouldRetry is returned as-is, without wrapping.
When MaxAttempts is exhausted, Do returns an error wrapping the last error from fn: "retry: max attempts reached: <last error>". Use errors.Is/errors.As to inspect the underlying cause.
Backoff and ShouldRetry are optional. If nil, Backoff defaults to no delay and ShouldRetry defaults to always retry.
LinearBackoff produces a zero-length first pause (attempt 0). Prefer FixedBackoff if an immediate first retry is undesirable.
Examples:
For examples of each function, please check out EXAMPLES.md
type Options struct {
MaxAttempts uint TotalTimeout time.Duration// Backoff returns how long to wait before the next attempt.// attempt is zero-indexed (0 = pause after the first failure).
Backoff func(attempt uint) time.Duration// ShouldRetry reports whether the given error is retryable.// Return false to abort immediately.
ShouldRetry func(err error) bool
}