retry

package
v0.115.2 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: Apache-2.0 Imports: 5 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package retry provides context-aware retry logic with configurable backoff strategies. It replaces ad-hoc for-loops scattered across fleet services with one correct implementation of exponential backoff + full jitter.

Usage:

err := retry.Do(ctx, func(ctx context.Context) error {
    return callUpstream(ctx)
},
    retry.WithMaxAttempts(3),
    retry.WithBackoff(retry.ExponentialJitter(100*time.Millisecond)),
    retry.WithRetryIf(retry.IsTransient),
)

The default strategy retries up to 3 times with exponential backoff starting at 100 ms and full jitter. Context cancellation always stops retries immediately.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func AlwaysRetry

func AlwaysRetry(err error) bool

AlwaysRetry retries on every non-nil, non-context error.

func Do

func Do(ctx context.Context, fn Func, opts ...Option) error

Do calls fn up to MaxAttempts times, sleeping between failures according to the Backoff strategy. It stops early when:

  • fn returns nil (success)
  • ctx is cancelled or deadline exceeded
  • RetryIf returns false for the returned error
  • MaxAttempts is exhausted

The error from the last attempt is returned. If the context was cancelled, ctx.Err() is returned directly.

Example

Only errors marked Transient are retried when IsTransient is the policy; any other error stops the loop at once.

package main

import (
	"context"
	"errors"
	"fmt"

	"github.com/baditaflorin/go-common/retry"
)

func main() {
	attempts := 0
	err := retry.Do(context.Background(), func(ctx context.Context) error {
		attempts++
		if attempts < 3 {
			return retry.Transient(errors.New("temporarily unavailable"))
		}
		return nil
	},
		retry.WithMaxAttempts(5),
		retry.WithBackoff(retry.NoBackoff()),
		retry.WithRetryIf(retry.IsTransient),
	)
	fmt.Println(attempts, err)
}
Output:
3 <nil>

func IsTransient

func IsTransient(err error) bool

IsTransient is a RetryIfFunc that retries only on errors marked as transient via the Transient sentinel or via errors.As(*TransientError). Use it when only networking / temporary errors should be retried.

Types

type BackoffFunc

type BackoffFunc func(attempt int) time.Duration

BackoffFunc returns the duration to wait before attempt number n (1-based: first retry is n=2). The implementation must be safe for concurrent use.

func ConstantBackoff

func ConstantBackoff(d time.Duration) BackoffFunc

ConstantBackoff returns a BackoffFunc that always waits d.

func ExponentialJitter

func ExponentialJitter(base time.Duration) BackoffFunc

ExponentialJitter returns a BackoffFunc that computes random(0, min(cap, base × 2^(attempt-1))). This is the "Full Jitter" strategy from the AWS Architecture Blog. It collapses the thundering herd better than plain exponential backoff.

retry.ExponentialJitter(100*time.Millisecond)
  attempt 1 → random [0, 100ms]
  attempt 2 → random [0, 200ms]
  attempt 3 → random [0, 400ms]
  ...        capped at 30s by default

func ExponentialJitterCapped

func ExponentialJitterCapped(base, cap time.Duration) BackoffFunc

ExponentialJitterCapped is ExponentialJitter with a configurable cap.

func LinearBackoff

func LinearBackoff(base time.Duration) BackoffFunc

LinearBackoff returns a BackoffFunc that waits base × attempt.

func NoBackoff

func NoBackoff() BackoffFunc

NoBackoff returns a BackoffFunc that never waits (immediate retry).

type Func

type Func func(ctx context.Context) error

Func is the function signature passed to Do.

type Option

type Option func(*Options)

Option is a functional option for Do.

func WithBackoff

func WithBackoff(b BackoffFunc) Option

WithBackoff sets the backoff strategy. See ExponentialJitter, ConstantBackoff, and LinearBackoff helpers.

func WithMaxAttempts

func WithMaxAttempts(n int) Option

WithMaxAttempts sets the maximum total attempts (including the first call). Must be ≥ 1; values < 1 are treated as 1 (no retries).

func WithRetryIf

func WithRetryIf(f RetryIfFunc) Option

WithRetryIf sets the predicate that decides whether an error warrants a retry. Defaults to retrying on all non-nil errors (except context cancellation / deadline exceeded, which always abort).

type Options

type Options struct {
	MaxAttempts int
	Backoff     BackoffFunc
	RetryIf     RetryIfFunc
}

Options control retry behaviour. All fields have sensible defaults (see defaults in Do). Prefer the With* option functions.

type RetryIfFunc

type RetryIfFunc func(err error) bool

RetryIfFunc decides whether an error is retryable. Return true to retry, false to abort immediately.

type TransientError

type TransientError struct{ Cause error }

TransientError marks an error as retryable. Wrap transient errors from the calling site; services like backoffcoord and circuitbreaker already produce these when the upstream is overloaded.

func Transient

func Transient(err error) *TransientError

Transient wraps err as retryable.

func (*TransientError) Error

func (e *TransientError) Error() string

func (*TransientError) Unwrap

func (e *TransientError) Unwrap() error

Jump to

Keyboard shortcuts

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