retry

package module
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: Apache-2.0 Imports: 6 Imported by: 276 modules, 335 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.

README

Retry

TestGoDoc

Retry is a Go library for facilitating retry logic and backoff. It's highly extensible with full control over how and when retries occur. You can also write your own custom backoff functions: a Backoff is a func(attempt uint64) (time.Duration, bool).

Features

  • Extensible - Inspired by Go's built-in HTTP package, this Go backoff and retry library is extensible via middleware. You can write custom backoff functions or use a provided filter.

  • Independent - No external dependencies besides the Go standard library, meaning it won't bloat your project.

  • Concurrent - Backoffs hold no state, so one backoff can be reused across calls and shared between goroutines.

  • Context-aware - Use native Go contexts to control cancellation.

Usage

Here is an example use for connecting to a database using Go's database/sql package:

package main

import (
	"context"
	"database/sql"
	"log"
	"time"

	"github.com/sethvargo/go-retry"
)

func main() {
	db, err := sql.Open("mysql", "...")
	if err != nil {
		log.Fatal(err)
	}

	ctx := context.Background()
	if err := retry.Fibonacci(ctx, 1*time.Second, func(ctx context.Context) error {
		if err := db.PingContext(ctx); err != nil {
			// This marks the error as retryable
			return retry.RetryableError(err)
		}
		return nil
	}); err != nil {
		log.Fatal(err)
	}
}

Backoffs

In addition to your own custom algorithms, there are built-in algorithms for backoff in the library.

Constant

A very rudimentary backoff, just returns a constant value. Here is an example:

1s -> 1s -> 1s -> 1s -> 1s -> 1s

Usage:

retry.NewConstant(1 * time.Second)
Exponential

Arguably the most common backoff, the next value is double the previous value. Here is an example:

1s -> 2s -> 4s -> 8s -> 16s -> 32s -> 64s

Usage:

retry.NewExponential(1 * time.Second)
Fibonacci

The Fibonacci backoff uses the Fibonacci sequence to calculate the backoff. The next value is the sum of the current value and the previous value. This means retries happen quickly at first, but then gradually slow down, ideal for network-type issues. Here is an example:

1s -> 1s -> 2s -> 3s -> 5s -> 8s -> 13s

Usage:

retry.NewFibonacci(1 * time.Second)

Modifiers (Middleware)

The built-in backoff algorithms never terminate and have no caps or limits - you control their behavior with middleware. There's built-in middleware, but you can also write custom middleware.

Jitter

To reduce the chances of a thundering herd, add random jitter to the returned value.

b := retry.NewFibonacci(1 * time.Second)

// Return the next value, +/- 500ms
b = retry.WithJitter(500*time.Millisecond, b)

// Return the next value, +/- 5% of the result
b = retry.WithJitterPercent(5, b)

// Return a random value in [0, next value)
b = retry.WithFullJitter(b)
MaxRetries

To terminate a retry, specify the maximum number of retries. Note this is retries, not attempts. Attempts is retries + 1.

b := retry.NewFibonacci(1 * time.Second)

// Stop after 4 retries, when the 5th attempt has failed. In this example, the
// worst case elapsed time would be 1s + 1s + 2s + 3s = 7s.
b = retry.WithMaxRetries(4, b)
CappedDuration

To ensure an individual calculated duration never exceeds a value, use a cap:

b := retry.NewFibonacci(1 * time.Second)

// Ensure the maximum value is 2s. In this example, the sleep values would be
// 1s, 1s, 2s, 2s, 2s, 2s...
b = retry.WithCappedDuration(2*time.Second, b)
Total time

To limit the total time spent retrying, set a deadline on the context:

ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()

// When the deadline passes, err wraps both context.DeadlineExceeded and the
// last error from the function.
err := retry.Do(ctx, retry.NewFibonacci(1*time.Second), func(ctx context.Context) error {
	// ...
	return nil
})

Notes and Caveats

  • Randomization uses math/rand/v2 (non-cryptographic, automatically seeded), not crypto/rand.
  • The order of middleware matters. For example, jitter added outside a cap can return a value above the cap: WithJitter(j, WithCappedDuration(c, b)) can exceed c, but WithCappedDuration(c, WithJitter(j, b)) cannot.

Upgrading from v0.6

Backoff changed from an interface with a Next method to a function, func(attempt uint64) (time.Duration, bool). Do passes the number of retries so far, starting at 0. Code that only passes the built-in backoffs and middleware to Do compiles without changes. The cases below need edits.

Calling Next directly
// Before
next, stop := b.Next()

