Retry with Feign Client
OpenFeign is a pretty handy integration to Spring Cloud for Spring Boot applicaiton. Feign is a Java to HTTP client binder inspired by Retrofit, JAXRS-2.0, and WebSocket. It allows to write code conveniently on top of HTTP libraries.
One of the prime and useful aspect of Feign is Retry. There can be several use cases where we may like to retry API calls from client. For example, a common use case can be retyring calls when client receives HTTP 504 (Gateway Timeout). There’s possibility to widen the scope of retry by customized Retry aspect in Feign.
By default, a Feign Client never retires for a failed call (It makes sense though). To enable retry, we need to slap this bean to spring boot application:
You may like to check the Default Retryer class for customized period and maximum attempts. In above case for example, there will be one retry after 100ms from first failure.
Slapping this bean will cause retry only for IOExceptions. In practical, we may like to extend the scope of retry for specific HTTP status code. For this, we need tweaking another aspect of Feign, which is ErrorDecoder.
An HTTP request not falling in 2XX range will trigger ErrorDecoder’s decode method. We can register a custom error decoder to wrap the failure into a custom exception and to have fine grained control.
If we want to retry the request again, we need to throw a RetryableException. In above gist, we are propagating RetryableException if exception is of same kind (this we need for comply with multiple retries with backoff strategy). The later part, we are interested specifically for response withHTTP Status Code 500. We create a RetryableException out of the response to trigger another retry with configured strategy. A complete demonstration can be found here.