Can Spring's Retryable or RetryTemplate use Retry-After header for dynamic backoff?

Viewed 1126

Can I make Spring's @Retryable or @RetryTemplate use the number received in a Retry-After header in an HTTP 503 "Service Unavailable" response as delay for the next retry iteration?

For example:

@Retryable(maxAttempts = 42,
           backoff = @Backoff(delay = 1000),
           value = NotYetReady.class)
public boolean isExternalComponentReadyToUse() throws NotYetReady {
    ResponseEntity<String> response = callRestEndpointToCheckReadiness();
    if (!response.getStatus().is2xxSuccessful()) {
        int retryAfterInSeconds = response.getHeaders().get("Retry-After");
        // tell @Retryable to run next attempt after retryAfterInSeconds?
        throw new NotYetReady();
    }
    return true;
}

Our Java app relies on an external component that takes some minutes to come up. That component provides a REST endpoint to check readiness. The endpoint sends back 503 with a Retry-After header if it can estimate how long the remaining setup will take.

1 Answers

One way would be to store the value in a static ThreadLocal (e.g. MyHolder.setDelay(...)) and use delayExpression in the @Backoff() to retrieve that value.

Something like "T(com.foo.MyHolder).getDelay()".

You would need to wire up a RetryOperationsInterceptor as a @Bean with a custom BackoffPolicy and reference it in the @Retryable.interceptor property.

Related