Retry

This chapter introduces the retry mechanism of Go Resty requests.

Resty uses backoff to increase the retry interval after each retry.

Usage example:

// Create a Resty client
client := resty.New()

// Retry count configuration is on each client
client.
    // Set a non-zero retry count to enable retries
    SetRetryCount(3).
    // You can customize the initial retry wait time.
    // Default is 100 milliseconds.
    SetRetryWaitTime(5 * time.Second).
    // MaxWaitTime can also be overridden.
    // Default is 2 seconds.
    SetRetryMaxWaitTime(20 * time.Second).
    // Set RetryAfter to calculate the callback function for the wait time between retries.
    // The default value (nil) means using exponentially increased backoff time and jitter.
    SetRetryAfter(func(client *resty.Client, resp *resty.Response) (time.Duration, error) {
        return 0, errors.New("Quota exceeded")
    })

By default, resty will retry requests that return non-zero errors during execution. Therefore, the above settings will make resty retry requests that return non-zero errors while increasing the delay after each attempt, up to a maximum of 3 retries.

You can also provide custom retry conditions for the client:

// Create a Resty client
client := resty.New()

client.AddRetryCondition(
    // RetryConditionFunc type is used for retry condition functions
    // Input: non-zero Response OR request execution error
    func(r *resty.Response, err error) bool {
        return r.StatusCode() == http.StatusTooManyRequests
    },
)

The above example will make resty retry requests that end with 429 Too Many Requests status code. It is important to note that when you specify conditions using AddRetryCondition, it will override the default retry behavior, which is to retry when encountering errors during the request process. If you want to retry as default behavior when encountering errors during the request process, you need to configure it as follows:

// Create a Resty client
client := resty.New()

client.AddRetryCondition(
    func(r *resty.Response, err error) bool {
        // Include "err != nil" to simulate the default retry behavior when encountering errors during the request process.
        return err != nil || r.StatusCode() == http.StatusTooManyRequests
    },
)

Multiple retry conditions can be added. It is important to note that if multiple conditions are specified, as long as any one of the conditions is met, a retry will be performed.

You can also use resty.Backoff(...) to implement arbitrary retry scenarios.