When you call external APIs, you’ll occasionally get a 503 back or hit a connection timeout. Most of the time the failure is temporary, and the call succeeds if you wait a moment and try again. Writing that retry logic by hand with a try-catch inside a loop is tedious, and managing backoff and retry counts tends to clutter your code.

That’s where spring-retry comes in. You add the @Retryable annotation and get retries declaratively. This article walks through implementation examples covering the basics of @Retryable, fallbacks with @Recover, the common self-invocation pitfall, and how to choose between spring-retry and Resilience4j. It assumes synchronous processing on Spring Boot 3.x (spring-retry 2.x) and doesn’t cover reactive retries in WebFlux.

What Is @Retryable?

@Retryable is a spring-retry annotation that automatically re-runs a method when it throws an exception. Spring wraps the Bean in a proxy, and when an exception occurs, it calls the method again a set number of times at a set interval. The caller doesn’t need to know about the retries. It gets back either a successful result or, if every attempt fails, the final exception.

Here’s the minimal setup (adding the dependencies is covered in a later section):

@Configuration
@EnableRetry
public class RetryConfig {
}

@Service
public class StockApiClient {

    @Retryable // 属性なしなら全例外が対象、最大3回試行、1秒間隔
    public Stock fetch(String itemId) {
        return restClient.get()
            .uri("/stocks/{id}", itemId)
            .retrieve()
            .body(Stock.class);
    }
}

With no attributes, it retries on all exceptions and makes up to 3 attempts (including the first call), 1 second apart. In real projects, though, you should normally limit which exceptions trigger a retry. Let’s look at how to do that with retryFor and @Backoff.

When Should You Use Spring Retry?

spring-retry is an AOP-based library: annotate a method, and its execution is retried automatically.

It’s a good fit for failures that might succeed on the next try, such as 503 or 502 responses from external APIs, connection timeouts, and temporary database connection errors. A 400 caused by invalid input won’t change no matter how many times you retry, so it shouldn’t be a retry target. The key to using spring-retry safely is to narrow down which exceptions get retried.

Adding Dependencies and Enabling @EnableRetry

First, add the dependencies. Along with spring-retry itself, you need spring-aspects for AOP. If you forget it, the annotations won’t work. If you let the Spring Boot BOM manage versions, Spring Boot 3.x selects spring-retry 2.x.

dependencies {
    implementation 'org.springframework.retry:spring-retry'
    implementation 'org.springframework:spring-aspects'
}

Next, enable @EnableRetry. You can put it on a configuration class or on your main class annotated with @SpringBootApplication.

@Configuration
@EnableRetry
public class RetryConfig {
}

That’s all the setup. Now you just annotate the methods you want to retry.

@Retryable Basics (maxAttempts and retryFor)

Let’s add @Retryable to a service that calls an external API.

@Service
public class PaymentApiClient {

    @Retryable(
        retryFor = { HttpServerErrorException.class },
        maxAttempts = 3
    )
    public PaymentResult charge(ChargeRequest request) {
        return restClient.post()
            .uri("/charges")
            .body(request)
            .retrieve()
            .body(PaymentResult.class);
    }
}

There are two key points. maxAttempts is the total number of attempts, including the initial call, so 3 means the first call plus 2 retries. The default is 3.

retryFor specifies which exceptions trigger a retry. When RestClient’s retrieve() receives a 5xx, it throws HttpServerErrorException (a subclass of RestClientException), so you can specify it directly as shown above. If you’d rather wrap it in your own exception, such as ApiTemporaryException, to make the retry targets explicit, check the status in onStatus and rethrow the converted exception. To exclude specific exceptions instead, use noRetryFor.

retryFor and noRetryFor were added in spring-retry 2.0 as new aliases for the older include and exclude attributes. The old attributes still work, but retryFor and noRetryFor are recommended for new code. For more on writing the external API calls themselves, see the Spring Boot RestClient guide.

Controlling Delays with @Backoff

If you retry immediately and repeatedly while the remote server is down, you only make things worse for it. Use @Backoff to add a wait between attempts.

@Retryable(
    retryFor = { HttpServerErrorException.class },
    maxAttempts = 4,
    backoff = @Backoff(delay = 500, multiplier = 2.0, maxDelay = 5000, random = true)
)
public PaymentResult charge(ChargeRequest request) {
    // ...
}

If you set only delay, you get a fixed delay. Adding multiplier, as in the example above, gives you exponential backoff, so the wait grows from 500ms to 1000ms to 2000ms. Without a cap it would keep growing, so in practice you should set an upper limit with maxDelay.

random = true adds jitter. When many clients fail at the same moment, their retries can all fire at once and hit the server again together (the thundering herd problem). Jitter randomizes the wait times to avoid this. It’s a good idea to enable it whenever you call external APIs.

Writing a Final Fallback with @Recover

What happens when every attempt fails? You can let the exception propagate, but sometimes you’d rather return a default value or fall back to a cache. That’s what @Recover is for.

@Service
public class PaymentApiClient {

    @Retryable(retryFor = { HttpServerErrorException.class }, maxAttempts = 3)
    public PaymentResult charge(ChargeRequest request) {
        // ...
    }

    @Recover
    public PaymentResult recoverCharge(HttpServerErrorException e, ChargeRequest request) {
        log.warn("リトライ上限に達したためフォールバックします", e);
        return PaymentResult.pending(request.orderId());
    }
}

A @Recover method has to match a specific signature. If it doesn’t, the @Recover method is never called and the original exception propagates to the caller, so be careful:

  • The return type must match the @Retryable method
  • The first parameter must be the exception type being retried
  • After the first parameter, you can list the original method’s parameters in the same order

