backoff

package
v1.32.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 15, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Index

Examples

Constants

View Source
const NoBackoff = time.Duration(-1)

NoBackoff is used to represent backoff when no cron backoff is needed

View Source
const (
	// NoInterval represents Maximim interval
	NoInterval = 0
)

Variables

This section is empty.

Functions

func CalculateExponentialRetryInterval

func CalculateExponentialRetryInterval(retryPolicy *commonpb.RetryPolicy, attempt int32) time.Duration

CalculateExponentialRetryInterval calculates the retry interval using exponential backoff algorithm

func ExponentialBackoffAlgorithm

func ExponentialBackoffAlgorithm(initInterval *durationpb.Duration, backoffCoefficient float64, currentAttempt int32) time.Duration

ExponentialBackoffAlgorithm calculates the backoff duration as `initInterval * (backoffCoefficient ^ (currentAttempt - 1))`. The result is clamped to [0, math.MaxInt64].

func FullJitter

func FullJitter[T ~int64 | ~int | ~int32 | ~float64 | ~float32](input T) T

FullJitter return random number from 0 to input, inclusive, exclusive

func GetBackoffForNextSchedule

func GetBackoffForNextSchedule(cronSchedule string, scheduledTime time.Time, now time.Time) time.Duration

GetBackoffForNextSchedule calculates the backoff time for the next run given a cronSchedule, current scheduled time, and now.

func GetBackoffForNextScheduleNonNegative

func GetBackoffForNextScheduleNonNegative(cronSchedule string, scheduledTime time.Time, now time.Time) time.Duration

GetBackoffForNextScheduleNonNegative calculates the backoff time and ensures a non-negative duration.

func IgnoreErrors

func IgnoreErrors(errorsToExclude []error) func(error) bool

IgnoreErrors can be used as IsRetryable handler for Retry function to exclude certain errors from the retry list

func Jitter

func Jitter[T ~int64 | ~int | ~int32 | ~float64 | ~float32](input T, coefficient float64) T

Jitter return random number from (1-coefficient)*input to (1+coefficient)*input, inclusive, exclusive

func ThrottleRetry

func ThrottleRetry(operation Operation, policy RetryPolicy, isRetryable IsRetryable) error

ThrottleRetry is a resource aware version of Retry. Resource exhausted error will be retried using a different throttle retry policy, instead of the specified one.

func ThrottleRetryContext

func ThrottleRetryContext(
	ctx context.Context,
	operation OperationCtx,
	policy RetryPolicy,
	isRetryable IsRetryable,
) error

ThrottleRetryContext is a context and resource aware version of Retry. Context timeout/cancellation errors are never retried, regardless of IsRetryable. Resource exhausted error will be retried using a different throttle retry policy, instead of the specified one. TODO: allow customizing throttle retry policy and what kind of error are categorized as throttle error.

func ThrottleRetryContextWithReturn

func ThrottleRetryContextWithReturn[T any](
	ctx context.Context,
	fn func(context.Context) (T, error),
	policy RetryPolicy,
	isRetryable IsRetryable,
) (T, error)

ThrottleRetryContextWithReturn is a context and resource aware version of Retry. Context timeout/cancellation errors are never retried, regardless of IsRetryable. Resource exhausted error will be retried using a different throttle retry policy, instead of the specified one. TODO: allow customizing throttle retry policy and what kind of error are categorized as throttle error.

func ValidateSchedule

func ValidateSchedule(cronSchedule string) error

ValidateSchedule validates a cron schedule spec

Types

type BackoffCalculatorAlgorithmFunc

type BackoffCalculatorAlgorithmFunc func(duration *durationpb.Duration, coefficient float64, currentAttempt int32) time.Duration

BackoffCalculatorAlgorithmFunc is a function type that calculates backoff duration based on initial duration, coefficient, and current attempt number.

func MakeBackoffAlgorithm

func MakeBackoffAlgorithm(requestedDelay *time.Duration) BackoffCalculatorAlgorithmFunc

MakeBackoffAlgorithm creates a BackoffCalculatorAlgorithmFunc that returns a fixed delay if requestedDelay is non-nil, otherwise falls back to exponential backoff algorithm.

