Retrying failed calls in Spring Framework 7
Since Spring Framework 7.0, retry is built into the core framework, with RetryTemplate for code blocks and @Retryable for bean methods. This page runs both against flaky clients, prints real backoff schedules, shows the traps that charge a customer twice or skip the retry entirely, and maps the older Spring Retry project to its replacements.
Contents
Retry in Spring: what it is and where it lives now RetryTemplate: retrying a block of code When retries run out: execute, invoke, excludes and timeout Backoff: fixed, exponential and jitter @Retryable on a bean method Retry and @Transactional together Traps: duplicate side effects and calls on this @ConcurrencyLimit: a bulkhead for one method Spring Retry 2.0 and migrating from it Choosing a retry approach
Retry in Spring: what it is and where it lives now
A retry runs a failed operation again, after a short pause, in the hope that the cause was temporary. A network timeout, an HTTP 503 from a service that is restarting, or a database lock wait often succeeds on the second or third try. Without retry, each of these brief failures becomes an error for the user.
Every retry mechanism answers the same four questions:
- Which failures: only exceptions that can succeed on a later attempt. A validation error or a 404 will fail the same way every time.
- How many times: a maximum number of retries, a time limit, or both.
- How long to wait: the backoff. A fixed pause, a pause that grows each time, and usually some random jitter so that many clients do not retry at the same moment.
- What happens at the end: the caller gets the last exception, a summary of all attempts, or a fallback value.
Spring has offered two answers over the years. For a long time retry lived in a separate project, Spring Retry, with @EnableRetry@Retryable@RecoverRetryTemplateRetryPolicyspring-core@Retryable@ConcurrencyLimitspring-context
| Option | Package | Since | Best for |
|---|---|---|---|
RetryTemplateRetryPolicy | org.springframework.core.retry | Spring Framework 7.0 | Retrying a block of code, with full control and a listener |
@Retryable@EnableResilientMethods | org.springframework.resilience.annotation | Spring Framework 7.0 | Retrying a whole bean method declaratively |
@ConcurrencyLimit | org.springframework.resilience.annotation | Spring Framework 7.0 | Capping how many callers run a method at once |
Spring Retry 2.0 (@EnableRetry@Recover | org.springframework.retry | Separate project, now archived | Existing Spring Boot 3 applications not yet migrated |
| Resilience4j | io.github.resilience4j | Separate library | Circuit breakers, rate limiters and bulkheads together with retry |
The annotation works like @Transactional@EnableResilientMethods
RetryTemplate: retrying a block of code
A stock lookup that times out twice and then answers shows the full cycle: the first failure, two retries and the result. A listener prints each step of the loop:
import java.time.Duration;
import org.springframework.core.retry.RetryException;
import org.springframework.core.retry.RetryListener;
import org.springframework.core.retry.RetryPolicy;
import org.springframework.core.retry.RetryState;
import org.springframework.core.retry.RetryTemplate;
import org.springframework.core.retry.Retryable;
public class RetryTemplateBasics {
static class TransientException extends RuntimeException {
TransientException(String message) {
super(message);
}
}
/** Fails the first {@code failures} calls, then answers. */
static class StockClient {
private final int failures;
private int calls;
StockClient(int failures) {
this.failures = failures;
}
int stockFor(String sku) {
calls++;
if (calls <= failures) {
throw new TransientException("timeout on call " + calls);
}
return 42;
}
}
static class PrintingListener implements RetryListener {
@Override
public void onRetryableExecution(RetryPolicy policy, Retryable<?> retryable,
RetryState state) {
System.out.println(" attempt done: retryCount=" + state.getRetryCount()
+ ", successful=" + state.isSuccessful()
+ ", exceptions=" + state.getExceptions().size());
}
@Override
public void onRetryFailure(RetryPolicy policy, Retryable<?> retryable, Throwable t) {
System.out.println(" retry failed: " + t.getMessage());
}
@Override
public void beforeRetry(RetryPolicy policy, Retryable<?> retryable, RetryState state) {
System.out.println(" before retry, retryCount=" + state.getRetryCount());
}
@Override
public void onRetrySuccess(RetryPolicy policy, Retryable<?> retryable, Object result) {
System.out.println(" retry succeeded with " + result);
}
}
public static void main(String[] args) throws RetryException {
RetryPolicy policy = RetryPolicy.builder()
.maxRetries(3)
.delay(Duration.ofMillis(20))
.includes(TransientException.class)
.build();
RetryTemplate template = new RetryTemplate(policy);
template.setRetryListener(new PrintingListener());
System.out.println("execute(), two failures then success:");
StockClient client = new StockClient(2);
int stock = template.execute(() -> client.stockFor("BOOK-1"));
System.out.println(" result: " + stock + " after " + client.calls + " calls");
System.out.println("invoke(), no failures:");
StockClient healthy = new StockClient(0);
int again = template.invoke(() -> healthy.stockFor("BOOK-1"));
System.out.println(" result: " + again + " after " + healthy.calls + " call");
}
}
execute(), two failures then success:
attempt done: retryCount=0, successful=false, exceptions=1
before retry, retryCount=1
retry failed: timeout on call 2
attempt done: retryCount=1, successful=false, exceptions=2
before retry, retryCount=2
retry succeeded with 42
attempt done: retryCount=2, successful=true, exceptions=2
result: 42 after 3 calls
invoke(), no failures:
attempt done: retryCount=0, successful=true, exceptions=0
result: 42 after 1 call
- The first attempt is not a retry.
reports it withonRetryableExecution and one recorded exception, and noretryCount=0 appears for it, because that callback covers retries only.onRetryFailure runs after the 20 ms pause, with the count already raised to 1 and then 2. The second attempt's failure,beforeRetry , is the onlytimeout on call 2 .onRetryFailure- The third call returned 42, so
fired and the final state saysonRetrySuccess aftersuccessful=true . The caller simply receivedretryCount=2 .42 - With a healthy client,
made one call and the listener saw a single successful execution with no exceptions.invoke
The policy lists what to retry with includesRetryPolicy.withDefaults()new RetryTemplate()
When retries run out: execute, invoke, excludes and timeout
A client that fails on every call shows what the caller receives at the end. The same template is used through both of its entry points, and a second policy adds a time limit:
import java.time.Duration;
import org.springframework.core.retry.RetryException;
import org.springframework.core.retry.RetryPolicy;
import org.springframework.core.retry.RetryTemplate;
import org.springframework.core.retry.Retryable;
public class RetryExhausted {
static class TransientException extends RuntimeException {
TransientException(String message) {
super(message);
}
}
static class InvalidRequestException extends RuntimeException {
InvalidRequestException(String message) {
super(message);
}
}
static int calls;
static String alwaysTimesOut() {
calls++;
throw new TransientException("timeout on call " + calls);
}
static String rejectsRequest() {
calls++;
throw new InvalidRequestException("unknown SKU on call " + calls);
}
/** A Retryable with a readable name, which appears in RetryException messages. */
static Retryable<String> named(String name, Retryable<String> body) {
return new Retryable<>() {
@Override
public String execute() throws Throwable {
return body.execute();
}
@Override
public String getName() {
return name;
}
};
}
public static void main(String[] args) {
RetryTemplate template = new RetryTemplate(RetryPolicy.builder()
.maxRetries(2)
.delay(Duration.ofMillis(10))
.excludes(InvalidRequestException.class)
.build());
System.out.println("1. execute() when every attempt fails:");
calls = 0;
try {
template.execute(named("stock lookup", RetryExhausted::alwaysTimesOut));
} catch (RetryException e) {
System.out.println(" RetryException: " + e.getMessage());
System.out.println(" retry count: " + e.getRetryCount() + ", calls: " + calls);
e.getExceptions().forEach(x -> System.out.println(" recorded: " + x.getMessage()));
System.out.println(" getCause(): " + e.getCause().getMessage());
}
System.out.println("2. invoke() when every attempt fails:");
calls = 0;
try {
template.invoke(RetryExhausted::alwaysTimesOut);
} catch (TransientException e) {
System.out.println(" " + e.getClass().getSimpleName() + ": " + e.getMessage());
for (Throwable s : e.getSuppressed()) {
System.out.println(" suppressed: " + s.getMessage());
}
}
System.out.println("3. an excluded exception is not retried:");
calls = 0;
try {
template.invoke(RetryExhausted::rejectsRequest);
} catch (InvalidRequestException e) {
System.out.println(" " + e.getMessage() + ", calls: " + calls);
}
System.out.println("4. a timeout stops retrying early:");
RetryTemplate withTimeout = new RetryTemplate(RetryPolicy.builder()
.maxRetries(100)
.delay(Duration.ofMillis(50))
.timeout(Duration.ofMillis(120))
.build());
calls = 0;
try {
withTimeout.execute(named("stock lookup", RetryExhausted::alwaysTimesOut));
} catch (RetryException e) {
System.out.println(" RetryException: " + e.getMessage());
System.out.println(" calls made: " + calls);
}
}
}
1. execute() when every attempt fails:
RetryException: Retry policy for operation 'stock lookup' exhausted; aborting execution
retry count: 2, calls: 3
recorded: timeout on call 1
recorded: timeout on call 2
recorded: timeout on call 3
getCause(): timeout on call 3
2. invoke() when every attempt fails:
TransientException: timeout on call 3
3. an excluded exception is not retried:
unknown SKU on call 1, calls: 1
4. a timeout stops retrying early:
RetryException: Retry policy for operation 'stock lookup' would exceed timeout (120ms) due to pending sleep time (50ms); preemptively aborting execution
calls made: 3
- Case 1:
throws the checkedexecute . Its message uses the name returned byRetryException , hereRetryable.getName() ; a plain lambda would show a generated class name that changes between runs. Withstock lookup there were 3 calls, all three exceptions are kept in order, andmaxRetries(2) is the last one.getCause() - Case 2:
rethrows the last original exception,invoke , unwrapped. It suits callers that already handle the client's own exception type.timeout on call 3 - Case 3:
is inInvalidRequestException , so the first failure ended the loop after 1 call. A bad SKU will not get better by waiting.excludes - Case 4: 100 retries were allowed, but the 120 ms timeout stopped the loop after 3 calls. The template checks the next pause before sleeping: at about 100 ms, another 50 ms pause would pass the limit, so it gave up at once.
Matching follows the exception's cause chain, so a TransientExceptionincludesexcludespredicate(Predicate<Throwable>)
Backoff: fixed, exponential and jitter
The pause between attempts matters as much as the number of attempts. A RetryPolicyBackOff
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.LongSummaryStatistics;
import org.springframework.core.retry.RetryPolicy;
import org.springframework.util.backoff.BackOffExecution;
import org.springframework.util.backoff.FixedBackOff;
public class BackoffSchedule {
static List<Long> delays(RetryPolicy policy) {
BackOffExecution execution = policy.getBackOff().start();
List<Long> result = new ArrayList<>();
long next;
while ((next = execution.nextBackOff()) != BackOffExecution.STOP) {
result.add(next);
}
return result;
}
public static void main(String[] args) {
System.out.println("Defaults: " + delays(RetryPolicy.withDefaults()));
System.out.println("Fixed 200 ms: " + delays(RetryPolicy.builder()
.maxRetries(4)
.delay(Duration.ofMillis(200))
.build()));
System.out.println("Exponential: " + delays(RetryPolicy.builder()
.maxRetries(6)
.delay(Duration.ofMillis(100))
.multiplier(2)
.maxDelay(Duration.ofSeconds(1))
.build()));
RetryPolicy jittered = RetryPolicy.builder()
.maxRetries(3)
.delay(Duration.ofMillis(1000))
.multiplier(2)
.jitter(Duration.ofMillis(250))
.build();
List<LongSummaryStatistics> stats = List.of(new LongSummaryStatistics(),
new LongSummaryStatistics(), new LongSummaryStatistics());
for (int i = 0; i < 10000; i++) {
List<Long> sample = delays(jittered);
for (int k = 0; k < sample.size(); k++) {
stats.get(k).accept(sample.get(k));
}
}
System.out.println("Exponential with 250 ms jitter, 10,000 runs, range of each delay"
+ " (rounded to 10 ms):");
for (int k = 0; k < stats.size(); k++) {
LongSummaryStatistics st = stats.get(k);
System.out.println(" delay " + (k + 1) + ": " + Math.round(st.getMin() / 10.0) * 10
+ " to " + Math.round(st.getMax() / 10.0) * 10 + " ms");
}
RetryPolicy custom = RetryPolicy.builder()
.backOff(new FixedBackOff(50, 2))
.build();
System.out.println("FixedBackOff(50, 2): " + delays(custom));
}
}
Defaults: [1000, 1000, 1000]
Fixed 200 ms: [200, 200, 200, 200]
Exponential: [100, 200, 400, 800, 1000, 1000]
Exponential with 250 ms jitter, 10,000 runs, range of each delay (rounded to 10 ms):
delay 1: 1000 to 1250 ms
delay 2: 1500 to 2500 ms
delay 3: 3000 to 5000 ms
FixedBackOff(50, 2): [50, 50]
- The defaults give three pauses of 1000 ms each: 3 retries with a fixed 1 second delay.
- With
the pause doubles from 100 ms to 800 ms, andmultiplier(2) then caps it at 1000 ms for the last two retries.maxDelay - Jitter adds or subtracts a random amount, and the multiplier scales the jitter as well. The second delay ranged from 1500 to 2500 ms, which is 2000 ms plus or minus 500 ms, and the third from 3000 to 5000 ms.
- The first delay only ranged from 1000 to 1250 ms. The Javadoc of
says a jittered value is "never belowExponentialBackOff.setJitter or aboveinitialInterval ", so the lower half of the range is clipped.maxInterval - Any
can replace the built-in one.BackOff produced two 50 ms pauses, and its own attempt limit decided the count.FixedBackOff(50, 2)
Jitter matters when many clients fail at the same moment, for example when a shared service restarts. Without it, they all retry at exactly 100, 200 and 400 ms, and each wave hits the recovering service together.
@Retryable on a bean method
The annotation applies the same policy to a whole method. A price client covers the four outcomes that matter: success after failures, exhaustion, a wrapped cause, and an excluded exception. A listener for MethodRetryEvent
import java.util.Map;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.core.env.MapPropertySource;
import org.springframework.resilience.annotation.EnableResilientMethods;
import org.springframework.resilience.annotation.Retryable;
import org.springframework.resilience.retry.MethodRetryEvent;
public class RetryableAnnotation {
static class TransientException extends RuntimeException {
TransientException(String message) {
super(message);
}
}
static class InvalidRequestException extends RuntimeException {
InvalidRequestException(String message) {
super(message);
}
}
@Configuration
@EnableResilientMethods
static class Config {
@Bean
PriceClient priceClient() {
return new PriceClient();
}
@Bean
RetryLog retryLog() {
return new RetryLog();
}
}
static class RetryLog {
@EventListener
void onRetry(MethodRetryEvent event) {
System.out.println(" event: " + event.getMethod().getName() + " failed with "
+ event.getFailure().getMessage() + ", aborted=" + event.isRetryAborted());
}
}
static class PriceClient {
private int calls;
public int calls() {
return calls;
}
public void reset() {
calls = 0;
}
@Retryable(includes = TransientException.class, maxRetries = 3, delay = 20)
public int price(String sku) {
calls++;
if (calls < 3) {
throw new TransientException("timeout " + calls);
}
return 1999;
}
@Retryable(includes = TransientException.class, maxRetriesString = "${prices.retries}",
delay = 20)
public int alwaysDown(String sku) {
calls++;
throw new TransientException("timeout " + calls);
}
@Retryable(includes = TransientException.class, delay = 20)
public int wrapped(String sku) {
calls++;
if (calls < 2) {
throw new IllegalStateException("lookup failed",
new TransientException("timeout " + calls));
}
return 2499;
}
@Retryable(excludes = InvalidRequestException.class, delay = 20)
public int invalid(String sku) {
calls++;
throw new InvalidRequestException("unknown SKU " + sku);
}
}
interface Call {
int run();
}
static void attempt(String label, PriceClient client, Call call) {
System.out.println(label);
client.reset();
try {
System.out.println(" returned " + call.run() + " (calls: " + client.calls() + ")");
} catch (RuntimeException e) {
System.out.println(" caller sees " + e.getClass().getSimpleName() + ": "
+ e.getMessage() + " (calls: " + client.calls() + ")");
}
}
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext()) {
context.getEnvironment().getPropertySources()
.addFirst(new MapPropertySource("demo", Map.of("prices.retries", "2")));
context.register(Config.class);
context.refresh();
PriceClient client = context.getBean(PriceClient.class);
System.out.println("Bean class: " + client.getClass().getSimpleName());
attempt("1. two transient failures, then success:", client, () -> client.price("A"));
attempt("2. fails every time, maxRetries from a property:", client,
() -> client.alwaysDown("A"));
attempt("3. transient exception as the cause:", client, () -> client.wrapped("A"));
attempt("4. excluded exception:", client, () -> client.invalid("ZZ"));
}
}
}
Bean class: RetryableAnnotation$PriceClient$$SpringCGLIB$$0
1. two transient failures, then success:
event: price failed with timeout 1, aborted=false
event: price failed with timeout 2, aborted=false
returned 1999 (calls: 3)
2. fails every time, maxRetries from a property:
event: alwaysDown failed with timeout 1, aborted=false
event: alwaysDown failed with timeout 2, aborted=false
event: alwaysDown failed with timeout 3, aborted=false
event: alwaysDown failed with Retry policy for operation 'RetryableAnnotation$PriceClient.alwaysDown' exhausted; aborting execution, aborted=true
caller sees TransientException: timeout 3 (calls: 3)
3. transient exception as the cause:
event: wrapped failed with lookup failed, aborted=false
returned 2499 (calls: 2)
4. excluded exception:
event: invalid failed with unknown SKU ZZ, aborted=false
event: invalid failed with Retry policy for operation 'RetryableAnnotation$PriceClient.invalid' exhausted; aborting execution, aborted=true
caller sees InvalidRequestException: unknown SKU ZZ (calls: 1)
- The bean is a CGLIB proxy,
, created because ofPriceClient$$SpringCGLIB$$0 . The retry loop lives in that proxy.@EnableResilientMethods - Case 1 returned 1999 after 3 calls. Spring published a
for each of the two failures, which the caller never saw.MethodRetryEvent - Case 2 read its limit from the property
throughprices.retries=2 , so it made 3 calls. After the third failure, a fourth event withmaxRetriesString reported the exhaustion, and the caller received the last original exception,aborted=true , not atimeout 3 .RetryException - Case 3 threw
, but its cause was aIllegalStateException , so it was retried and returned 2499 on the second call.TransientException - Case 4 threw an excluded exception: 1 call, an event for the failure, then an aborted event. The message of the aborted event comes from the internal
, which is why it says "exhausted" even though no retry happened.RetryException
The attributes mirror the builder: includesvalueexcludespredicatemaxRetriesdelayjittermultipliermaxDelaytimeouttimeUnit...String${...}application.propertiesMonoFlux
Retry and @Transactional together
An order insert that hits a lock timeout twice checks the most important combination: does each attempt get a clean transaction, or does a failed attempt leave its row behind?
import javax.sql.DataSource;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.resilience.annotation.EnableResilientMethods;
import org.springframework.resilience.annotation.Retryable;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
public class RetryWithTransaction {
static class LockTimeoutException extends RuntimeException {
LockTimeoutException(String message) {
super(message);
}
}
@Configuration
@EnableTransactionManagement
@EnableResilientMethods
static class Config {
@Bean
DataSource dataSource() {
return new DriverManagerDataSource("jdbc:h2:mem:retrytx;DB_CLOSE_DELAY=-1");
}
@Bean
JdbcTemplate jdbc(DataSource dataSource) {
JdbcTemplate jdbc = new JdbcTemplate(dataSource);
jdbc.execute("CREATE TABLE orders (id INT AUTO_INCREMENT PRIMARY KEY,"
+ " item VARCHAR(20))");
return jdbc;
}
@Bean
PlatformTransactionManager transactionManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean
OrderService orderService(JdbcTemplate jdbc) {
return new OrderService(jdbc);
}
}
static class OrderService {
private final JdbcTemplate jdbc;
private int attempts;
OrderService(JdbcTemplate jdbc) {
this.jdbc = jdbc;
}
@Transactional
@Retryable(includes = LockTimeoutException.class, maxRetries = 2, delay = 10)
public void placeOrder(String item) {
attempts++;
int attempt = attempts;
TransactionSynchronizationManager.registerSynchronization(
new TransactionSynchronization() {
@Override
public void afterCompletion(int status) {
System.out.println(" attempt " + attempt + ": transaction "
+ (status == STATUS_COMMITTED ? "COMMITTED" : "ROLLED BACK"));
}
});
jdbc.update("INSERT INTO orders (item) VALUES (?)", item);
if (attempt < 3) {
throw new LockTimeoutException("lock wait timeout");
}
}
}
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(Config.class)) {
System.out.println("placeOrder(\"book\"), failing twice before it succeeds:");
context.getBean(OrderService.class).placeOrder("book");
JdbcTemplate jdbc = context.getBean(JdbcTemplate.class);
System.out.println("Rows in orders: " + jdbc.queryForList(
"SELECT item FROM orders", String.class));
}
}
}
placeOrder("book"), failing twice before it succeeds:
attempt 1: transaction ROLLED BACK
attempt 2: transaction ROLLED BACK
attempt 3: transaction COMMITTED
Rows in orders: [book]
- Each attempt ran in its own transaction. The first two inserted a row, threw, and rolled back; the third committed.
- The table holds exactly one
, so the failed attempts left nothing behind.book
This works because the retry advice always runs outside the transaction advice: retry, then transaction, then the method. The Spring Framework reference states this order holds for @Transactional@Cacheableorder@EnableResilientMethods@Async
Traps: duplicate side effects and calls on this
A payment gateway that charges the card and then loses its response shows the most expensive retry mistake. The same program also calls a @Retryable
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.resilience.annotation.EnableResilientMethods;
import org.springframework.resilience.annotation.Retryable;
public class RetryTraps {
static class TimeoutException extends RuntimeException {
TimeoutException(String message) {
super(message);
}
}
/** A payment provider that charges the card, then loses the first response. */
static class PaymentGateway {
final List<String> charges = new ArrayList<>();
private final Set<String> seenKeys = new HashSet<>();
private int calls;
void charge(String order, String idempotencyKey) {
calls++;
if (idempotencyKey == null || seenKeys.add(idempotencyKey)) {
charges.add(order);
}
if (calls == 1) {
throw new TimeoutException("response lost after charging " + order);
}
}
}
@Configuration
@EnableResilientMethods
static class Config {
@Bean
PaymentGateway gateway() {
return new PaymentGateway();
}
@Bean
CheckoutService checkoutService(PaymentGateway gateway) {
return new CheckoutService(gateway);
}
}
static class CheckoutService {
private final PaymentGateway gateway;
CheckoutService(PaymentGateway gateway) {
this.gateway = gateway;
}
@Retryable(includes = TimeoutException.class, delay = 10)
public void pay(String order) {
gateway.charge(order, null);
}
@Retryable(includes = TimeoutException.class, delay = 10)
public void payWithKey(String order) {
gateway.charge(order, "key-" + order);
}
public void checkout(String order) {
this.pay(order);
}
}
static void reset(PaymentGateway gateway) {
gateway.charges.clear();
gateway.calls = 0;
}
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(Config.class)) {
CheckoutService service = context.getBean(CheckoutService.class);
PaymentGateway gateway = context.getBean(PaymentGateway.class);
System.out.println("1. Retrying a call that is not idempotent:");
service.pay("order-7");
System.out.println(" charges: " + gateway.charges);
System.out.println("2. The same retry with an idempotency key:");
reset(gateway);
service.payWithKey("order-8");
System.out.println(" charges: " + gateway.charges + ", gateway calls: "
+ gateway.calls);
System.out.println("3. Calling the @Retryable method on this:");
reset(gateway);
try {
service.checkout("order-9");
} catch (TimeoutException e) {
System.out.println(" no retry, caller sees: " + e.getMessage()
+ ", gateway calls: " + gateway.calls);
}
}
}
}
1. Retrying a call that is not idempotent:
charges: [order-7, order-7]
2. The same retry with an idempotency key:
charges: [order-8], gateway calls: 2
3. Calling the @Retryable method on this:
no retry, caller sees: response lost after charging order-9, gateway calls: 1
- Case 1: the first call charged
and then timed out. From the client's side it failed, so the retry charged the card again, and the customer paid twice.order-7 - Case 2: with an idempotency key, the gateway recognised the second call and did not charge again. Two calls were made, one charge exists. Retry only operations that are idempotent, or make them so with a key the server checks.
- Case 3:
calledcheckout , which goes straight to the target object and skips the proxy. The first timeout went to the caller after 1 gateway call, with no retry at all.this.pay(...)
Other mistakes are quieter. Retrying every exception, the default when includes
@ConcurrencyLimit: a bulkhead for one method
Spring Framework 7.0 added a second resilience annotation. It caps how many threads may run a method at once, which protects a slow downstream system from being flooded, especially with virtual threads, which have no pool size to act as a limit. Six virtual threads call a 100 ms report method limited to 2:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.resilience.InvocationRejectedException;
import org.springframework.resilience.annotation.ConcurrencyLimit;
import org.springframework.resilience.annotation.EnableResilientMethods;
public class ConcurrencyLimitDemo {
@Configuration
@EnableResilientMethods
static class Config {
@Bean
ReportService reportService() {
return new ReportService();
}
}
static class ReportService {
private final AtomicInteger running = new AtomicInteger();
private final AtomicInteger peak = new AtomicInteger();
private String work(String name) throws InterruptedException {
peak.accumulateAndGet(running.incrementAndGet(), Math::max);
Thread.sleep(100);
running.decrementAndGet();
return name;
}
@ConcurrencyLimit(2)
public String blocking(String name) throws InterruptedException {
return work(name);
}
@ConcurrencyLimit(limit = 2, policy = ConcurrencyLimit.ThrottlePolicy.REJECT)
public String rejecting(String name) throws InterruptedException {
return work(name);
}
public int peakAndReset() {
return peak.getAndSet(0);
}
}
interface Call {
String run(String name) throws Exception;
}
static void runSix(String label, ReportService service, Call call) throws Exception {
try (ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor()) {
List<Future<String>> futures = new ArrayList<>();
for (int i = 1; i <= 6; i++) {
String name = "report-" + i;
futures.add(pool.submit(() -> call.run(name)));
}
int done = 0;
int rejected = 0;
for (Future<String> f : futures) {
try {
f.get();
done++;
} catch (ExecutionException e) {
if (e.getCause() instanceof InvocationRejectedException) {
rejected++;
}
}
}
System.out.println(label + ": completed " + done + ", rejected " + rejected
+ ", most running at once " + service.peakAndReset());
}
}
public static void main(String[] args) throws Exception {
try (var context = new AnnotationConfigApplicationContext(Config.class)) {
ReportService service = context.getBean(ReportService.class);
runSix("BLOCK (limit 2, 6 callers)", service, service::blocking);
runSix("REJECT (limit 2, 6 callers)", service, service::rejecting);
}
}
}
BLOCK (limit 2, 6 callers): completed 6, rejected 0, most running at once 2
REJECT (limit 2, 6 callers): completed 2, rejected 4, most running at once 2
- With the default
policy all 6 calls completed, but never more than 2 at a time. The other callers waited for a free slot.BLOCK - With
, the first 2 ran and the other 4 failed at once withREJECT , which a caller can turn into an HTTP 503 or a fallback.InvocationRejectedException
A limit of 1 serialises all calls to the bean instance. limitString@EnableResilientMethods
Spring Retry 2.0 and migrating from it
Many Spring Boot 3 applications still use the separate Spring Retry project. It still works on Spring Framework 7.0, as this program shows with Spring Retry 2.0.13:
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.EnableRetry;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.retry.support.RetryTemplate;
public class LegacySpringRetry {
static class TransientException extends RuntimeException {
TransientException(String message) {
super(message);
}
}
@Configuration
@EnableRetry
static class Config {
@Bean
ShippingClient shippingClient() {
return new ShippingClient();
}
}
static class ShippingClient {
private int calls;
@Retryable(retryFor = TransientException.class, maxAttempts = 3,
backoff = @Backoff(delay = 20, multiplier = 2))
public String quote(String postcode) {
calls++;
System.out.println(" attempt " + calls);
throw new TransientException("carrier timeout " + calls);
}
@Recover
public String fallbackQuote(TransientException e, String postcode) {
return "flat rate for " + postcode + " (after " + e.getMessage() + ")";
}
}
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(Config.class)) {
System.out.println("@Retryable(maxAttempts = 3) with @Recover:");
String quote = context.getBean(ShippingClient.class).quote("SW1A 1AA");
System.out.println(" result: " + quote);
}
System.out.println("RetryTemplate.builder() from Spring Retry:");
RetryTemplate template = RetryTemplate.builder()
.maxAttempts(3)
.fixedBackoff(20)
.retryOn(TransientException.class)
.build();
int[] calls = {0};
String result = template.execute(
context -> {
calls[0]++;
throw new TransientException("timeout " + calls[0]);
},
context -> "recovered after " + context.getRetryCount() + " failures");
System.out.println(" result: " + result + ", calls: " + calls[0]);
}
}
@Retryable(maxAttempts = 3) with @Recover:
attempt 1
attempt 2
attempt 3
result: flat rate for SW1A 1AA (after carrier timeout 3)
RetryTemplate.builder() from Spring Retry:
result: recovered after 3 failures, calls: 3
made 3 calls in total, including the first. The core annotation'smaxAttempts = 3 means 3 retries after the first call, so 4 calls. Copying the number across unchanged adds one attempt.maxRetries = 3- When the attempts ran out, Spring Retry called the
method, matched by exception type and parameters, and the caller received its fallback value instead of an exception.@Recover - The programmatic
took a recovery callback, which saw 3 failures.RetryTemplate.builder()
Three differences matter when you migrate:
- Dependencies:
needs AspectJ on the classpath. Without@EnableRetry , this program fails at startup withaspectjweaver . In Spring Boot 4 the oldNoClassDefFoundError: org/aspectj/lang/annotation/Pointcut is nowspring-boot-starter-aop . The core annotations need neither.spring-boot-starter-aspectj - Version management:
3.5.15 managesspring-boot-dependencies at 2.0.13, but 4.1.2 no longer lists it, so a Boot 4 build must state the version itself.spring-retry - Fallbacks: the core annotation has no
. Catch the final exception in the caller, or use@Recover and handle theRetryTemplate.execute .RetryException
| Spring Retry 2.0 | Spring Framework 7 |
|---|---|
@EnableRetry | @EnableResilientMethods |
@Retryable(retryFor = X.class) | @Retryable(includes = X.class) |
noRetryFor | excludes |
maxAttempts = 3 | maxRetries = 2 |
@Backoff(delay, multiplier, maxDelay, random) | delaymultipliermaxDelayjitter |
@Recover | No equivalent; handle the exception in the caller |
org.springframework.retry.support.RetryTemplate | org.springframework.core.retry.RetryTemplate |
Choosing a retry approach
| Situation | Use |
|---|---|
| A bean method that calls a flaky remote service | @Retryable(includes = ...)@EnableResilientMethods |
| A few lines inside a method, or code that is not a bean | RetryTemplateRetryPolicy |
| The caller needs every failure, not just the last | RetryTemplate.executeRetryException.getExceptions() |
| Logging or metrics for each failed attempt | MethodRetryEventRetryListener |
| Many clients retrying the same service | Exponential delay with maxDelayjitter |
| A hard limit on total time | timeout |
| Too many concurrent callers, especially virtual threads | @ConcurrencyLimitREJECT |
| Circuit breaking or rate limiting as well | |
| An existing Spring Retry application | Keep it working, and migrate using the table above |
Whichever you pick, retry only exceptions that can succeed later, only operations that are safe to repeat, and only through the proxy. The @Retryable