Skip to content

Latest commit

 

History

History
41 lines (28 loc) · 2.3 KB

File metadata and controls

41 lines (28 loc) · 2.3 KB

Retry

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.

  • LinearBackoff(d time.Duration) func(attempt uint) time.Duration:
    Waits d * attempt. Grows linearly: 0, d, 2d, 3d, …

  • ExponentialBackoff(d time.Duration) func(attempt uint) time.Duration:
    Waits min(d * 2^attempt, 2^63 - 1). Doubles on each failure: d, 2d, 4d, 8d, …

Notes

  • 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