Backend Development 20 min read

Understanding Spring Retry: A Comprehensive Guide to Retry, Backoff, and Circuit Breaker Mechanisms

This article explains the concept of retry in distributed systems, introduces Spring Retry and its annotations, demonstrates Maven dependencies, configuration, various retry policies, backoff strategies, circuit breaker support, and walks through the core implementation details with practical code examples.

政采云技术
政采云技术
政采云技术
Understanding Spring Retry: A Comprehensive Guide to Retry, Backoff, and Circuit Breaker Mechanisms

Retry refers to the technique of re‑executing a failed operation—such as a network call—when transient errors occur, in order to improve fault tolerance, availability, and consistency. Spring provides its own retry mechanism called Spring Retry , which is extracted from Spring Batch and can be used in many Spring projects.

Overview

Spring Retry offers annotation‑based and programmatic support. The central flow involves the RetryTemplate and annotations like @EnableRetry , @Retryable , @Recover , and @CircuitBreaker .

Maven Dependencies

<dependency>
    <groupId>org.springframework.retry</groupId>
    <artifactId>spring-retry</artifactId>
</dependency>
<!-- also need Spring AOP -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
</dependency>

Enabling Retry

Add @EnableRetry to a Spring Boot application class to activate the retry infrastructure.

@SpringBootApplication
@EnableRetry
@EnableScheduling
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

Retryable Annotation

Place @Retryable on a method (or class) to specify which exceptions trigger a retry and configure parameters such as maxAttempts , include , exclude , exceptionExpression , and backoff settings.

@Retryable(value = RuntimeException.class)
public void testRetry01() throws MyException {
    System.out.println("测试-value属性");
    throw new RuntimeException("出现了异常");
}

By default, Spring retries three times with a 1‑second delay.

Configuration Attributes

value / include : exception types to retry.

exclude : exception types that should not be retried.

maxAttempts : maximum number of attempts (default 3).

maxAttemptsExpression : SpEL expression to resolve the max attempts from configuration.

exceptionExpression : SpEL that decides whether to retry based on the thrown exception.

Backoff Settings

The @Backoff annotation controls the waiting period between attempts. Parameters include delay , maxDelay , multiplier , random , and their corresponding SpEL expressions.

@Retryable(value = MyException.class, maxAttempts = 4,
    backoff = @Backoff(delay = 2000, multiplier = 2, maxDelay = 5000))
public void testRetry08() throws MyException {
    System.out.println("测试-backoff属性");
    throw new MyException("出现了异常");
}

Recover Method

If all retry attempts fail, a method annotated with @Recover is invoked as a fallback.

@Retryable(value = MyException.class)
public void testRetry06() throws MyException {
    System.out.println("测试兜底方法");
    throw new MyException("出现了异常");
}

@Recover
public void recover06(MyException e) {
    System.out.println("兜底方法开启,异常信息:" + e.getMessage());
}

Circuit Breaker Mode

Combine retry with a circuit breaker using @CircuitBreaker . When the configured failure threshold is reached, the circuit opens for a defined period, preventing further attempts until it half‑opens.

@CircuitBreaker(openTimeout = 1000, resetTimeout = 3000, value = MyException.class)
public void testRetry07() throws MyException {
    System.out.println("测试CircuitBreaker注解");
    throw new MyException("出现了异常");
}

Retry Policies

SimpleRetryPolicy (default, max 3 attempts)

TimeoutRetryPolicy (retries while within a time window)

ExpressionRetryPolicy (uses SpEL to decide)

CircuitBreakerRetryPolicy (adds circuit‑breaker logic)

CompositeRetryPolicy (combines multiple policies)

NeverRetryPolicy (never retries)

AlwaysRetryPolicy (always retries)

Backoff Strategies

FixedBackOffPolicy (constant delay)

ExponentialBackOffPolicy (delay * multiplier)

ExponentialRandomBackOffPolicy (randomized exponential)

UniformRandomBackOffPolicy (random delay between min and max)

Core Implementation Details

The @EnableRetry annotation imports RetryConfiguration , which registers a pointcut for @Retryable and creates the appropriate Advice . The configuration builds a RetryTemplate with the selected RetryPolicy and BackOffPolicy . The template’s doExecute method drives the retry loop, invoking listeners, applying back‑off, handling @Recover , and finally cleaning up the RetryContext .

Key methods include:

getStatelessInterceptor – builds a stateless interceptor with the chosen policies.

getStatefulInterceptor – adds stateful handling and optional circuit‑breaker support.

getRetryPolicy – translates annotation attributes into a concrete RetryPolicy (e.g., SimpleRetryPolicy or ExpressionRetryPolicy ).

getBackoffPolicy – creates the appropriate back‑off implementation based on @Backoff parameters.

SimpleRetryPolicy.canRetry – checks exception type and attempt count.

FixedBackOffPolicy.doBackOff – performs a fixed‑interval sleep.

Overall, Spring Retry provides a flexible, annotation‑driven way to add retry, back‑off, and circuit‑breaker capabilities to Spring applications, with extensible policies and full programmatic control.

JavaSpringRetrycircuitbreakerAnnotationsSpringBootbackoff
政采云技术
Written by

政采云技术

ZCY Technology Team (Zero), based in Hangzhou, is a growth-oriented team passionate about technology and craftsmanship. With around 500 members, we are building comprehensive engineering, project management, and talent development systems. We are committed to innovation and creating a cloud service ecosystem for government and enterprise procurement. We look forward to your joining us.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.