// After
next, stop := b(attempt)
Custom backoffs and middleware built with BackoffFunc

BackoffFunc is gone. Return a plain function instead:

// Before
func withShift(shift time.Duration, next retry.Backoff) retry.Backoff {
	return retry.BackoffFunc(func() (time.Duration, bool) {
		val, stop := next.Next()
		if stop {
			return 0, true
		}
		return val + shift, false
	})
}

// After
func withShift(shift time.Duration, next retry.Backoff) retry.Backoff {
	return func(attempt uint64) (time.Duration, bool) {
		val, stop := next(attempt)
		if stop {
			return 0, true
		}
		return val + shift, false
	}
}
Types with a Next method

A type that implemented the old interface no longer satisfies Backoff. Add the attempt parameter to its Next method and pass the method value to Do:

// Before
func (b *myBackoff) Next() (time.Duration, bool) { ... }

err := retry.Do(ctx, &myBackoff{}, f)

// After
func (b *myBackoff) Next(attempt uint64) (time.Duration, bool) { ... }

err := retry.Do(ctx, (&myBackoff{}).Next, f)
WithMaxDuration

WithMaxDuration is gone. Set a deadline on the context instead:

// Before
b = retry.WithMaxDuration(5*time.Second, b)
err := retry.Do(ctx, b, f)

// After
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
err := retry.Do(ctx, b, f)

The returned error wraps both context.DeadlineExceeded and the last error from f. Unlike WithMaxDuration, the deadline also cancels a call to f that is still running when time runs out.

Sharing one backoff across Do calls

Before, Do calls that shared one backoff also shared its retry count, so a shared WithMaxRetries(100, b) allowed 100 retries across all of those calls combined. Now each Do call counts its own retries from 0. To keep one limit across calls, count the retries in your own middleware:

var used atomic.Uint64

withBudget := func(limit uint64, next retry.Backoff) retry.Backoff {
	return func(attempt uint64) (time.Duration, bool) {
		if used.Add(1) > limit {
			return 0, true
		}
		return next(attempt)
	}
}

b := withBudget(100, retry.NewExponential(1*time.Second))

Documentation

Overview

Package retry retries Go functions that fail temporarily, waiting between attempts according to a Backoff.

A Backoff is a function of the attempt number. Middleware such as WithMaxRetries and WithJitter wraps one Backoff in another. The function passed to Do marks the errors to retry with RetryableError, and Do returns any other error right away.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Constant

func Constant(ctx context.Context, base time.Duration, f RetryFunc) error

Constant calls Do with NewConstant(base). With no retry limit, it retries until f succeeds, f returns an error not marked with RetryableError, or ctx is done.

func Do

func Do(ctx context.Context, b Backoff, f RetryFunc) error

Do is DoValue for a function that returns only an error.

Example (CustomRetry)
package main

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"
	"sync/atomic"
	"time"

	"github.com/sethvargo/go-retry"
)

func main() {
	// The test server returns 503 for the first two requests and 200 after that.
	var requests atomic.Int64
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if requests.Add(1) <= 2 {
			w.WriteHeader(http.StatusServiceUnavailable)
			return
		}
		fmt.Fprint(w, "ok")
	}))
	defer srv.Close()

	client := &http.Client{Timeout: 5 * time.Second}
	b := retry.WithMaxRetries(3, retry.NewConstant(1*time.Millisecond))

	// Do retries only errors wrapped with RetryableError. This function wraps
	// errors for 5xx responses, so Do retries them, and returns 4xx errors as is.
	err := retry.Do(context.Background(), b, func(ctx context.Context) error {
		req, err := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL, nil)
		if err != nil {
			return err
		}

		resp, err := client.Do(req)
		if err != nil {
			return err
		}
		defer resp.Body.Close()

		switch resp.StatusCode / 100 {
		case 4:
			return fmt.Errorf("bad response: %d", resp.StatusCode)
		case 5:
			return retry.RetryableError(fmt.Errorf("bad response: %d", resp.StatusCode))
		default:
			return nil
		}
	})
	fmt.Println(err, requests.Load())

}
Output:
<nil> 3
Example (Simple)
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/sethvargo/go-retry"
)

func main() {
	ctx := context.Background()

	b := retry.NewFibonacci(1 * time.Nanosecond)

	i := 0
	err := retry.Do(ctx, retry.WithMaxRetries(3, b), func(ctx context.Context) error {
		fmt.Printf("%d\n", i)
		i++
		return retry.RetryableError(fmt.Errorf("oops"))
	})
	fmt.Println(err)

}
Output:
0
1
2
3
oops
Example (Timeout)
package main

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

	"github.com/sethvargo/go-retry"
)

