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)