The retry package provides a generic, context-aware way to retry fallible operations with configurable backoff strategies and timeout handling.
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.attemptis zero-indexed.ShouldRetry func(err error) bool: Reports whether the given error is retryable. Returnfalseto abort immediately.
-
Do[T any](ctx context.Context, opts Options, fn RetryFunc[T]) (T, error):
Callsfnrepeatedly until it succeeds,ShouldRetryreturnsfalse,MaxAttemptsis reached, orTotalTimeoutelapses. -
DoVoid(ctx context.Context, opts Options, fn func(ctx context.Context) error) error:
Convenience wrapper aroundDofor operations that return no value.
-
FixedBackoff(d time.Duration) func(attempt uint) time.Duration:
Waits exactlydbetween every attempt. -
LinearBackoff(d time.Duration) func(attempt uint) time.Duration:
Waitsd * attempt. Grows linearly:0, d, 2d, 3d, … -
ExponentialBackoff(d time.Duration) func(attempt uint) time.Duration:
Waitsmin(d * 2^attempt, 2^63 - 1). Doubles on each failure:d, 2d, 4d, 8d, …
TotalTimeoutis enforced via a derived context passed to every attempt. If the deadline is exceeded mid-backoff,Doreturnscontext.DeadlineExceededimmediately. A value of0means no timeout is applied.- A non-retryable error returned from
ShouldRetryis returned as-is, without wrapping. - When
MaxAttemptsis exhausted,Doreturns an error wrapping the last error fromfn:"retry: max attempts reached: <last error>". Useerrors.Is/errors.Asto inspect the underlying cause. BackoffandShouldRetryare optional. Ifnil,Backoffdefaults to no delay andShouldRetrydefaults to always retry.LinearBackoffproduces a zero-length first pause (attempt 0). PreferFixedBackoffif an immediate first retry is undesirable.
For examples of each function, please check out EXAMPLES.md