func main() {
	// To limit the total time spent retrying, set a deadline on the context.
	ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
	defer cancel()

	err := retry.Do(ctx, retry.NewConstant(10*time.Millisecond), func(_ context.Context) error {
		return retry.RetryableError(errors.New("database is down"))
	})

	// The error wraps both the context error and the last error from f.
	fmt.Println(errors.Is(err, context.DeadlineExceeded))
	fmt.Println(err)

}
Output:
true
context deadline exceeded
database is down

func DoValue added in v0.3.0

func DoValue[T any](ctx context.Context, b Backoff, f RetryFuncValue[T]) (T, error)

DoValue calls f until it succeeds, returns an error not marked with RetryableError, the backoff stops, or ctx is done. The provided context is the same context passed to f. To limit the total time spent retrying, use context.WithTimeout on ctx.

When the backoff stops, DoValue returns the error that was passed to RetryableError. When ctx is done, it returns context.Cause joined with the last error from f, if there was one.

Example
package main

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

	"github.com/sethvargo/go-retry"
)

func main() {
	b := retry.WithMaxRetries(3, retry.NewConstant(1*time.Millisecond))

	attempts := 0
	val, err := retry.DoValue(context.Background(), b, func(_ context.Context) (string, error) {
		attempts++
		if attempts < 3 {
			return "", retry.RetryableError(errors.New("not ready"))
		}
		return "ready", nil
	})
	fmt.Println(val, err, attempts)

}
Output:
ready <nil> 3

func Exponential

func Exponential(ctx context.Context, base time.Duration, f RetryFunc) error

Exponential calls Do with NewExponential(base). With no retry limit, it retries until f succeeds, f returns an error not marked with RetryableError, or ctx is done.

func Fibonacci

func Fibonacci(ctx context.Context, base time.Duration, f RetryFunc) error

Fibonacci calls Do with NewFibonacci(base). With no retry limit, it retries until f succeeds, f returns an error not marked with RetryableError, or ctx is done.

func RetryableError

func RetryableError(err error) error

RetryableError marks err as retryable. It returns nil if err is nil.

Types

type Backoff

type Backoff func(attempt uint64) (next time.Duration, stop bool)

Backoff returns the wait before the next retry, or stop=true to end retrying. Do passes the number of retries made so far, starting at 0. The built-in backoffs and middleware depend only on attempt, so one value can be reused across Do calls and shared between goroutines.

Example
package main

import (
	"fmt"
	"time"

	"github.com/sethvargo/go-retry"
)

func main() {
	// A custom backoff: wait 100ms more on each retry, and stop after 3 retries.
	linear := retry.Backoff(func(attempt uint64) (time.Duration, bool) {
		if attempt >= 3 {
			return 0, true
		}
		return time.Duration(attempt+1) * 100 * time.Millisecond, false
	})

	// A custom middleware: add shift to every wait from next.
	withShift := func(shift time.Duration, next retry.Backoff) retry.Backoff {
		return func(attempt uint64) (time.Duration, bool) {
			val, stop := next(attempt)
			if stop {
				return 0, true
			}
			return val + shift, false
		}
	}

	b := withShift(1*time.Second, linear)
	for attempt := range uint64(4) {
		fmt.Println(b(attempt))
	}
}
Output:
1.1s false
1.2s false
1.3s false
0s true

func NewConstant

func NewConstant(base time.Duration) Backoff

NewConstant returns a backoff that always waits base. It panics if base is less than or equal to zero.

Example
package main

import (
	"fmt"
	"time"

	"github.com/sethvargo/go-retry"
)

func main() {
	b := retry.NewConstant(1 * time.Second)

	for i := range 5 {
		val, _ := b(uint64(i))
		fmt.Printf("%v\n", val)
	}
}
Output:
1s
1s
1s
1s
1s

func NewExponential

func NewExponential(base time.Duration) Backoff

NewExponential returns a backoff that waits base, then doubles the wait on each retry (1, 2, 4, 8, 16, 32, 64...). Once the wait overflows, it stays at math.MaxInt64.

It panics if base is less than or equal to zero.

Example
package main

import (
	"fmt"
	"time"

	"github.com/sethvargo/go-retry"
)

func main() {
	b := retry.NewExponential(1 * time.Second)

	for i := range 5 {
		val, _ := b(uint64(i))
		fmt.Printf("%v\n", val)
	}
}
Output:
1s
2s
4s
8s
16s