type ConditionalRetryPolicy

type ConditionalRetryPolicy struct {
	// contains filtered or unexported fields
}

ConditionalRetryPolicy chooses between two underlying retry policies based on a predicate evaluated against the error from the last attempt. The numAttempts counter is shared across both branches, so a sequence that mixes error types can hit the more conservative branch's cap on a later attempt.

func NewConditionalRetryPolicy

func NewConditionalRetryPolicy(predicate func(err error) bool, whenTrue, whenFalse RetryPolicy) *ConditionalRetryPolicy

NewConditionalRetryPolicy returns a policy that delegates to whenTrue when predicate(err) is true, and whenFalse otherwise.

func (*ConditionalRetryPolicy) ComputeNextDelay

func (p *ConditionalRetryPolicy) ComputeNextDelay(elapsedTime time.Duration, numAttempts int, err error) time.Duration

type ConstantDelayRetryPolicy

type ConstantDelayRetryPolicy struct {
	// contains filtered or unexported fields
}

func NewConstantDelayRetryPolicy

func NewConstantDelayRetryPolicy(delay time.Duration) *ConstantDelayRetryPolicy

func (*ConstantDelayRetryPolicy) ComputeNextDelay

func (p *ConstantDelayRetryPolicy) ComputeNextDelay(_ time.Duration, attempt int, _ error) time.Duration

func (*ConstantDelayRetryPolicy) WithJitter

func (p *ConstantDelayRetryPolicy) WithJitter(jitterPct float64) *ConstantDelayRetryPolicy

func (*ConstantDelayRetryPolicy) WithMaximumAttempts

func (p *ConstantDelayRetryPolicy) WithMaximumAttempts(maximumAttempts int) *ConstantDelayRetryPolicy

type ErrorDependentRetryPolicy

type ErrorDependentRetryPolicy struct {
	// contains filtered or unexported fields
}

ErrorDependentRetryPolicy is a policy that computes the next delay time based on the error returned by the operation. The delay time to use for a particular error is determined by the delayForError function.

func NewErrorDependentRetryPolicy

func NewErrorDependentRetryPolicy(delayForError func(err error) time.Duration) *ErrorDependentRetryPolicy

func (*ErrorDependentRetryPolicy) ComputeNextDelay

func (p *ErrorDependentRetryPolicy) ComputeNextDelay(_ time.Duration, attempt int, err error) time.Duration

func (*ErrorDependentRetryPolicy) WithJitter

func (*ErrorDependentRetryPolicy) WithMaximumAttempts

func (p *ErrorDependentRetryPolicy) WithMaximumAttempts(maximumAttempts int) *ErrorDependentRetryPolicy

type ExponentialRetryPolicy

type ExponentialRetryPolicy struct {
	// contains filtered or unexported fields
}

ExponentialRetryPolicy provides the implementation for retry policy using a coefficient to compute the next delay. Formula used to compute the next delay is:

min(initialInterval * pow(backoffCoefficient, currentAttempt), maximumInterval)

func NewExponentialRetryPolicy

func NewExponentialRetryPolicy(initialInterval time.Duration) *ExponentialRetryPolicy

NewExponentialRetryPolicy returns an instance of ExponentialRetryPolicy using the provided initialInterval

func (*ExponentialRetryPolicy) ComputeNextDelay

func (p *ExponentialRetryPolicy) ComputeNextDelay(elapsedTime time.Duration, numAttempts int, _ error) time.Duration

ComputeNextDelay returns the next delay interval. This is used by Retrier to delay calling the operation again

func (*ExponentialRetryPolicy) WithBackoffCoefficient

func (p *ExponentialRetryPolicy) WithBackoffCoefficient(backoffCoefficient float64) *ExponentialRetryPolicy

WithBackoffCoefficient sets the coefficient used by ExponentialRetryPolicy to compute next delay for each retry All retries are computed using the following formula: initialInterval * math.Pow(backoffCoefficient, currentAttempt)

func (*ExponentialRetryPolicy) WithExpirationInterval

func (p *ExponentialRetryPolicy) WithExpirationInterval(expirationInterval time.Duration) *ExponentialRetryPolicy

