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

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 and @Recover. Since Spring Framework 7.0, retry is part of the core framework: RetryTemplate and RetryPolicy live in spring-core, and the @Retryable and @ConcurrencyLimit annotations live in spring-context. The Spring Retry README now says the project "has been superseded by Spring Framework 7 and is now archived".

Retry options for Spring applications
OptionPackageSinceBest for
RetryTemplate + RetryPolicyorg.springframework.core.retrySpring Framework 7.0Retrying a block of code, with full control and a listener
@Retryable + @EnableResilientMethodsorg.springframework.resilience.annotationSpring Framework 7.0Retrying a whole bean method declaratively
@ConcurrencyLimitorg.springframework.resilience.annotationSpring Framework 7.0Capping how many callers run a method at once
Spring Retry 2.0 (@EnableRetry, @Recover)org.springframework.retrySeparate project, now archivedExisting Spring Boot 3 applications not yet migrated
Resilience4jio.github.resilience4jSeparate libraryCircuit breakers, rate limiters and bulkheads together with retry

The annotation works like @Transactional: the bean is wrapped in a proxy, and the proxy runs the method inside a retry loop. The same proxy limits apply, as the traps section shows. Every program on this page is a complete class that runs on Spring Framework 7.0.10 without Spring Boot. Spring Boot 4.1.2 adds no auto-configuration for these annotations, so in a Boot application you also add @EnableResilientMethods to a configuration class yourself.

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:

Java
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");
    }
}
Output
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. onRetryableExecution reports it with retryCount=0 and one recorded exception, and no onRetryFailure appears for it, because that callback covers retries only.
  • beforeRetry runs after the 20 ms pause, with the count already raised to 1 and then 2. The second attempt's failure, timeout on call 2, is the only onRetryFailure.
  • The third call returned 42, so onRetrySuccess fired and the final state says successful=true after retryCount=2. The caller simply received 42.
  • With a healthy client, invoke made one call and the listener saw a single successful execution with no exceptions.

The policy lists what to retry with includes. Without it, every exception is retried. RetryPolicy.withDefaults() means 3 retries with a fixed 1 second delay, and new RetryTemplate() uses it.

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:

Java
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);
        }
    }
}
Output
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: execute throws the checked RetryException. Its message uses the name returned by Retryable.getName(), here stock lookup; a plain lambda would show a generated class name that changes between runs. With maxRetries(2) there were 3 calls, all three exceptions are kept in order, and getCause() is the last one.
  • Case 2: invoke rethrows the last original exception, timeout on call 3, unwrapped. It suits callers that already handle the client's own exception type.
  • Case 3: InvalidRequestException is in excludes, so the first failure ended the loop after 1 call. A bad SKU will not get better by waiting.
  • 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 TransientException wrapped in another exception still counts as transient. When includes and excludes are not enough, predicate(Predicate<Throwable>) can inspect the exception, for example to retry only HTTP status 503.

Backoff: fixed, exponential and jitter

The pause between attempts matters as much as the number of attempts. A RetryPolicy exposes its delays as a BackOff, so this program prints the schedule each setting produces without waiting for it:

Java
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));
    }
}
Output
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 multiplier(2) the pause doubles from 100 ms to 800 ms, and maxDelay then caps it at 1000 ms for the last two retries.
  • 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 ExponentialBackOff.setJitter says a jittered value is "never below initialInterval or above maxInterval", so the lower half of the range is clipped.
  • Any BackOff can replace the built-in one. FixedBackOff(50, 2) produced two 50 ms pauses, and its own attempt limit decided the count.

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 logs each failure:

Java
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"));
        }
    }
}
Output
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, PriceClient$$SpringCGLIB$$0, created because of @EnableResilientMethods. The retry loop lives in that proxy.
  • Case 1 returned 1999 after 3 calls. Spring published a MethodRetryEvent for each of the two failures, which the caller never saw.
  • Case 2 read its limit from the property prices.retries=2 through maxRetriesString, so it made 3 calls. After the third failure, a fourth event with aborted=true reported the exhaustion, and the caller received the last original exception, timeout 3, not a RetryException.
  • Case 3 threw IllegalStateException, but its cause was a TransientException, so it was retried and returned 2499 on the second call.
  • 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 RetryException, which is why it says "exhausted" even though no retry happened.

