Skip to main content

How to retry a method call in Spring or Quarkus?

Have you ever come across a situation where you wanted to retry a method invocation automatically?

Let's say you are calling a stock ticker service for a given stock and get a transient error. Since it is a transient error, you will try again and it may work in second attempt.

But what if it doesn't? Well, you will try third time. But how many times can you try like that? More importantly after how much time will you retry?

Imagine if you have a handful of methods like this. Your code will become convoluted with retry logic. Is there a better way?

Well, if you are using spring/spring boot, you are in luck. Here is how you can do that using spring. Let's write our business service as follows.


import java.time.LocalDateTime;
import java.util.concurrent.CompletableFuture;
import lombok.extern.slf4j.Slf4j;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class StockService {

    int count;

    @Retryable(value = RuntimeException.class, 
        backoff = @Backoff(random = true, delay = 1000, maxDelay = 5000, multiplier = 3))
    public LocalDateTime getStockUpdatedTime(String stock) {
        count++;
        log.info("Inside StockService {}", count);
        if (count < 2) {
            throw new RuntimeException();
        }
        return LocalDateTime.now();
    }
}

Following is the application class.


import java.time.LocalDateTime;
import java.util.concurrent.ExecutionException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.retry.annotation.EnableRetry;
import org.springframework.scheduling.annotation.EnableAsync;

@SpringBootApplication
@EnableRetry
@Slf4j
public class Application {

  public static void main(String[] args) throws InterruptedException, ExecutionException {
    ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
    StockService bean = context.getBean(StockService.class);

    log.info("main {}", LocalDateTime.now());
    LocalDateTime stockUpdatedAt = bean.getStockUpdatedTime('ABC');
log.info("stockUpdatedAt {}", stockUpdatedAt);
log.info("main {}", LocalDateTime.now()); } }

Here,

  • Mark your method with @Retryable.
  • Add @EnableRetry to enable the auto scanning of the above annotation.
  • value refers to the exception upon which you want to retry the method invocation.
  • maxAttempts defines the number of retries, the default is 3. 
  • @Backoff referes to the retry expression. Here we are attempting the method invocation 3 times with the following delay computation logic. Min delay of 1 sec and max delay of 5 sec and the generated random delay is then multiplied by the multiplier and used in each retry.

What happend to the caller during the retry? Will it wait until all the retries?

Yes, in this example, the output from main method is printed as if @Retryable was not used at all; i.e., the last two log lines are printed after the call from getStockUpdatedTime() returns.

Wow! this helps. Wait... what happens if your method is within a transaction boundry? i.e., if the method that you want to retry is part of a db transaction.

There are two possibilities. 

  1. The method that you want to retry is annotated with @Transactional annotation.
  2. The caller of the method you want to retry is annotated with @Transactional annotation.
In the first scenario, it works out of the box. You don't have to do anything. If an exception is thrown, transaction will be rolled back and spring will retry your method with a new transacion, depending on your transaction scope.

In the second scenario, instead of annotating getStockUpdatedTime() method, you will have to annotate the caller with @Retryable that is annotated with @Transactional. If you do that, then the transaction boundry and retry are taken care.

One last thing. What if your method is an asynchoronous method? Well, as long as the caller can invoke the callback, the caller thread can be made to wait until all the retries are done. Let's modify the service a little bit as follows.


    @Retryable(value = RuntimeException.class, 
        backoff = @Backoff(random = true, delay = 1000, maxDelay = 5000, multiplier = 3))
    @Async
    public CompletableFuture<LocalDateTime> getStockUpdatedTime(String stock) {
        count++;
        log.info("Inside StockService {}", count);
        if (count < 2) {
            throw new RuntimeException();
        }
        return CompletableFuture.completedFuture(LocalDateTime.now());
    }

and our main method as follows.

    log.info("main {}", LocalDateTime.now());
    LocalDateTime stockUpdatedAt = bean.getStockUpdatedTime('ABC').get();
log.info("getStockUpdatedTime {}", stockUpdatedAt);
log.info("main {}", LocalDateTime.now());

Here the main thread waits until a result or exception is received after the retries. More information can be found here
What about Quarkus? 
You can use @org.eclipse.microprofile.faulttolerance.Retry. It also has similar properties as that of spring. More details can be found here.

Comments

Popular posts from this blog

Installing GoDaddy certificate in Wildfly/Keycloak

In the previous post we saw how to set up Keycloak . Here we will see how to generate and install GoDaddy.com certificate in Keycloak. The steps are similar for Wildfly as well. Step 1: Generate CSR file Run the following commands in your terminal. <mydomain.com> has to be replaced with your actual domain name. keytool -genkey -alias mydomain_com -keyalg RSA -keysize 2048 -keystore mydomain_com.jks keytool -certreq -alias mydomain_com -file mydomain_com.csr -keystore mydomain_com.jks Step 2: Generate certificate Upload  mydomain_com . csr  file content into GoDaddy.com, generate and download certificate for tomcat server (steps to generating SSL certificate is beyond the scope of this article). If you unzip the file, you will see the following files. gd_bundle-g2-g1.crt ..5f8c...3a89.crt   #some file with alphanumeric name gdig2.crt Files 1 and 2 are of our interest. Third file is not required. Step 3: Import certificate to key store Download r

Using Nginx as proxy server for Keycloak

I have used Keycloak  in its very early stage ( when it is was in 2.x version). But now it has come a long way (at this time of writing it is in 21.x) In this article let's configure Keycloak behind Nginx. Here are the points to consider.  If you want to configure Apache2 as a proxy server for your java application, please check  this article . We are going to use a domain name other than localhost Anything other than localhost will require Keycloak to run in production mode which requires SSL configurations etc. Or it requires a proxy server. Lets begin. Requirements Keycloak distribution Ubuntu 22.04 server Configuring Keycloak 1. Download Keycloak from here . 2. Extract it using tar -xvzf  keycloak-21.0.1.tar.gz 3. Create a script file called keycloak.sh with the following contents #!/bin/bash export KEYCLOAK_ADMIN=<admin-username-here> export KEYCLOAK_ADMIN_PASSWORD=<admin-password-here> nohup keycloak-21.0.0/bin/kc.sh start-dev --proxy edge --hostname-strict=fa

Hibernate & Postgresql

If you are using Hibernate 3.5 or above to talk to Postgresql database, have you ever tried to store a byte array? Let's take an example. Here is the mapping which will store and read byte[] from the database. @Lob @Column(name = "image") private byte[] image; Here is the JPA mapping file configuration. <persistence version="2.0"  xmlns="http://java.sun.com/xml/ns/persistence"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">   <persistence-unit name="testPU" transaction-type="JTA">     <provider>org.hibernate.ejb.HibernatePersistence</provider>     <jta-data-source>test</jta-data-source>     <properties>     </properties>   </persistence-unit> </persistence> When you try to save your entity you will get t

Dynamic SOAP Service Client

If you have written SOAP service client, you might know that you need the WSDL file; need to generate Java code for that,compile that Java classes and add it as dependency for your module. What would you do if you have to incorporate your code with a new SOAP service every now and then? What would you do if all you need is to consume the service and do a little processing on the output, i.e., you need the data in XML format? What would you do if you don't have a complete WSDL? What would you do if your service is in .NET whose WSDL is having problem while generating Java classes? Is there a way to write a dynamic client which can consume any SOAP service? .... YES!... there is a way. Let's quickly write a web (SOAP) service. Software used: Java 7 NetBeans IDE 7.4 GlassFish 4.0 Maven Create a web project and choose Glassfish as server. Now add web service (not a rest service) as below. Edit the SimpleService.java as follows. package com.mycom