retry

package
v5.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 18, 2026 License: AGPL-3.0 Imports: 6 Imported by: 0

Documentation

Overview

Package retry provides retry policies with exponential backoff and optional jitter for resilient operation execution.

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrUnretryable = errors.New("unretryable")

ErrUnretryable marks an error as one that Execute must not retry. Wrap a returned error with Unretryable (or return anything that wraps ErrUnretryable) to stop the retry loop immediately instead of exhausting the remaining attempts.

Functions

func Unretryable

func Unretryable(err error) error

Unretryable wraps err so Execute stops retrying on it. The original error is preserved in the chain, so errors.Is/As against it still work.

Types

type Config

type Config struct {
	MaxAttempts  uint          `env:"MAX_ATTEMPTS"  json:"maxAttempts"  yaml:"maxAttempts"`
	InitialDelay time.Duration `env:"INITIAL_DELAY" json:"initialDelay" yaml:"initialDelay"`
	MaxDelay     time.Duration `env:"MAX_DELAY"     json:"maxDelay"     yaml:"maxDelay"`
	Multiplier   float64       `env:"MULTIPLIER"    json:"multiplier"   yaml:"multiplier"`
	UseJitter    bool          `env:"USE_JITTER"    json:"useJitter"    yaml:"useJitter"`
}

Config configures retry behavior.

func (*Config) EnsureDefaults

func (cfg *Config) EnsureDefaults()

EnsureDefaults sets default values for zero (and invalid) fields. It clamps rather than merely zero-checking so a nonsensical config — a negative delay or a Multiplier below 1 that would shrink the backoff — can't produce a pathological policy, since the constructor returns no error to reject it.

func (*Config) ValidateWithContext

func (cfg *Config) ValidateWithContext(ctx context.Context) error

ValidateWithContext validates the config.

type Policy

type Policy interface {
	Execute(ctx context.Context, operation func(ctx context.Context) error) error
}

Policy executes operations with retry logic.

func NewExponentialBackoffPolicy

func NewExponentialBackoffPolicy(cfg Config) Policy

NewExponentialBackoffPolicy returns a Policy that retries with exponential backoff.

Example
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/primandproper/platform-go/v5/retry"
)

func main() {
	policy := retry.NewExponentialBackoffPolicy(retry.Config{
		MaxAttempts:  3,
		InitialDelay: 10 * time.Millisecond,
		MaxDelay:     100 * time.Millisecond,
		Multiplier:   2.0,
	})

	attempts := 0
	err := policy.Execute(context.Background(), func(_ context.Context) error {
		attempts++
		if attempts < 3 {
			return fmt.Errorf("not yet")
		}
		return nil
	})

	fmt.Println(err)
	fmt.Println(attempts)
}
Output:
<nil>
3

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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