Spring Retry provides the ability to automatically re-invoke a failed operation. This is helpful when errors may be transient in nature (like a momentary network glitch). Spring Retry provides a declarative control of the process and policy-based behavior that is easy to extend and customize.
To make processing more robust and less prone to failure, it sometimes helps to automatically retry a failed operation in case it might succeed on a subsequent attempt. Errors that are susceptible to intermittent failure are often transient in nature.
Retry should be tried only if you think that it may meet your requirements.
- You should not use it for each use case. This is something you don't build right from the beginning but based on what you learn during development or testing. For example, you might find while testing that when you hit a resource, it works one time, but the next time, it gives a timeout error, then works fine when hit again.
- After checking with the downstream system, you're not able to find out any root cause or solution. You might want to build a Retry feature to handle your application's side, but the first attempt should be to fix the downstream side.
- Retry may cause resource clogging and make things even worse, preventing the application from recovering; therefore, the number of retries has to be limited.
- Retry should not be done for each exception. It should be coded only for a particular type of exception. For example, instead of putting code around Exception.class, do it for SQLException.class.
- Retry can cause multiple threads trying to access the same shared resource and locking can be a big issue. An exponential backoff algorithm has to be applied to continually increase the delay between retries until you reach the maximum limit.
- While applying Retry, idempotency has to be handled. Triggering the same request again should not trigger a duplicate transaction in the system.
Enable Retry:
Put the @EnableRetry annotation in the SpringBoot main class.
@EnableRetry
@SpringBootApplication
public class Demo {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}