How To retry Third-party API Elegantly in Spring Boot

Malvin Lok
4 min readNov 12, 2022
Photo by KOBU Agency on Unsplash

Hi guys, I’m Malvin. I am back again. In the past month, I have devoted all of myself to my daily work. Finally, I got a moment to talk about some coding experiences I encountered that day.

As a backend programmer, our daily routine would be calling some third-party service, saving data into the database, and returning information to the FE side.

But here is the thing, you can’t promise all things just went well all the time. Like third-party API, if we need to connect them through the wide area network, we may get time-out occasionally. At this point, we have to retry several times, depending on your retry strategy.

Here is an example I have seen many times in my daily development:


public interface OutSource {
List<Integer> getResult() throws TimeOutException;
}

@Service
public class OutSourceImpl implements OutSource {

static Random random = new Random();
@Override
public List<Integer> getResult() {
//mock failure
if (random.nextInt(2) == 1)
throw new TimeOutException();
return List.of(1, 2, 3);
}
}


@Slf4j
@Service
public class ManuallyRetryService {

@Autowired
private OutSource outSource;

public List<Integer> getOutSourceResult(String data, int retryTimes) {
log.info("trigger time:{}"…

--

--

Malvin Lok

Backend Engineer, focus on Java. Haft-way full-stack developer, interested in React/Flutter. Enjoy life, have fun, and also, be a naturalist(hiker/bicycler).