retrykit

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Mar 12, 2026 License: MIT Imports: 6 Imported by: 0

README

go-retry-kit

Retry with exponential backoff, circuit breaker, and context cancellation for Go.

Installation

go get github.com/philiprehberger/go-retry-kit

Usage

Basic Retry
import "github.com/philiprehberger/go-retry-kit"

data, err := retrykit.Do(ctx, func(ctx context.Context) (string, error) {
    return fetchData(ctx)
})
With Options
data, err := retrykit.Do(ctx, fetchData,
    retrykit.WithMaxAttempts(5),
    retrykit.WithBackoff(retrykit.Exponential),
    retrykit.WithInitialDelay(time.Second),
    retrykit.WithMaxDelay(30*time.Second),
    retrykit.WithJitter(true),
    retrykit.WithRetryOn(func(err error) bool {
        return errors.Is(err, ErrTemporary)
    }),
    retrykit.WithOnSuccess(func(attempt int) {
        log.Printf("succeeded on attempt %d", attempt)
    }),
    retrykit.WithOnFailure(func(err error, attempts int) {
        log.Printf("all %d attempts failed: %v", attempts, err)
    }),
)
Presets
data, err := retrykit.Do(ctx, fetchData, retrykit.NetworkRequest()...)
data, err := retrykit.Do(ctx, queryDB, retrykit.DatabaseQuery()...)
data, err := retrykit.Do(ctx, criticalOp, retrykit.Aggressive()...)
Circuit Breaker
cb := retrykit.NewCircuitBreaker(
    retrykit.WithFailureThreshold(5),
    retrykit.WithResetTimeout(30*time.Second),
    retrykit.WithOnStateChange(func(from, to retrykit.CircuitState) {
        log.Printf("circuit: %s → %s", from, to)
    }),
)

result, err := retrykit.Call(cb, func() (string, error) {
    return fetchData()
})

License

MIT

Documentation

Overview

Package retrykit provides retry with backoff and circuit breaker for Go.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Call

func Call[T any](cb *CircuitBreaker, fn func() (T, error)) (T, error)

Call executes fn through the circuit breaker.

func Do

func Do[T any](ctx context.Context, fn func(ctx context.Context) (T, error), opts ...Option) (T, error)

Do executes fn with retry logic according to the provided options.

Types

type Backoff

type Backoff int

Backoff defines the backoff strategy.

const (
	Exponential Backoff = iota
	Linear
	Fixed
)

type CircuitBreaker

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

CircuitBreaker implements the circuit breaker pattern.

func NewCircuitBreaker

func NewCircuitBreaker(opts ...CircuitBreakerOption) *CircuitBreaker

NewCircuitBreaker creates a new CircuitBreaker with the given options.

func (*CircuitBreaker) State

func (cb *CircuitBreaker) State() CircuitState

State returns the current circuit state.

func (*CircuitBreaker) String

func (cb *CircuitBreaker) String() string

String returns a human-readable description of the circuit breaker state.

type CircuitBreakerOption

type CircuitBreakerOption func(*CircuitBreaker)

CircuitBreakerOption configures a CircuitBreaker.

func WithFailureThreshold

func WithFailureThreshold(n int) CircuitBreakerOption

WithFailureThreshold sets the number of failures before opening the circuit.

func WithHalfOpenMaxAttempts

func WithHalfOpenMaxAttempts(n int) CircuitBreakerOption

WithHalfOpenMaxAttempts sets the max attempts allowed in half-open state.

func WithOnCircuitOpen

func WithOnCircuitOpen(fn func(failures int)) CircuitBreakerOption

WithOnCircuitOpen sets a callback when the circuit opens.

func WithOnStateChange

func WithOnStateChange(fn func(from, to CircuitState)) CircuitBreakerOption

WithOnStateChange sets a callback for state transitions.

func WithResetTimeout

func WithResetTimeout(d time.Duration) CircuitBreakerOption

WithResetTimeout sets how long to wait before transitioning from open to half-open.

type CircuitOpenError

type CircuitOpenError struct{}

CircuitOpenError is returned when the circuit breaker is open.

func (*CircuitOpenError) Error

func (e *CircuitOpenError) Error() string

type CircuitState

type CircuitState int

CircuitState represents the state of the circuit breaker.

const (
	Closed CircuitState = iota
	Open
	HalfOpen
)

func (CircuitState) String

func (s CircuitState) String() string

type Option

type Option func(*Options)

Option is a functional option for configuring retry behavior.

func Aggressive

func Aggressive() []Option

Aggressive returns options for aggressive retry (5 attempts, fast backoff).

func DatabaseQuery

func DatabaseQuery() []Option

DatabaseQuery returns options suited for database queries.

func Gentle

func Gentle() []Option

Gentle returns options for gentle retry (3 attempts, slow backoff).

func NetworkRequest

func NetworkRequest() []Option

NetworkRequest returns options suited for network requests.

func WithBackoff

func WithBackoff(b Backoff) Option

WithBackoff sets the backoff strategy.

func WithInitialDelay

func WithInitialDelay(d time.Duration) Option

WithInitialDelay sets the initial delay between retries.

func WithJitter

func WithJitter(j bool) Option

WithJitter enables or disables jitter.

func WithMaxAttempts

func WithMaxAttempts(n int) Option

WithMaxAttempts sets the maximum number of attempts.

func WithMaxDelay

func WithMaxDelay(d time.Duration) Option

WithMaxDelay sets the maximum delay between retries.

func WithOnFailure added in v0.2.0

func WithOnFailure(fn func(err error, attempts int)) Option

WithOnFailure sets a callback invoked when all attempts have been exhausted.

func WithOnRetry

func WithOnRetry(fn func(error, int)) Option

WithOnRetry sets a callback invoked before each retry.

func WithOnSuccess added in v0.2.0

func WithOnSuccess(fn func(attempt int)) Option

WithOnSuccess sets a callback invoked when the operation succeeds.

func WithRetryOn

func WithRetryOn(fn func(error) bool) Option

WithRetryOn sets a function to determine if an error should be retried.

type Options

type Options struct {
	MaxAttempts  int
	Backoff      Backoff
	InitialDelay time.Duration
	MaxDelay     time.Duration
	Jitter       bool
	RetryOn      func(error) bool
	OnRetry      func(err error, attempt int)
	OnSuccess    func(attempt int)
	OnFailure    func(err error, attempts int)
}

Options configures retry behavior.

func DefaultOptions

func DefaultOptions() Options

DefaultOptions returns sensible default retry options.

type RetryError

type RetryError struct {
	Attempts int
	Last     error
}

RetryError is returned when all attempts have been exhausted.

func (*RetryError) Error

func (e *RetryError) Error() string

func (*RetryError) Unwrap

func (e *RetryError) Unwrap() error

Jump to

Keyboard shortcuts

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