Let's understand Retries in Spring Boot

posted 1 min read

What’s a Retry?
A retry means trying an operation again if it fails the first time. For example:

Your app calls a weather API. It fails because of a slow connection. You try again after 1 second — and it works! ️
Retries help your app become more reliable, especially when dealing with temporary issues.

⚙️ Doing Retries in Spring Boot (The Simple Way)

Step 1 :

Spring Boot has a library called Spring Retry that makes this super easy.Let’s add it first.

<dependency>
    <groupId>org.springframework.retry</groupId>
    <artifactId>spring-retry</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

Step 2 :

Enable retries in your main class

@SpringBootApplication
@EnableRetry
public class RetryDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(RetryDemoApplication.class, args);
    }
}

Step 3 :

Use @Retryable, so wherever a method might fail (for example, calling an external API), you can tell Spring to retry automatically.

@Service
public class WeatherService {

    @Retryable(maxAttempts = 3, backoff = @Backoff(delay = 2000))
    public String callWeatherAPI() {
        System.out.println("Calling weather API...");
        if (Math.random() < 0.7) {
            throw new RuntimeException("API failed!");
        }
        return "Weather is Sunny ☀️";
    }

    @Recover
    public String recover(RuntimeException e) {
        return "Weather service is temporarily unavailable ️";
    }
}

What’s Happening Here

@Retryable → Tells Spring to retry this method up to 3 times.
@Backoff(delay = 2000) → Wait 2 seconds between retries.
@Recover → If all retries fail, this method is called instead of crashing the app.

Retries are like giving your app a second chance to succeed. With just two annotations — @Retryable and @Recover — you can make your Spring Boot app much more reliable.

1 Comment

2 votes
1

More Posts

Upgrading JJWT on Spring Boot 3.3.x for GraalVM and Cloud Native

Ricardo Campos - Sep 3

Power Up Java with AI: Integrate LLaMA 3 Using Spring Boot

Mandeep Dhakal - Jul 30

Creating RESTful API Using Spring Boot for The First Time

didikts - Oct 14, 2024

Integrating Kafka Test Container for Local Development Environment

Amol Gote - Jun 8, 2024

Handling Different Types of Data in Express.js

Riya Sharma - Jun 26
chevron_left