sethvargo/go-retry
Tentang
Pustaka Go untuk melakukan percobaan ulang dengan backoff yang dapat dikonfigurasi
Alat pengembanganYang dapat Anda lakukan
- 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.
Pertumbuhan bintang terukur
- dalam 24 jam
- +1
- dalam 7 hari
- 0
- dalam 15 hari
- -2
- dalam 1 bulan
- Mengumpulkan riwayat
Perubahan bersih pada periode yang tumpang tindih, bukan total harian. Pengukuran yang belum tersedia dibiarkan kosong. Bintang menunjukkan perhatian, bukan kualitas.
README.md
AsliRetry
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), notcrypto/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 exceedc, butWithCappedDuration(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))
Jelajahi proyek terkait
Memuat…