Use Spring Retry instead of do-while

Lejdi Prifti
3 min readNov 1, 2023

In this article, I’ll outline the advantages of switching from the standard do-while method to Spring Retry when contacting external services.

Spring Retry

Consider the following situation. The source and target microservices are our two. To begin processing its own data, the source microservice needs to get in touch with the target microservice to find out if the data is ready. The data readiness procedure is time-consuming, therefore we are unsure of when it will be finished. Let’s assume that, among a plethora of possible design solutions to this type of issue, we opted to verify the data ready state by a straightforward HTTP request.

Our target microservice includes a very simple logic. It basically defines an endpoint /readiness that based on the number of attemps either throws an exception or returns OK .

@Slf4j
@RestController
@RequestMapping("/target")
public class TargetController {

private static int NUMBER_OF_ATTEMPTS = 0;

@GetMapping("/readiness")
public String isDataReady() throws Exception {
if (NUMBER_OF_ATTEMPTS < 5) {
NUMBER_OF_ATTEMPTS++;
throw new Exception("data is not ready");
}
log.info("data is ready");
NUMBER_OF_ATTEMPTS = 0;
return "OK";
}

}

Now, let’s have a look at the source microservice. It defines a service called ExternalService which makes the call to the target

--

--

Lejdi Prifti
Lejdi Prifti

Written by Lejdi Prifti

Software Engineer @ Linfa | Building daily | Sharing insights

Responses (1)