The attributes mirror the builder: includes (or value), excludes, predicate, maxRetries, delay, jitter, multiplier, maxDelay and timeout, with timeUnit defaulting to milliseconds. Each numeric attribute has a ...String variant that accepts ${...} placeholders and SpEL, which keeps limits in application.properties. On a method returning a Reactor Mono or Flux, the annotation decorates the returned pipeline with a Reactor retry instead of looping around the call.

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?

Java
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));
        }
    }
}
Output
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 book, so the failed attempts left nothing behind.

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 and @Cacheable whatever order you give @EnableResilientMethods. With @Async the order is reversed by default: the async proxy hands the call to another thread first, and all retries happen on that thread. The @Transactional page explains the transaction side.

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 method from inside its own bean:

Java
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);
            }
        }
    }
}
Output
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 order-7 and then timed out. From the client's side it failed, so the retry charged the card again, and the customer paid twice.
  • 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: checkout called this.pay(...), 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.

Other mistakes are quieter. Retrying every exception, the default when includes is empty, wastes time on errors that cannot succeed. Retries at several layers multiply: 3 retries in a client, called by a service that also retries 3 times, make 16 calls to a service that is already down. And a long retry inside a web request holds the request thread and the user for the whole schedule, so keep the total delay well under the caller's own timeout.

@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:

Java
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);
        }
    }
}
Output
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 BLOCK policy all 6 calls completed, but never more than 2 at a time. The other callers waited for a free slot.
  • With REJECT, the first 2 ran and the other 4 failed at once with InvocationRejectedException, which a caller can turn into an HTTP 503 or a fallback.

A limit of 1 serialises all calls to the bean instance. limitString reads the limit from a property. The annotation is enabled by the same @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:

Java
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]);
    }
}
Output
@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
  • maxAttempts = 3 made 3 calls in total, including the first. The core annotation's maxRetries = 3 means 3 retries after the first call, so 4 calls. Copying the number across unchanged adds one attempt.
  • When the attempts ran out, Spring Retry called the @Recover method, matched by exception type and parameters, and the caller received its fallback value instead of an exception.
  • The programmatic RetryTemplate.builder() took a recovery callback, which saw 3 failures.

Three differences matter when you migrate:

  • Dependencies: @EnableRetry needs AspectJ on the classpath. Without aspectjweaver, this program fails at startup with NoClassDefFoundError: org/aspectj/lang/annotation/Pointcut. In Spring Boot 4 the old spring-boot-starter-aop is now spring-boot-starter-aspectj. The core annotations need neither.
  • Version management: spring-boot-dependencies 3.5.15 manages spring-retry at 2.0.13, but 4.1.2 no longer lists it, so a Boot 4 build must state the version itself.
  • Fallbacks: the core annotation has no @Recover. Catch the final exception in the caller, or use RetryTemplate.execute and handle the RetryException.
Spring Retry names and their Spring Framework 7 equivalents
Spring Retry 2.0Spring Framework 7
@EnableRetry@EnableResilientMethods
@Retryable(retryFor = X.class)@Retryable(includes = X.class)
noRetryForexcludes
maxAttempts = 3 (calls in total)maxRetries = 2 (retries after the first call)
@Backoff(delay, multiplier, maxDelay, random)delay, multiplier, maxDelay, jitter
@RecoverNo equivalent; handle the exception in the caller
org.springframework.retry.support.RetryTemplateorg.springframework.core.retry.RetryTemplate

Choosing a retry approach

Which tool fits which situation
SituationUse
A bean method that calls a flaky remote service@Retryable(includes = ...) with @EnableResilientMethods
A few lines inside a method, or code that is not a beanRetryTemplate with a RetryPolicy
The caller needs every failure, not just the lastRetryTemplate.execute and RetryException.getExceptions()
Logging or metrics for each failed attemptMethodRetryEvent listener or RetryListener
Many clients retrying the same serviceExponential delay with maxDelay and jitter
A hard limit on total timetimeout on the policy or annotation
Too many concurrent callers, especially virtual threads@ConcurrencyLimit, with REJECT to fail fast
Circuit breaking or rate limiting as wellResilience4j
An existing Spring Retry applicationKeep 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 Spring AOP page explains the proxies behind @Retryable, and the @Async page covers running work on other threads.