retry

package
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 3 Imported by: 0

Documentation

Overview

Package retry runs a function with configurable retries, exponential backoff, and optional jitter.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Do

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

Do runs fn, retrying on error per the options. It returns nil on the first success, the last error once attempts are exhausted (or pred is false), or ctx.Err() if the context ends.

Example

Retry a flaky operation a few times with exponential backoff.

package main

import (
	"context"
	"errors"
	"fmt"
	"time"

	"github.com/rahmadafandi/fibr/retry"
)

func main() {
	attempts := 0
	err := retry.Do(context.Background(), func() error {
		attempts++
		if attempts < 3 {
			return errors.New("temporary failure")
		}
		return nil
	}, retry.WithAttempts(5), retry.WithDelay(time.Millisecond))

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

func DoValue

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

DoValue is Do for a function that returns a value.

Types

type Option

type Option func(*config)

Option configures a retry.

func WithAttempts

func WithAttempts(n int) Option

WithAttempts sets the total number of attempts including the first. Values below 1 are clamped to 1. The default is 3.

func WithDelay

func WithDelay(d time.Duration) Option

WithDelay sets the base backoff delay. The default is 100ms.

func WithJitter

func WithJitter(frac float64) Option

WithJitter adds random jitter as a fraction (0..1) of each delay. The default is 0 (no jitter).

func WithMaxDelay

func WithMaxDelay(d time.Duration) Option

WithMaxDelay caps the per-attempt backoff delay. Zero (default) means no cap.

func WithMultiplier

func WithMultiplier(m float64) Option

WithMultiplier sets the exponential backoff factor. The default is 2.0.

func WithRetryIf

func WithRetryIf(pred func(error) bool) Option

WithRetryIf retries only when pred(err) is true. The default retries on any non-nil error.

Jump to

Keyboard shortcuts

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