Search code examples
javaspring-elspring-retry

Incremental linear backoff in Spring Retry


I am using the following annotation in a method that I would like retried:

@Retryable(maxAttempts = 5, backoff = @Backoff(delay = 1000))
private boolean myMethod() {
    ...
}

This retry is working as expected, as well as an exponential delay that's not shown. I would like to use a linear incremental retry as opposed to an exponential one (so first a 1-second wait, then 2-second, 3-second, etc.) in some cases. It sounds like I need delayExpresion, but I'm not familiar with SpEL to know what to use here. I tried:

@Retryable(maxAttempts = 5, backoff = @Backoff(delay = 1000, delayExpression = "#{delay + 1000}"))

Is what I'm trying to do (where delay is incremented by 1000) possible with SpEL? Or perhaps, is my approach to the linear retry even correct?


Solution

  • That isn't possible via annotations.

    The Retryable has an interceptor() option:

    /**
     * Retry interceptor bean name to be applied for retryable method. Is mutually
     * exclusive with other attributes.
     * @return the retry interceptor bean name
     */
    String interceptor() default "";
    

    So, you should consider to build a RetryOperationsInterceptor bean via RetryInterceptorBuilder and inject there a custom BackOffPolicy with desired linear logic.