Retry Using Resilience4j & Spring Retry

Kablumndl
2 min readJul 24, 2021

When we are working in a microservice then anything could happen. lets image a scenario where downstream services is consumed by upstream service and due to the limitation in threadpool of downstream service.

Sometimes it is not feasible to increase number of worker thread in thread pool but business must continue without impact. Generally we are getting timeout/socketConnection exception when downstream service is not connected. We have to retry for a certain number of times.

Usually, we should consider Retry operation in certain scenarios.

  1. HTTP call to a REST Endpoint
  2. Sending or retrieving messages from Queue
  3. Remote Procedure call or a web service
  4. Fetching or storing data in clustered databases

We can hit remote service multiple times when we will get some runtime exception or the downstream service return specific code or in downstream services worker thread not able to process the requests.

This can be achieve from Spring Framework Retry and Resilience4j

Below is the configuration snippet:-

resilience4j:retry:instances:productService:max-attempts: 3wait-duration: 90000retryExceptions:- org.springframework.web.client.HttpServerErrorException- java.io.IOException

If we want to same in Spring framework , we can use @Retryable, below is the code snippet.

import org.springframework.retry.annotation.Backoff;import org.springframework.retry.annotation.Recover;import org.springframework.retry.annotation.Retryable;import com.retrable.controller.exception.ServiceNotAvailableException;public interface ICustomerAdapter {@Retryable(value = {ServiceNotAvailableException.class}, maxAttempts = 3, backoff = @Backoff(delay = 1000))public String getProductResponse(boolean retrySimulate, boolean retryFallbackSimulate);@Recoverpublic String getFallBackResponse(RuntimeException re);}

Complete POC project committed in git, below are the links:-

https://github.com/kablu/spring-retry-poc.git

*******************************************************************

--

--

Kablumndl

Java Developer, Software Engineer, Spring, Spark, MicroService, PostgresSQL