21. Retrying Failed Requests

Spring Cloud Netflix offers a variety of ways to make HTTP requests. You can use a load balanced RestTemplate, Ribbon, or Feign. No matter how you choose to your HTTP requests, there is always a chance the request may fail. When a request fails you may want to have the request retried automatically. To accomplish this when using Sping Cloud Netflix you need to include Spring Retry on your application’s classpath. When Spring Retry is present load balanced RestTemplates, Feign, and Zuul will automatically retry any failed requests (assuming you configuration allows it to).

21.1 BackOff Policies

By default no backoff policy is used when retrying requests. If you would like to configure a backoff policy you will need to create a bean of type LoadBalancedBackOffPolicyFactory which will be used to create a BackOffPolicy for a given service.

@Configuration
public class MyConfiguration {
    @Bean
    LoadBalancedBackOffPolicyFactory backOffPolciyFactory() {
        return new LoadBalancedBackOffPolicyFactory() {
            @Override
            public BackOffPolicy createBackOffPolicy(String service) {
                return new ExponentialBackOffPolicy();
            }
        };
    }
}

21.2 Configuration

Anytime Ribbon is used with Spring Retry you can control the retry functionality by configuring certain Ribbon properties. The properties you can use are client.ribbon.MaxAutoRetries, client.ribbon.MaxAutoRetriesNextServer, and client.ribbon.OkToRetryOnAllOperations. See the Ribbon documentation for a description of what there properties do.

[Warning]Warning

Enabling client.ribbon.OkToRetryOnAllOperations includes retring POST requests wich can have a impact on the server’s resources due to the buffering of the request’s body.

In addition you may want to retry requests when certain status codes are returned in the response. You can list the response codes you would like the Ribbon client to retry using the property clientName.ribbon.retryableStatusCodes. For example

clientName:
  ribbon:
    retryableStatusCodes: 404,502

You can also create a bean of type LoadBalancedRetryPolicy and implement the retryableStatusCode method to determine whether you want to retry a request given the status code.

21.2.1 Zuul

You can turn off Zuul’s retry functionality by setting zuul.retryable to false. You can also disable retry functionality on route by route basis by setting zuul.routes.routename.retryable to false.