Skip to main content

Spring boot retry tutorial

Spring Retry API

Spring provides spring-retry API for running business logic with retry options and recovery method or operations. In this tutorial we will learn the usage of all these with example. We are using Spring boot application here for our example code.

Maven dependencies

To use spring retry we need below dependencies.


This API provides many annotations which we can use in a declarative manner to implement the same.


Spring AOP is also required for retry implementation.

Retry implementation

To implement retry with our business logic we need to follow steps mentioned in this section.
  1. Enable retry

  2. To enable retry we need to add below annotation on Spring boot main class.
  3. Service interface with Retry annotations

    In service interface we have two methods for business logic which we will execute with retry option and then two recovery methods, one for each business logic. Retry annotation defines the maxAttempts for number of times to retry the execution and backoff attribute defines the delay in milliseconds during each attempt. Recovery methods are mapped with the best matching of method signature for business method. If it is not able to match any of recovery method for a given retry business method then it will throws an exception for no recovery methods found.
    Method "sayHello" with recovery method. If this method is not able to respond in three attempts then it will call the recovery method with default message.
        @Retryable(value=Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 1000))
        public String sayHello(String name)throws Exception;
        public String fallbackMessage(String name);
    Method "sum" with recovery method. If this method is not able to provide sum in three attempts then it will call the recovery method which will return -1.
        @Retryable(value=Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 1000))
        public int sum(int a, int b)throws Exception;
        public int fallbackSum();
  4. Service class implementation

    This class will provide the implementation for the above interface. Below is the complete code for this class.
    import org.springframework.retry.annotation.Recover;
    import org.springframework.stereotype.Service;
    public class HelloServiceImpl implements HelloService {
        public String sayHello(String name) throws Exception {
            System.out.println("Executing sayHello");
                throw new Exception("Throwing exception for retry...");
            return "Hello "+name+"!";
        public String fallbackMessage(String name) {
            return name+": Couldn't say hello. Try next time.";
        public int sum(int a, int b) throws Exception {
            System.out.println("Executing sum");
                throw new Exception("Throwing exception for retry...");
            return a+b;
        public int fallbackSum(){
            return -1;
  5. Spring boot main class implementation

    Main class is a Spring boot main class which contains main method. Here we will call service methods for both scenario when it is able to respond without error and when it has to retry three times with recovery option. We are using Spring application events to execute this code once Spring boot application is up and running. Below is the complete code for this class.
    public class RetryDemoApplication {
        public static void main(String[] args) {
  , args);
        HelloService helloService;
        public void test()throws Exception{
            System.out.println(helloService.sayHello("Black pearl"));
            System.out.println("Sum: "+helloService.sum(0, 0));
            System.out.println("Sum: "+helloService.sum(10, 20));

Executing application

If we run this application then you will see that it is executing the "test" method from main class once application is started. Below is the output after the code execution and here, you can notice that it tries the code to execute three time and then executed recovery method due to all failed attempts. Then it has executed one success scenario where it is able to execute logic in first attempt without any error.
2020-02-16 11:35:23.989  INFO 8519 --- [           main] com.ttj.retrydemo.RetryDemoApplication   : Started RetryDemoApplication in 16.511 seconds (JVM running for 16.886)
Executing sayHello
Executing sayHello
Executing sayHello
ERROR: Couldn't say hello. Try next time.
Executing sayHello
Hello Black pearl!
Executing sum
Executing sum
Executing sum
Sum: -1
Executing sum
Sum: 30

Source code

You can download the complete source code from below Github location.


Post a Comment

Popular Posts

Asynchronous REST service implementation in Spring boot

In this tutorial we will see how to create an asynchronous REST service endpoint using Spring boot application. Asynchronous service works in a way that it will not block the client request and do the processing in separate thread. When work is complete the response returned to the client so our service will be able to handle more client requests at the same time, compare to synchronous processing model. Let's understand how it is working in synchronous mode. In such server/client application at server side it has a pool of threads which are serving the request. If a request received by a thread then it will be blocked until it send the response back to client. In this case if processing doesn't take much time it will be able to process it quickly and accept other client requests but there could be one situation when all threads are busy and not able to accept the new client requests. To overcome of such problems, asynchronous processing model introduced for REST service

SpringBoot - @ConditionalOnProperty example for conditional bean initialization

@ConditionalOnProperty annotation is used to check if specified property available in the environment or it matches some specific value so it can control the execution of some part of code like bean creation. It may be useful in many cases for example enable/disable service if specific property is available. Below are the attributes which can be used for property check. havingValue - Provide the value which need to check against specified property otherwise it will check that value should not be false. matchIfMissing - If true it will match the condition and execute the annotated code when property itself is not available in environment. name - Name of the property to be tested. If you want to test single property then you can directly put the property name as string like "" and if you have multiple properties to test then you can put the names like {"prop.name1","prop.name2"} prefix - It can be use when you want to apply some prefix to

Setting up kerberos in Mac OS X

Kerberos in MAC OS X Kerberos authentication allows the computers in same domain network to authenticate certain services with prompting the user for credentials. MAC OS X comes with Heimdal Kerberos which is an alternate implementation of the kerberos and uses LDAP as identity management database. Here we are going to learn how to setup a kerberos on MAC OS X which we will configure latter in our application. Installing Kerberos In MAC we can use Homebrew for installing any software package. Homebrew makes it very easy to install the kerberos by just executing a simple command as given below. brew install krb5 Once installation is complete, we need to set the below export commands in user's profile which will make the kerberos utility commands and compiler available to execute from anywhere. Open user's bash profile: vi ~/.bash_profile Add below lines: export PATH=/usr/local/opt/krb5/bin:$PATH export PATH=/usr/local/opt/krb5/sbin:$PATH export LDFLAGS=&

Web scraper using JSoup and Spring Boot

What is webscraping Webscraping is a technique to extract or pull the data from a website to gather required information by parsing the HTML source of their websites, such as articles from news or books site, products information from online shopping sites or course information from education sites. There are many organisations who uses web scraper to provide the best experience to their customers, for example extract the price for a smartphone from multiple online websites and show their customers the best and cheap product URL. We will learn here how to code a web scraper by developing a simple new scraper service. News scraper News scraper is used to extract the news articles or other related contents from a news site. Here we are going to create a web scraper application to pull the articles from news site. Below are the operations provided by our news scraper service. List all the authors Search articles by author name Search articles by article title Search articles