Retries and backoff
Configure exponential backoff, a cap, and jitter, and choose which errors are worth retrying with Stop and Retryable.
Configure backoff
After the nth failure, Retry waits Delay × Multiplier^(n-1), capped by Retry.MaxDelay and shortened at random by Retry.Jitter. Zero fields use the defaults: 3 for Retry.Attempts, 100ms for Retry.Delay, and 2 for Retry.Multiplier. A Retry.Multiplier of 1 gives a constant wait. Retry.OnRetry is called after each failure and before the wait, which makes it a good place for logs or metrics.
retry := resil.Retry{
Attempts: 5,
Delay: 50 * time.Millisecond,
MaxDelay: time.Second,
Jitter: 0.2,
OnRetry: func(attempt int, err error, wait time.Duration) {
fmt.Printf("attempt %d failed (%v), retrying in about %s\n", attempt, err, wait.Round(10*time.Millisecond))
},
}
for _, id := range []int{42, 7} {
calls := 0
fetch := fetchOrder(&calls)
order, err := retry.Get(ctx, func(ctx context.Context) (string, error) {
return fetch(ctx, id)
})
fmt.Printf("order %d: %q, err=%v, calls=%d\n", id, order, err, calls)
}When a service restarts, every client fails at once and would retry at once too. Retry.Jitter spreads the clients' waits apart, and Retry.MaxDelay keeps waits from growing without limit.
Errors that should not be retried
A 404 or a validation error fails the same way every time. Return Stop(err) from the operation, and Retry gives up immediately. The wrapped error keeps its message and still matches the original with errors.Is:
errNotFound := errors.New("not found")
attempts := 0
err := resil.Retry{}.Do(context.Background(), func(context.Context) error {
attempts++
return resil.Stop(errNotFound) // retrying cannot help
})
fmt.Println(attempts, err, errors.Is(err, errNotFound))1 not found trueFor a rule that covers many call sites, set Retry.Retryable. When it is nil, every error except ErrOpen is retried. Errors wrapped with Stop are never retried, whatever Retry.Retryable returns.
The returned error
Retry.Do and Retry.Get return the value and error of the last attempt, unwrapped. Retrying stops as soon as the caller's context ends. If that happens during a wait between attempts, the returned error matches both the context's error and the last failure. If a field is invalid, such as a negative Retry.Attempts, they return an error without calling the operation.