Skip to content
프로젝트

소개

대기 시간을 설정할 수 있는 Go 재시도 라이브러리

개발 도구

이 수치를 측정하는 방법

What you can do

  • 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.

측정된 스타 증가

in 24h
+1
in 7 days
0
in 15 days
-2
in 1 month
기록 수집 중

서로 겹치는 기간의 순증가량이며 일별 합계가 아닙니다. 측정값이 없으면 비워 둡니다. 스타는 관심도를 나타내며 품질을 보장하지 않습니다.

README.md

Original

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))

관련 프로젝트 살펴보기

불러오는 중…