retry

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jul 26, 2023 License: MIT Imports: 7 Imported by: 0

README

Retry

Go Reference

Documentation

Overview

Package retry provides exponential backoff.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Retry

func Retry[T any](
	ctx context.Context,
	f func(ctx context.Context) (T, error),
	opts ...Option,
) (T, error)

Retry calls f, retrying with exponential backoff on errors. After the first error, will wait MinDelay before retrying. Each successive retry waits for twice as long, up to MaxDelay. f might be failing because an upstream system is overloaded and retries may exacerbate that problem, doubling the delay means that even uncoordinated clients will eventually estimate the available capacity in the upstream.

Delays are jittered by +/-50% to avoid thundering herds. That is, the configured MinDelay is the _average_ first delay, and the actual minimum delay is half of the configured. Likewise for MaxDelay, the configured is the average max delay, but the actual maximum delay is 1.5x this value.

Attempts that are very old are forgotten with regard to picking the next delay because they are not likely to still be relevant to the health of the upstream system. This is to make Retry usable for retrying very long-running operations, for example keeping a long-lived stream alive. The age is set so that if f is consistently failing once per MaxDelay, the next delay will be MaxDelay, but any attempts older than the minimum needed to achieve that are forgotten.

Types

type Option

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

Option affects the behavior of Retry.

func Attempts

func Attempts(x int) Option

The maximum number of times to call f before returning the error. Attempts(1) means try just once and do not retry.

func Indefinitely

func Indefinitely() Option

Indefinitely is shorthand for Attempts(math.MaxInt).

func Log

func Log(f func(error, int, time.Duration)) Option

Called before sleeping on each retry with the last error that occurred, the attempt index, and the delay before the next attempt.

func MaxDelay

func MaxDelay(d time.Duration) Option

The maximum delay between attempts.

func MinDelay

func MinDelay(d time.Duration) Option

The minimum delay between attempts.

func Retryable

func Retryable(f func(error) bool) Option

If f returns false for an error observed during Retry, it is returned immediately rather than retried.

Jump to

Keyboard shortcuts

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