func NewFibonacci

func NewFibonacci(base time.Duration) Backoff

NewFibonacci returns a backoff that waits base twice, then the sum of the previous two waits on each retry (1, 1, 2, 3, 5, 8, 13...). Once the wait overflows, it stays at math.MaxInt64.

It panics if base is less than or equal to zero.

Example
package main

import (
	"fmt"
	"time"

	"github.com/sethvargo/go-retry"
)

func main() {
	b := retry.NewFibonacci(1 * time.Second)

	for i := range 5 {
		val, _ := b(uint64(i))
		fmt.Printf("%v\n", val)
	}
}
Output:
1s
1s
2s
3s
5s

func WithCappedDuration

func WithCappedDuration(limit time.Duration, next Backoff) Backoff

WithCappedDuration limits each wait from next to at most limit. It returns stop=true only when next does. To limit the total time spent retrying, use context.WithTimeout on the context passed to Do.

Example
package main

import (
	"fmt"
	"time"

	"github.com/sethvargo/go-retry"
)

func main() {
	b := retry.WithCappedDuration(5*time.Second, retry.NewExponential(1*time.Second))

	for attempt := range uint64(5) {
		fmt.Println(b(attempt))
	}
}
Output:
1s false
2s false
4s false
5s false
5s false

func WithFullJitter added in v0.4.0

func WithFullJitter(next Backoff) Backoff

WithFullJitter replaces each wait from next with a random value in [0, wait). For example, a 20s wait becomes anything from 0 up to just under 20s. Retries from many clients end up further apart than with WithJitter. See https://aws.amazon.com/blogs/architecture/exponential-backoff-and-jitter/.

Example
package main

import (
	"fmt"
	"time"

	"github.com/sethvargo/go-retry"
)

func main() {
	// Each wait is anywhere in [0, 2s).
	b := retry.WithFullJitter(retry.NewConstant(2 * time.Second))

	for attempt := range uint64(3) {
		next, _ := b(attempt)
		fmt.Println(next >= 0 && next < 2*time.Second)
	}
}
Output:
true
true
true

func WithJitter

func WithJitter(j time.Duration, next Backoff) Backoff

WithJitter adds a random amount in [-j, j) to each wait from next. For example, with j = 5s and a 20s wait, the result is between 15s and 25s. The result is never below 0 or above math.MaxInt64.

Example
package main

import (
	"fmt"
	"time"

	"github.com/sethvargo/go-retry"
)

func main() {
	// Each wait is 2s +/- 500ms.
	b := retry.WithJitter(500*time.Millisecond, retry.NewConstant(2*time.Second))

	for attempt := range uint64(3) {
		next, _ := b(attempt)
		fmt.Println(next >= 1500*time.Millisecond && next <= 2500*time.Millisecond)
	}
}
Output:
true
true
true

func WithJitterPercent

func WithJitterPercent(j uint64, next Backoff) Backoff

WithJitterPercent multiplies each wait from next by a random factor in [1-j/100, 1+j/100). For example, with j = 5 and a 20s wait, the result is between 19s and 21s. A j above 100 counts as 100.

Example
package main

import (
	"fmt"
	"time"

	"github.com/sethvargo/go-retry"
)

func main() {
	// Each wait is 2s +/- 10%.
	b := retry.WithJitterPercent(10, retry.NewConstant(2*time.Second))

	for attempt := range uint64(3) {
		next, _ := b(attempt)
		fmt.Println(next >= 1800*time.Millisecond && next <= 2200*time.Millisecond)
	}
}
Output:
true
true
true

func WithMaxRetries

func WithMaxRetries(maxRetries uint64, next Backoff) Backoff

WithMaxRetries executes the backoff function up until the maximum retries. Note this is retries, not attempts. Attempts is retries + 1.

Example
package main

import (
	"fmt"
	"time"

	"github.com/sethvargo/go-retry"
)

func main() {
	b := retry.WithMaxRetries(3, retry.NewFibonacci(1*time.Second))

	for attempt := range uint64(5) {
		fmt.Println(b(attempt))
	}
}
Output:
1s false
1s false
2s false
0s true
0s true

type RetryFunc

type RetryFunc func(ctx context.Context) error

RetryFunc is a function passed to Do.

type RetryFuncValue added in v0.3.0

type RetryFuncValue[T any] func(ctx context.Context) (T, error)

RetryFuncValue is a function passed to DoValue which returns a value.

Jump to

Keyboard shortcuts

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