retrykit

package module
v0.3.2 Latest Latest
Warning

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

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

README

go-retry-kit

CI Go Reference License

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()
})

// Manually reset the circuit breaker
cb.Reset()

API

Function / Method Description
Backoff Backoff strategy type (Exponential, Linear, Fixed)
Options Struct configuring retry behavior
Option Functional option for configuring retries
DefaultOptions() Options Return sensible default retry options
Do[T](ctx, fn, opts ...Option) (T, error) Execute fn with retry logic
WithMaxAttempts(n int) Option Set maximum number of attempts
WithBackoff(b Backoff) Option Set the backoff strategy
WithInitialDelay(d time.Duration) Option Set initial delay between retries
WithMaxDelay(d time.Duration) Option Set maximum delay between retries
WithJitter(j bool) Option Enable or disable jitter
WithRetryOn(fn func(error) bool) Option Filter which errors trigger retries
WithOnRetry(fn func(error, int)) Option Set callback invoked before each retry
WithOnSuccess(fn func(int)) Option Set callback invoked on success
WithOnFailure(fn func(error, int)) Option Set callback invoked when all attempts fail
Aggressive() []Option Preset: 5 attempts, fast exponential backoff
Gentle() []Option Preset: 3 attempts, slow exponential backoff
NetworkRequest() []Option Preset: tuned for network requests
DatabaseQuery() []Option Preset: tuned for database queries
RetryError Error returned when all attempts are exhausted
(*RetryError) Error() string Format the retry error message
(*RetryError) Unwrap() error Return the last underlying error
CircuitState Circuit breaker state (Closed, Open, HalfOpen)
(CircuitState) String() string Human-readable state name
CircuitBreaker Circuit breaker implementation
CircuitBreakerOption Functional option for configuring circuit breaker
NewCircuitBreaker(opts ...CircuitBreakerOption) *CircuitBreaker Create a new circuit breaker
(*CircuitBreaker) State() CircuitState Return the current circuit state
(*CircuitBreaker) Reset() Manually reset to Closed state
(*CircuitBreaker) String() string Human-readable breaker description
Call[T](cb *CircuitBreaker, fn func() (T, error)) (T, error) Execute fn through the circuit breaker
WithFailureThreshold(n int) CircuitBreakerOption Set failures before opening the circuit
WithResetTimeout(d time.Duration) CircuitBreakerOption Set open-to-half-open timeout
WithHalfOpenMaxAttempts(n int) CircuitBreakerOption Set max attempts in half-open state
WithOnStateChange(fn) CircuitBreakerOption Set callback for state transitions
WithOnCircuitOpen(fn func(int)) CircuitBreakerOption Set callback when circuit opens
CircuitOpenError Error returned when circuit is open
(*CircuitOpenError) Error() string Format the circuit open error

Development

go test ./...
go vet ./...

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) Reset added in v0.3.0

func (cb *CircuitBreaker) Reset()

Reset manually resets the circuit breaker to the Closed state with zero failures.

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