When the fallback isn’t called, the cause is usually a mismatched return type, or a first-parameter exception type that doesn’t match the exception actually thrown. Check those two things first.

The Self-Invocation Pitfall: When Retries Don’t Work

The most common spring-retry pitfall is self-invocation. @Retryable works through an AOP proxy, so when you call the method directly from another method in the same class, the call bypasses the proxy and no retry happens.

@Service
public class OrderService {

    public void process(Order order) {
        // これはプロキシを経由しないのでリトライされない
        callExternalApi(order);
    }

    @Retryable(retryFor = HttpServerErrorException.class)
    public void callExternalApi(Order order) {
        // ...
    }
}

Here process calls callExternalApi, but because it’s an internal call, @Retryable has no effect at all. The annotation is present, but it does nothing.

The fix is simple: move the method you want to retry into a separate Bean.

@Service
public class ExternalApiClient {

    @Retryable(retryFor = HttpServerErrorException.class)
    public void call(Order order) {
        // ...
    }
}

@Service
public class OrderService {

    private final ExternalApiClient apiClient;

    public OrderService(ExternalApiClient apiClient) {
        this.apiClient = apiClient;
    }

    public void process(Order order) {
        apiClient.call(order); // 別Bean経由なのでプロキシが効く
    }
}

Now the call goes through the proxy and the retry works as expected. Also note that methods annotated with @Retryable must be public, because proxies aren’t applied to private methods. Moving the method into a separate Bean is a general AOP rule, and the same caution applies when you combine retries with optimistic locking, as covered in the JPA optimistic locking guide.

Writing Retries Programmatically with RetryTemplate

Annotations are declarative and convenient, but sometimes you need finer control, such as deciding at runtime whether to retry based on the response content. In those cases, RetryTemplate lets you build the retry logic in code.

import org.springframework.retry.RetryContext;
import org.springframework.retry.support.RetryTemplate;

RetryTemplate retryTemplate = RetryTemplate.builder()
    .maxAttempts(3)
    .exponentialBackoff(500, 2.0, 5000)
    .retryOn(HttpServerErrorException.class)
    .build();

PaymentResult result = retryTemplate.execute((RetryContext context) -> {
    // context.getRetryCount() で現在の試行回数を参照できる
    return apiClient.charge(request);
});

The lambda passed to execute is a RetryCallback, and its context parameter is a RetryContext. The context exposes state such as the attempt count, which you can use for runtime decisions.

Defining It as a Bean and Using It for RestClient Retries

In practice, it’s convenient to define a RetryTemplate as a Bean and reuse it. If you register a RetryListener with withListener, you can log every failure.

@Bean
public RetryTemplate apiRetryTemplate() {
    return RetryTemplate.builder()
        .maxAttempts(3)
        .exponentialBackoff(500, 2.0, 5000)
        .retryOn(HttpServerErrorException.class)
        .withListener(new RetryListener() {
            @Override
            public <T, E extends Throwable> void onError(
                    RetryContext context, RetryCallback<T, E> callback, Throwable e) {
                log.warn("{}回目の呼び出しに失敗しました", context.getRetryCount(), e);
            }
        })
        .build();
}

Wrap a RestClient call like this. The second argument, a RecoveryCallback, is the fallback that corresponds to @Recover.

Stock stock = apiRetryTemplate.execute(
    ctx -> restClient.get().uri("/stocks/{id}", itemId)
        .retrieve().body(Stock.class),
    ctx -> Stock.unknown(itemId));

That said, annotations are enough for most cases. Unless you have a specific reason not to, start with @Retryable.

Retries in Spring Boot 4

Spring Framework 7, which Spring Boot 4 uses, has retry support built into the core. You don’t need to add spring-retry: add @EnableResilientMethods and you can use org.springframework.resilience.annotation.Retryable.

@Configuration
@EnableResilientMethods
public class ResilienceConfig {
}

@Retryable(includes = HttpServerErrorException.class,
    maxRetries = 3, delay = 500, multiplier = 2.0, maxDelay = 5000)
public PaymentResult charge(ChargeRequest request) {
    // ...
}

Watch how attempts are counted. maxRetries doesn’t include the initial call, so the example above makes up to 4 calls. There’s also no equivalent of @Recover, so you write the fallback by catching the exception on the caller side. For new Boot 4 projects, use the core feature. For existing spring-retry code, work out how you’ll replace @Recover before you migrate.

Choosing Between Spring Retry and Resilience4j

Many developers think of Resilience4j when it comes to retries. Here’s a quick comparison to help you choose.

AspectSpring RetryResilience4j
Main responsibilityRetryRetry + Circuit Breaker + Bulkhead + RateLimiter
Ease of adoptionAnnotations alone are enoughMore configuration options
Best suited forSimple automatic retriesStopping cascading failures, or when you need many features

The decision is simple. If all you need is a basic retry, spring-retry is enough. If you need a Circuit Breaker that stops calls after repeated failures, or a Bulkhead that limits concurrent executions, choose Resilience4j. For details, see the guide to implementing a circuit breaker with Resilience4j.

Messaging platforms such as Kafka have their own retry mechanisms (such as DLT). Those are covered in the Kafka Producer/Consumer guide.

Summary

With spring-retry, you add the dependencies, enable @EnableRetry, and annotate methods with @Retryable to get declarative retries. Narrow the targets with maxAttempts and retryFor, apply exponential backoff with @Backoff, and provide a final fallback with @Recover. With that pattern, you can cleanly handle temporary failures in external API calls.

Watch out for self-invocation: retries don’t work for calls within the same class, so move the method into a separate Bean. Choose by responsibility: use Resilience4j when you need more advanced fault tolerance such as a Circuit Breaker, and spring-retry when a simple retry is enough. spring-retry is the easier one to start with, so try it first.