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 ¶
- func Constant(ctx context.Context, base time.Duration, f RetryFunc) error
- func Do(ctx context.Context, b Backoff, f RetryFunc) error
- func DoValue[T any](ctx context.Context, b Backoff, f RetryFuncValue[T]) (T, error)
- func Exponential(ctx context.Context, base time.Duration, f RetryFunc) error
- func Fibonacci(ctx context.Context, base time.Duration, f RetryFunc) error
- func RetryableError(err error) error
- type Backoff
- func NewConstant(base time.Duration) Backoff
- func NewExponential(base time.Duration) Backoff
- func NewFibonacci(base time.Duration) Backoff
- func WithCappedDuration(limit time.Duration, next Backoff) Backoff
- func WithFullJitter(next Backoff) Backoff
- func WithJitter(j time.Duration, next Backoff) Backoff
- func WithJitterPercent(j uint64, next Backoff) Backoff
- func WithMaxRetries(maxRetries uint64, next Backoff) Backoff
- type RetryFunc
- type RetryFuncValue
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Constant ¶
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 ¶
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
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 ¶
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 ¶
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 ¶
RetryableError marks err as retryable. It returns nil if err is nil.
Types ¶
type Backoff ¶
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 ¶
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 ¶
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 ¶
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 ¶
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
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 ¶
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 ¶
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 ¶
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