http retry for Request Timeout (408)

3.2k Views Asked by At

Using hashicorp go-retryablehttp library (https://github.com/hashicorp/go-retryablehttp)

It retries automatically for all 5xx code:

retryablehttp performs automatic retries under certain conditions. Mainly, if an error is returned by the client (connection errors, etc.), or if a 500-range response code is received (except 501), then a retry is invoked after a wait period. Otherwise, the response is returned and left to the caller to interpret.

Is that possible it retries on Request Timeout, e.g. on 408 http status code just ootb?
or I should build some custom wrappers?

2

There are 2 best solutions below

0
On BEST ANSWER

You can implement your own retry policy and pass it to the Client.CheckRetry field.

Doc ref:

Code ref:

The code might look like something similar to

package main

import (
    "context"
    "net/http"

    "github.com/hashicorp/go-retryablehttp"
)

func main() {

    retryClient := retryablehttp.NewClient()
    retryClient.RetryMax = 10
    retryClient.CheckRetry = func(ctx context.Context, resp *http.Response, err error) (bool, error) {
        ok, e := retryablehttp.DefaultRetryPolicy(ctx, resp, err)
        if !ok && resp.StatusCode == http.StatusRequestTimeout {
            return true, nil 
            // return true for a retry, 
            // if e is nil,
            // you might want to populate that error 
            // to propagate it.
            // see https://github.com/hashicorp/go-retryablehttp/blob/02c1586c8f14be23e7eeb522f1094afbabf45e93/client.go#L673
        }
        return ok, e
    }
}
0
On

As source code specify in line 354 in file client.go, you can configure the CheckRetry function to retry in any custom scenario.

    // CheckRetry specifies the policy for handling retries, and is called
    // after each request. The default policy is DefaultRetryPolicy.
    CheckRetry CheckRetry

Only you need to do is write a function in below type and configure the retryablehttp.Client.CheckRetry with that custom implementation.

type CheckRetry func(ctx context.Context, resp *http.Response, err error) (bool, error)