WithExpirationInterval sets the absolute expiration interval for all retries

func (*ExponentialRetryPolicy) WithInitialInterval

func (p *ExponentialRetryPolicy) WithInitialInterval(initialInterval time.Duration) *ExponentialRetryPolicy

WithInitialInterval sets the initial interval used by ExponentialRetryPolicy for the very first retry All later retries are computed using the following formula: initialInterval * math.Pow(backoffCoefficient, currentAttempt)

func (*ExponentialRetryPolicy) WithMaximumAttempts

func (p *ExponentialRetryPolicy) WithMaximumAttempts(maximumAttempts int) *ExponentialRetryPolicy

WithMaximumAttempts sets the maximum number of retry attempts

func (*ExponentialRetryPolicy) WithMaximumInterval

func (p *ExponentialRetryPolicy) WithMaximumInterval(maximumInterval time.Duration) *ExponentialRetryPolicy

WithMaximumInterval sets the maximum interval for each retry. This does *not* cause the policy to stop retrying when the interval between retries reaches the supplied duration. That is what WithExpirationInterval does. Instead, this prevents the interval from exceeding maximumInterval.

Example

ExampleExponentialRetryPolicy_WithMaximumInterval demonstrates example delays with a backoff coefficient of 2 and a maximum interval of 10 seconds. Keep in mind that there is a random jitter in these times, so they are not exactly what you'd expect.

jitterRand.Store(rand.New(rand.NewSource(42)))

p1 := NewExponentialRetryPolicy(time.Second).
	WithBackoffCoefficient(2.0).
	WithMaximumInterval(0).
	WithMaximumAttempts(0).
	WithExpirationInterval(0)
p1copy := *p1
p2 := &p1copy
p2 = p2.WithMaximumInterval(time.Second * 10)
var e1, e2 time.Duration
fmt.Printf("%-10s| %15s| %15s\n", "Attempt", "Delay", "Capped Delay")
for attempts := range 10 {
	d1 := p1.ComputeNextDelay(e1, attempts, nil)
	d2 := p2.ComputeNextDelay(e2, attempts, nil)
	e1 += d1
	e2 += d2
	_, _ = fmt.Printf(
		"%-10d| %14.1fs| %14.1fs\n",
		attempts,
		d1.Round(100*time.Millisecond).Seconds(),
		d2.Round(100*time.Millisecond).Seconds(),
	)
}
Output:
Attempt   |           Delay|    Capped Delay
0         |            0.0s|            0.0s
1         |            0.8s|            0.9s
2         |            1.7s|            1.6s
3         |            3.3s|            3.2s
4         |            7.2s|            7.2s
5         |           15.1s|            9.6s
6         |           26.2s|            8.8s
7         |           62.8s|            9.4s
8         |          112.8s|            9.5s
9         |          219.7s|            8.3s

type IsRetryable

type IsRetryable func(error) bool

IsRetryable handler can be used to exclude certain errors during retry

type Operation

type Operation func() error

Operation to retry

type OperationCtx

type OperationCtx func(context.Context) error

OperationCtx plays the same role as Operation but for context-aware retryable functions.

type Retrier

type Retrier interface {
	NextBackOff(err error) time.Duration
	Reset()
}

Retrier manages the state of retry operation

func NewRetrier

func NewRetrier(policy RetryPolicy, timeSource clock.TimeSource) Retrier

NewRetrier is used for creating a new instance of Retrier

type RetryLockedSource

type RetryLockedSource struct {
	// contains filtered or unexported fields
}

func NewRetryLockedSource

func NewRetryLockedSource() *RetryLockedSource

func (*RetryLockedSource) Int63

func (r *RetryLockedSource) Int63() int64

func (*RetryLockedSource) Seed

func (r *RetryLockedSource) Seed(seed int64)

type RetryPolicy

type RetryPolicy interface {
	ComputeNextDelay(elapsedTime time.Duration, numAttempts int, err error) time.Duration
}

RetryPolicy is the API which needs to be implemented by various retry policy implementations

var (
	// DisabledRetryPolicy is a retry policy that never retries
	DisabledRetryPolicy RetryPolicy = &disabledRetryPolicyImpl{}
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL