DEV Community

Madhu
Madhu

Posted on

๐ŸŒ€ Let's understand Retries in Spring Boot

๐Ÿ’ก 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>
Enter fullscreen mode Exit fullscreen mode

Step 2
Enable retries in your main class

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

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 ๐ŸŒง๏ธ";
    }
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ” 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.

Top comments (0)