Documentation
¶
Overview ¶
Package exponentialbackoff provides utilities for computing exponential backoff delays.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CalculateDelay ¶
func CalculateDelay(backoffCount int, jitter time.Duration, config Config, opts ...DelayOption) time.Duration
CalculateDelay computes the delay for a given backoff count using exponential backoff with optional jitter.
The formula is: initial * (multiplier ^ (count - 1)) + jitter
- First backoff (count=1): max(serverDelay, InitialDuration) or InitialDuration
- Second backoff (count=2): initial * multiplier
- And so on, capped at MaxDuration
Parameters:
- backoffCount: The current backoff attempt number (1-indexed)
- jitter: Maximum random duration to add to the delay (0 for no jitter)
- config: Backoff configuration created with NewConfig or MustConfig
- opts: Optional functional options (e.g., WithServerDelay)
Example:
config := exponentialbackoff.MustConfig(1*time.Second, 1*time.Minute, 2.0)
// Basic usage
delay := exponentialbackoff.CalculateDelay(1, 100*time.Millisecond, config)
// With server delay from Retry-After header
delay = exponentialbackoff.CalculateDelay(1, 100*time.Millisecond, config,
exponentialbackoff.WithServerDelay(5*time.Second))
func ComputeJitter ¶
ComputeJitter returns a pseudo-random duration between 0 and max (inclusive). Uses the global rand which is automatically seeded with a random value at startup (Go 1.20+), ensuring different jitter values across concurrent calls. Returns 0 if max is less than or equal to 0.
Types ¶
type Config ¶
type Config struct {
// contains filtered or unexported fields
}
Config holds the immutable configuration for exponential backoff. Create instances using NewConfig or MustConfig.
func MustConfig ¶
MustConfig creates a new Config, panicking on invalid values. Use for static configurations where errors are impossible.
func NewConfig ¶
NewConfig creates a new Config with validation. Returns error if values are invalid:
- initialDuration must be >= 0
- multiplier must be > 0
- maxDuration must be > 0
- initialDuration must be <= maxDuration
func (Config) InitialDuration ¶
InitialDuration returns the starting backoff duration.
func (Config) MaxDuration ¶
MaxDuration returns the maximum backoff duration cap.
func (Config) Multiplier ¶
Multiplier returns the factor by which the backoff increases each attempt.
type DelayOption ¶
type DelayOption func(*delayOptions)
DelayOption is a functional option for CalculateDelay.
func WithServerDelay ¶
func WithServerDelay(d time.Duration) DelayOption
WithServerDelay sets a server-suggested delay (e.g., from Retry-After header). The initial backoff will use max(serverDelay, InitialDuration) as the starting point.