Resilience in Spring: retries, limits and circuit breakers
A remote call can fail, hang or slow down, and each of those needs a different defence. Spring Framework 7 now ships retries and concurrency limits in its core, and Resilience4j adds circuit breakers, rate limiters and time limits on top. This page explains each pattern, runs the built-in Spring features and the Resilience4j circuit breaker, rate limiter, bulkhead and time limiter, and shows their Spring Boot 4 setup.
Contents
What resilience patterns protect against Retrying a method with @Retryable Which failures to retry Programmatic retries with RetryTemplate Retries and transactions Limiting concurrent calls with @ConcurrencyLimit Circuit breakers with Resilience4j Rate limiters, bulkheads, time limiters and order Traps that make resilience code harmful Choosing a resilience tool
What resilience patterns protect against
A call to another service can go wrong in three ways. It can fail quickly, with a connection refused or an HTTP 503. It can hang, holding a thread while it waits for a response that may never come. Or it can slow down for everyone, because the service on the other end is overloaded. A plain method call handles none of these: the caller either gets an exception or waits.
Resilience patterns are small wrappers around such a call. Each one answers one of those problems:
- Retry: calls again after a short failure, such as a dropped connection or a lock timeout, usually with a growing delay between attempts.
- Circuit breaker: counts recent failures and, past a threshold, stops calling the service for a while, so that a dead dependency fails fast instead of piling up waiting threads.
- Bulkhead: limits how many calls to one dependency may run at the same time, so that a slow service cannot take every thread in the application.
- Rate limiter: limits how many calls may start in a period, for example to stay under a partner API's quota.
- Time limiter: gives up on a call that takes too long.
In Spring, all of them are applied the same way as @Transactionalthis
Until recently, retries in Spring meant the separate Spring Retry project. Spring Framework 7.0 moved retries and concurrency limits into the core framework, so a Spring Boot 4 application has them with no extra dependency. Circuit breakers, rate limiters and time limiters still come from a library, and Resilience4j is the usual choice:
| Pattern | Spring Framework 7 (built in) | Resilience4j 2.4 |
|---|---|---|
| Retry with backoff | @RetryableRetryTemplate | @Retry |
| Bulkhead (concurrent calls) | @ConcurrencyLimit | @Bulkhead |
| Circuit breaker | None | @CircuitBreaker |
| Rate limiter (calls per period) | None | @RateLimiter |
| Time limiter | None for synchronous calls | @TimeLimiter |
| Fallback method | None; catch the exception | fallbackMethod |
| Metrics and health | MethodRetryEventRetryListener | Micrometer metrics, Actuator endpoints |
The first five programs on this page use only Spring Framework 7.0 and run as shown. Resilience4j is not available in the environment where this page was built, so its sections show configuration checked against the Resilience4j reference documentation, and say so.
Retrying a method with @Retryable
A price lookup that times out three times and then answers is the typical case for a retry: the failure is short, and the fourth call works. The program asks for up to four retries, starting 100 ms apart and doubling each time:
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.annotation.EnableResilientMethods;
import org.springframework.resilience.annotation.Retryable;
public class RetryBasics {
@Configuration
@EnableResilientMethods
static class Config {
@Bean
PriceClient priceClient() {
return new PriceClient();
}
}
static class PriceClient {
private final AtomicInteger calls = new AtomicInteger();
private long last;
// fails on the first three calls, then succeeds
@Retryable(maxRetries = 4, delay = 100, multiplier = 2)
public String price(String sku) {
int n = calls.incrementAndGet();
long now = System.nanoTime();
// the gap since the previous attempt, rounded to 50 ms to hide scheduling noise
String gap = n == 1 ? "first call"
: "~" + Math.round((now - last) / 1e6 / 50) * 50 + " ms after the previous one";
last = now;
System.out.println(" attempt " + n + ": " + gap);
if (n <= 3) {
throw new IllegalStateException("price service timed out");
}
return sku + " costs 9.99";
}
}
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(Config.class)) {
PriceClient client = context.getBean(PriceClient.class);
System.out.println("Bean class: " + client.getClass().getSimpleName());
System.out.println("Result: " + client.price("book-42"));
}
}
}
Bean class: RetryBasics$PriceClient$$SpringCGLIB$$0
attempt 1: first call
attempt 2: ~100 ms after the previous one
attempt 3: ~200 ms after the previous one
attempt 4: ~400 ms after the previous one
Result: book-42 costs 9.99
turned on the processing of the annotation, and the bean became a CGLIB proxy,@EnableResilientMethods . The proxy catches the exception and calls the real method again.PriceClient$$SpringCGLIB$$0- The gaps were about 100, 200 and 400 ms:
is the first wait, anddelay = 100 doubles it after each failure. The fourth attempt succeeded, so the caller received the result and never saw the three exceptions.multiplier = 2 counts retries, not attempts. WithmaxRetries , the method may run up to five times in total: one first call and four retries.maxRetries = 4
Without attributes, @RetryablemaxDelayjitterStringdelayString = "${pricing.retry-delay}"
The annotation also works on methods that return a Reactor MonoFlux
Which failures to retry
A retry helps only when the next attempt might succeed. A busy gateway may answer on the second try, but an expired card will be expired on every try. This payment client throws both kinds, plus a transient failure wrapped in another exception, and an event listener records what the proxy saw:
import java.util.ArrayList;
import java.util.List;
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.resilience.annotation.EnableResilientMethods;
import org.springframework.resilience.annotation.Retryable;
import org.springframework.resilience.retry.MethodRetryEvent;
public class RetryRules {
static class TransientException extends RuntimeException {
TransientException(String message) {
super(message);
}
}
static class InvalidCardException extends RuntimeException {
InvalidCardException(String message) {
super(message);
}
}
@Configuration
@EnableResilientMethods
static class Config {
@Bean
PaymentClient paymentClient() {
return new PaymentClient();
}
@Bean
RetryLog retryLog() {
return new RetryLog();
}
}
static class PaymentClient {
private int attempts;
// fields of a proxied bean must be read through methods: the proxy has its own copy
public int attempts() {
return attempts;
}
public void reset() {
attempts = 0;
}
@Retryable(includes = TransientException.class, maxRetries = 2, delay = 10)
public void charge(String card) {
attempts++;
switch (card) {
case "busy" -> throw new TransientException("gateway busy, attempt " + attempts);
case "expired" -> throw new InvalidCardException("card expired");
default -> throw new IllegalStateException("wrapped",
new TransientException("socket reset, attempt " + attempts));
}
}
}
static class RetryLog {
final List<String> events = new ArrayList<>();
@EventListener
void onRetry(MethodRetryEvent event) {
events.add(event.getFailure().getClass().getSimpleName()
+ (event.isRetryAborted() ? " (retry aborted)" : ""));
}
}
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(Config.class)) {
PaymentClient client = context.getBean(PaymentClient.class);
RetryLog log = context.getBean(RetryLog.class);
for (String card : List.of("busy", "expired", "wrapped")) {
client.reset();
log.events.clear();
try {
client.charge(card);
} catch (RuntimeException e) {
System.out.println(card + ": " + client.attempts() + " attempt(s), caller got "
+ e.getClass().getSimpleName() + ": " + e.getMessage());
System.out.println(" events: " + log.events);
}
}
}
}
}
busy: 3 attempt(s), caller got TransientException: gateway busy, attempt 3
events: [TransientException, TransientException, TransientException, RetryException (retry aborted)]
expired: 1 attempt(s), caller got InvalidCardException: card expired
events: [InvalidCardException, RetryException (retry aborted)]
wrapped: 3 attempt(s), caller got IllegalStateException: wrapped
events: [IllegalStateException, IllegalStateException, IllegalStateException, RetryException (retry aborted)]
:busy is inTransientException , so the method ran 3 times, the first call plusincludes . The caller then got the last original exception, the one that says "attempt 3", not a wrapper.maxRetries = 2 :expired is not included, so the proxy gave up after 1 attempt and rethrew it at once.InvalidCardException : the thrownwrapped is not inIllegalStateException , but its cause is aincludes . Spring matches the causes too, so this call was retried 3 times as well.TransientException- The events show every failure, which the caller cannot see, since it only gets the last one. Each run ends with an extra event that carries a
and hasRetryException set, marking the point where the proxy stopped retrying.isRetryAborted()
Three attributes choose the exceptions. The includesvalue@Retryable(TransientException.class)excludespredicateMethodRetryPredicateincludesexcludes
The program also shows why the counter is read through attempts()client.attempts
Programmatic retries with RetryTemplate
RetryTemplate
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 RetryTemplateDemo {
static int calls;
static String fetchRates() {
calls++;
throw new IllegalStateException("rates service unavailable (call " + calls + ")");
}
static RetryListener printer() {
return new RetryListener() {
@Override
public void onRetryFailure(RetryPolicy policy, Retryable<?> retryable, Throwable t) {
System.out.println(" retry failed: " + t.getMessage());
}
@Override
public void onRetryPolicyExhaustion(RetryPolicy policy, Retryable<?> retryable,
RetryException e) {
System.out.println(" exhausted after " + e.getRetryCount() + " retries");
}
@Override
public void onRetryPolicyTimeout(RetryPolicy policy, Retryable<?> retryable,
RetryException e) {
System.out.println(" timed out after " + e.getRetryCount() + " retries");
}
};
}
static void run(String label, RetryPolicy policy) {
System.out.println(label);
calls = 0;
RetryTemplate template = new RetryTemplate(policy);
template.setRetryListener(printer());
try {
template.execute(new Retryable<String>() {
@Override
public String execute() {
return fetchRates();
}
@Override
public String getName() {
return "fetchRates";
}
});
} catch (RetryException e) {
RetryState state = e;
System.out.println(" RetryException: " + e.getMessage());
System.out.println(" calls made: " + calls + ", exceptions kept: "
+ state.getExceptions().size());
System.out.println(" last: " + e.getLastException().getMessage());
}
}
public static void main(String[] args) {
run("Three retries, 20 ms apart:", RetryPolicy.builder()
.maxRetries(3)
.delay(Duration.ofMillis(20))
.build());
run("Ten retries, doubling from 50 ms, but at most 300 ms in total:", RetryPolicy.builder()
.maxRetries(10)
.delay(Duration.ofMillis(50))
.multiplier(2)
.timeout(Duration.ofMillis(300))
.build());
System.out.println("invoke() rethrows the original exception instead:");
calls = 0;
try {
new RetryTemplate(RetryPolicy.builder().maxRetries(1).delay(Duration.ZERO).build())
.invoke(RetryTemplateDemo::fetchRates);
} catch (IllegalStateException e) {
System.out.println(" " + e.getClass().getSimpleName() + ": " + e.getMessage());
}
}
}
Three retries, 20 ms apart:
retry failed: rates service unavailable (call 2)
retry failed: rates service unavailable (call 3)
retry failed: rates service unavailable (call 4)
exhausted after 3 retries
RetryException: Retry policy for operation 'fetchRates' exhausted; aborting execution
calls made: 4, exceptions kept: 4
last: rates service unavailable (call 4)
Ten retries, doubling from 50 ms, but at most 300 ms in total:
retry failed: rates service unavailable (call 2)
retry failed: rates service unavailable (call 3)
timed out after 2 retries
RetryException: Retry policy for operation 'fetchRates' would exceed timeout (300ms) due to pending sleep time (200ms); preemptively aborting execution
calls made: 3, exceptions kept: 3
last: rates service unavailable (call 3)
invoke() rethrows the original exception instead:
IllegalStateException: rates service unavailable (call 2)
- The first policy allowed 3 retries, so
ran 4 times. The listener'sfetchRates fired only for calls 2 to 4, the retries, not for the first call.onRetryFailure threw the checkedexecute , which keeps all 4 exceptions inRetryException and the last one ingetExceptions() . Its message names the operation fromgetLastException() ; a plain lambda would be named by its generated class instead.Retryable.getName()- The second policy allowed 10 retries but only 300 ms in total. After waits of 50 and 100 ms the next wait would have been 200 ms, which would pass the limit, so the template stopped early, after 2 retries, and called
.onRetryPolicyTimeout takes ainvoke orSupplier and rethrows the last original exception, likeRunnable does. Use it when the caller only cares about the final failure.@Retryable
RetryPolicy.withDefaults()new RetryTemplate()timeout
Retries and transactions
When a method has both @Retryable@Transactional
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.dao.TransientDataAccessResourceException;
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 {
@Configuration
@EnableTransactionManagement
@EnableResilientMethods
static class Config {
@Bean
DataSource dataSource() {
return new DriverManagerDataSource("jdbc:h2:mem:retry;DB_CLOSE_DELAY=-1");
}
@Bean
JdbcTemplate jdbc(DataSource dataSource) {
JdbcTemplate jdbc = new JdbcTemplate(dataSource);
jdbc.execute("CREATE TABLE transfers (id INT PRIMARY KEY, amount INT)");
return jdbc;
}
@Bean
PlatformTransactionManager transactionManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean
TransferService transferService(JdbcTemplate jdbc) {
return new TransferService(jdbc);
}
}
static class TransferService {
private final JdbcTemplate jdbc;
private int attempt;
TransferService(JdbcTemplate jdbc) {
this.jdbc = jdbc;
}
@Transactional
@Retryable(includes = TransientDataAccessResourceException.class, maxRetries = 2,
delay = 10)
public void transfer(int id, int amount) {
attempt++;
System.out.println("attempt " + attempt + ": transaction active = "
+ TransactionSynchronizationManager.isActualTransactionActive());
int n = attempt;
TransactionSynchronizationManager.registerSynchronization(
new TransactionSynchronization() {
@Override
public void afterCompletion(int status) {
System.out.println(" transaction of attempt " + n + ": "
+ (status == STATUS_COMMITTED ? "committed" : "rolled back"));
}
});
jdbc.update("INSERT INTO transfers VALUES (?, ?)", id, amount);
if (attempt == 1) {
throw new TransientDataAccessResourceException("lock wait timeout");
}
}
}
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(Config.class)) {
context.getBean(TransferService.class).transfer(7, 250);
JdbcTemplate jdbc = context.getBean(JdbcTemplate.class);
System.out.println("rows in transfers: "
+ jdbc.queryForObject("SELECT COUNT(*) FROM transfers", Integer.class));
}
}
}
attempt 1: transaction active = true
transaction of attempt 1: rolled back
attempt 2: transaction active = true
transaction of attempt 2: committed
rows in transfers: 1
- Attempt 1 inserted the row, then threw
. Its transaction rolled back, removing the row.TransientDataAccessResourceException - Attempt 2 ran in a new transaction, inserted the same row again and committed. The table holds 1 row, not 2, and the primary key never clashed.
Spring always applies the retry outside the transaction, whatever order you declare: each attempt starts a fresh transaction, as the output shows. That is what you want, because retrying inside a transaction that has already failed cannot succeed. The same fixed order applies to @Cacheable@Async
A retry repeats the call, so the call must be safe to repeat. A database write inside a transaction is, because the failed attempt was rolled back. A remote POST
Limiting concurrent calls with @ConcurrencyLimit
A bulkhead caps how many threads may be inside a method at once. A report renderer that takes 100 ms per call, called by six threads together, shows both of its modes:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
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.ConcurrencyLimit.ThrottlePolicy;
import org.springframework.resilience.annotation.EnableResilientMethods;
public class ConcurrencyLimitDemo {
@Configuration
@EnableResilientMethods
static class Config {
@Bean
ReportClient reportClient() {
return new ReportClient();
}
}
static class ReportClient {
private final AtomicInteger inside = new AtomicInteger();
private final AtomicInteger maxInside = new AtomicInteger();
@ConcurrencyLimit(2)
public void render(int id) throws InterruptedException {
maxInside.accumulateAndGet(inside.incrementAndGet(), Math::max);
Thread.sleep(100);
inside.decrementAndGet();
}
@ConcurrencyLimit(limit = 1, policy = ThrottlePolicy.REJECT)
public String export(CountDownLatch entered, CountDownLatch release)
throws InterruptedException {
entered.countDown();
release.await();
return "exported";
}
public int maxInside() {
return maxInside.get();
}
}
public static void main(String[] args) throws Exception {
try (var context = new AnnotationConfigApplicationContext(Config.class);
ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor()) {
ReportClient client = context.getBean(ReportClient.class);
long start = System.nanoTime();
List<Future<?>> calls = new ArrayList<>();
for (int i = 1; i <= 6; i++) {
int id = i;
calls.add(pool.submit(() -> {
client.render(id);
return null;
}));
}
for (Future<?> f : calls) {
f.get();
}
long ms = (System.nanoTime() - start) / 1000000;
System.out.println("BLOCK policy, limit 2, six 100 ms calls:");
System.out.println(" most calls inside at once: " + client.maxInside());
System.out.println(" total time about " + Math.round(ms / 100.0) * 100 + " ms");
System.out.println("REJECT policy, limit 1, two calls at once:");
CountDownLatch entered = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
Future<String> first = pool.submit(() -> client.export(entered, release));
entered.await();
try {
client.export(new CountDownLatch(1), new CountDownLatch(0));
} catch (InvocationRejectedException e) {
System.out.println(" second call: " + e.getClass().getSimpleName()
+ ": " + e.getMessage());
}
release.countDown();
System.out.println(" first call: " + first.get());
}
}
}
BLOCK policy, limit 2, six 100 ms calls:
most calls inside at once: 2
total time about 300 ms
REJECT policy, limit 1, two calls at once:
second call: InvocationRejectedException: Concurrency limit reached: 1 - not allowed to enter ConcurrencyLimitDemo$ReportClient.export
first call: exported
- With the default
policy and a limit of 2, no more than 2 calls were insideBLOCK at once. The other four waited, so the six calls took about 300 ms, three rounds of two, instead of 100 ms.render - With
and a limit of 1, the second call did not wait. It failed at once withpolicy = ThrottlePolicy.REJECT , a subclass ofInvocationRejectedException , while the first call finished normally.RejectedExecutionException
Blocking suits work that must happen anyway, where the limit protects a resource such as a small connection pool on the other side. Rejecting suits a request path, where a fast error is better than a growing queue of waiting requests. The limit matters most with virtual threads: a pool of 200 platform threads limits concurrency by accident, but virtual threads have no such limit, and nothing stops ten thousand of them calling one slow service. limitString
Circuit breakers with Resilience4j
A retry makes a dead service worse: every caller now sends three or four requests instead of one. A circuit breaker watches the outcome of recent calls and, when too many fail, stops sending them for a while. It has three main states:
- CLOSED: calls go through, and each outcome is recorded in a sliding window of the last N calls (
) or the last N seconds (COUNT_BASED ).TIME_BASED - OPEN: once the failure rate passes the threshold, calls are rejected at once with
, without touching the service, forCallNotPermittedException .waitDurationInOpenState - HALF_OPEN: after the wait, a few trial calls are let through. If they succeed the breaker closes again, and if they fail it opens again.
The breaker itself is plain Java, in the resilience4j-circuitbreakerresilience4j-allDecorators
import io.github.resilience4j.circuitbreaker.CallNotPermittedException;
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig;
import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry;
import io.github.resilience4j.decorators.Decorators;
import java.time.Duration;
import java.util.function.Supplier;
public class CircuitBreakerDemo {
static class UnknownSkuException extends RuntimeException {
UnknownSkuException(String sku) {
super("unknown sku " + sku);
}
}
/** A fake inventory service: "down" until told otherwise. */
static boolean serviceUp = false;
static String fetch(String sku) {
if (sku.startsWith("X")) {
throw new UnknownSkuException(sku);
}
if (!serviceUp) {
throw new IllegalStateException("503 from inventory");
}
return sku + ": 7 in stock";
}
static void call(CircuitBreaker breaker, String sku) {
Supplier<String> decorated = Decorators.ofSupplier(() -> fetch(sku))
.withCircuitBreaker(breaker)
.withFallback(t -> "fallback (" + t.getClass().getSimpleName() + ")")
.decorate();
String result = decorated.get();
CircuitBreaker.Metrics m = breaker.getMetrics();
System.out.printf(" %-5s -> %-48s %-9s calls=%d failed=%d rate=%.0f%%%n", sku, result,
breaker.getState(), m.getNumberOfBufferedCalls(), m.getNumberOfFailedCalls(),
m.getFailureRate());
}
public static void main(String[] args) throws InterruptedException {
CircuitBreakerConfig config = CircuitBreakerConfig.custom()
.slidingWindowType(CircuitBreakerConfig.SlidingWindowType.COUNT_BASED)
.slidingWindowSize(10)
.minimumNumberOfCalls(5)
.failureRateThreshold(50)
.waitDurationInOpenState(Duration.ofMillis(200))
.permittedNumberOfCallsInHalfOpenState(2)
.ignoreExceptions(UnknownSkuException.class)
.build();
CircuitBreaker breaker = CircuitBreakerRegistry.of(config).circuitBreaker("inventory");
breaker.getEventPublisher().onStateTransition(e ->
System.out.println(" event: " + e.getStateTransition()));
CircuitBreakerConfig defaults = CircuitBreakerConfig.ofDefaults();
System.out.println("Defaults: window " + defaults.getSlidingWindowSize()
+ ", minimum calls " + defaults.getMinimumNumberOfCalls()
+ ", threshold " + defaults.getFailureRateThreshold()
+ "%, open for " + defaults.getWaitIntervalFunctionInOpenState().apply(1) + " ms");
System.out.println("Service down:");
call(breaker, "A-1");
call(breaker, "X-9"); // business error: ignored
for (String sku : new String[] {"A-2", "A-3", "A-4", "A-5", "A-6"}) {
call(breaker, sku);
}
try {
breaker.executeSupplier(() -> fetch("A-7"));
} catch (CallNotPermittedException e) {
System.out.println(" without a fallback: " + e.getMessage());
}
System.out.println("Service back up, after the wait in OPEN:");
serviceUp = true;
Thread.sleep(300);
call(breaker, "A-8");
call(breaker, "A-9");
call(breaker, "B-1");
}
}
Defaults: window 100, minimum calls 100, threshold 50.0%, open for 60000 ms
Service down:
A-1 -> fallback (IllegalStateException) CLOSED calls=1 failed=1 rate=-1%
X-9 -> fallback (UnknownSkuException) CLOSED calls=1 failed=1 rate=-1%
A-2 -> fallback (IllegalStateException) CLOSED calls=2 failed=2 rate=-1%
A-3 -> fallback (IllegalStateException) CLOSED calls=3 failed=3 rate=-1%
A-4 -> fallback (IllegalStateException) CLOSED calls=4 failed=4 rate=-1%
event: State transition from CLOSED to OPEN
A-5 -> fallback (IllegalStateException) OPEN calls=5 failed=5 rate=100%
A-6 -> fallback (CallNotPermittedException) OPEN calls=5 failed=5 rate=100%
without a fallback: CircuitBreaker 'inventory' is OPEN and does not permit further calls
Service back up, after the wait in OPEN:
event: State transition from OPEN to HALF_OPEN
A-8 -> A-8: 7 in stock HALF_OPEN calls=1 failed=0 rate=-1%
event: State transition from HALF_OPEN to CLOSED
A-9 -> A-9: 7 in stock CLOSED calls=0 failed=0 rate=-1%
B-1 -> B-1: 7 in stock CLOSED calls=1 failed=0 rate=-1%
- The first line shows the defaults: a window of 100 calls, at least 100 calls before the rate counts, a 50% threshold and 60000 ms in
. On a service with little traffic, such a breaker would almost never open, which is why the program sets smaller values.OPEN - The failure rate printed as
until 5 calls were recorded: below-1% , the breaker does not compute a rate at all.minimumNumberOfCalls threwX-9 , which is inUnknownSkuException , so the buffered calls stayed at 1. The fallback still ran for it:ignoreExceptions catches every exception, ignored or not.withFallback- The fifth recorded call,
, made the rate 100%, and the event listener printed the transition fromA-5 toCLOSED . The next call,OPEN , never reached the service: the fallback received aA-6 . Without a fallback, the caller gets that exception with the message shown.CallNotPermittedException - After 300 ms, longer than the 200 ms wait, the next call moved the breaker to
and was let through. Two successful trial calls, theHALF_OPEN , closed it, and closing reset the window, so the metrics started again from 0.permittedNumberOfCallsInHalfOpenState
The transition to HALF_OPENautomaticTransitionFromOpenToHalfOpenEnabled(true)
In Spring Boot, the same breaker is configured with properties and applied with an annotation. Resilience4j 2.4.0 added the resilience4j-spring-boot4resilience4j-spring-boot3spring-boot-starter-aopspring-boot-starter-aspectj
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-spring-boot4</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aspectj</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Each breaker is an instance with a name, configured under resilience4j.circuitbreaker.instances
resilience4j:
circuitbreaker:
instances:
inventory:
sliding-window-type: COUNT_BASED
sliding-window-size: 20
minimum-number-of-calls: 10
failure-rate-threshold: 50
slow-call-duration-threshold: 2s
slow-call-rate-threshold: 80
wait-duration-in-open-state: 30s
permitted-number-of-calls-in-half-open-state: 3
ignore-exceptions:
- com.example.inventory.UnknownSkuException
@Service
public class StockService {
private final InventoryClient inventory;
public StockService(InventoryClient inventory) {
this.inventory = inventory;
}
@CircuitBreaker(name = "inventory", fallbackMethod = "unknownStock")
public StockLevel stockFor(String sku) {
return inventory.fetch(sku);
}
// same parameters plus one exception parameter, same return type, same class
private StockLevel unknownStock(String sku, Throwable cause) {
return StockLevel.unknown(sku);
}
}
- The properties map one to one to the builder methods in the program:
tosliding-window-size ,slidingWindowSize toignore-exceptions , and so on.ignoreExceptions - Slow calls count too. With the settings above, if 80% of recent calls take longer than 2 seconds, the breaker opens even though nothing failed.
- By default every exception counts as a failure.
excludes business errors, such as an unknown product code, that say nothing about the health of the service.ignore-exceptions - The fallback must be in the same class, with the same parameters plus one exception parameter. It runs for any failure, including
when the breaker is open. With several fallbacks, the one whose exception type matches most closely is chosen.CallNotPermittedException
Besides the three main states, a breaker can be put in DISABLEDFORCED_OPENMETRICS_ONLY
Rate limiters, bulkheads, time limiters and order
The other Resilience4j patterns follow the same model of a named instance with a configuration. This program runs a rate limiter that allows 3 calls per 500 ms, and a bulkhead that allows 2 concurrent calls, with four callers arriving while two slow calls hold their permits:
import io.github.resilience4j.bulkhead.Bulkhead;
import io.github.resilience4j.bulkhead.BulkheadConfig;
import io.github.resilience4j.bulkhead.BulkheadFullException;
import io.github.resilience4j.ratelimiter.RateLimiter;
import io.github.resilience4j.ratelimiter.RateLimiterConfig;
import io.github.resilience4j.ratelimiter.RequestNotPermitted;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class LimitersDemo {
public static void main(String[] args) throws Exception {
RateLimiter limiter = RateLimiter.of("partner-api", RateLimiterConfig.custom()
.limitForPeriod(3)
.limitRefreshPeriod(Duration.ofMillis(500))
.timeoutDuration(Duration.ZERO) // do not wait for a permit
.build());
System.out.println("Rate limiter, 3 calls per 500 ms:");
for (int round = 1; round <= 2; round++) {
StringBuilder line = new StringBuilder(" round " + round + ":");
for (int i = 1; i <= 5; i++) {
try {
line.append(" " + limiter.executeSupplier(() -> "ok"));
} catch (RequestNotPermitted e) {
line.append(" rejected");
}
}
System.out.println(line);
Thread.sleep(600);
}
try {
limiter.executeSupplier(() -> "ok");
limiter.executeSupplier(() -> "ok");
limiter.executeSupplier(() -> "ok");
limiter.executeSupplier(() -> "ok");
} catch (RequestNotPermitted e) {
System.out.println(" message: " + e.getMessage());
}
Bulkhead bulkhead = Bulkhead.of("inventory", BulkheadConfig.custom()
.maxConcurrentCalls(2)
.maxWaitDuration(Duration.ZERO)
.build());
System.out.println("Bulkhead, 2 concurrent calls, 4 callers at once:");
CountDownLatch inside = new CountDownLatch(2);
CountDownLatch release = new CountDownLatch(1);
ExecutorService pool = Executors.newFixedThreadPool(4);
List<Future<String>> results = new ArrayList<>();
for (int i = 1; i <= 4; i++) {
int caller = i;
results.add(pool.submit(() -> {
if (caller > 2) {
inside.await(); // start only once two calls are running
}
try {
return bulkhead.executeCallable(() -> {
inside.countDown();
release.await(); // a slow call: hold the permit
return "caller " + caller + " done";
});
} catch (BulkheadFullException e) {
return "caller " + caller + " rejected: " + e.getMessage();
}
}));
}
inside.await();
System.out.println(" available permits while two calls run: "
+ bulkhead.getMetrics().getAvailableConcurrentCalls());
for (int i = 2; i < 4; i++) {
System.out.println(" " + results.get(i).get());
}
release.countDown();
for (int i = 0; i < 2; i++) {
System.out.println(" " + results.get(i).get());
}
pool.shutdown();
}
}
Rate limiter, 3 calls per 500 ms:
round 1: ok ok ok rejected rejected
round 2: ok ok ok rejected rejected
message: RateLimiter 'partner-api' does not permit further calls
Bulkhead, 2 concurrent calls, 4 callers at once:
available permits while two calls run: 0
caller 3 rejected: Bulkhead 'inventory' is full and does not permit further calls
caller 4 rejected: Bulkhead 'inventory' is full and does not permit further calls
caller 1 done
caller 2 done
- In each round, the first 3 calls got a permit and the next 2 were rejected at once with
, becauseRequestNotPermitted is zero. After 600 ms a new period had started, and the second round got 3 permits again.timeoutDuration - The rate limiter counts calls that start in a period; it does not care how long they run. The bulkhead counts calls that are running: with both permits held,
was 0, and callers 3 and 4 gotgetAvailableConcurrentCalls() without waiting, becauseBulkheadFullException is zero.maxWaitDuration - Callers 1 and 2 finished normally once released. A bulkhead with a non-zero wait would have queued callers 3 and 4 instead, as
with the@ConcurrencyLimit policy did earlier.BLOCK
A time limiter needs something it can stop waiting for, a FutureCompletableFuture
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig;
import io.github.resilience4j.decorators.Decorators;
import io.github.resilience4j.retry.Retry;
import io.github.resilience4j.retry.RetryConfig;
import io.github.resilience4j.timelimiter.TimeLimiter;
import io.github.resilience4j.timelimiter.TimeLimiterConfig;
import java.time.Duration;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
public class TimeLimiterAndOrder {
public static void main(String[] args) throws Exception {
System.out.println("Time limiter, 100 ms:");
ExecutorService pool = Executors.newSingleThreadExecutor();
for (boolean cancel : new boolean[] {true, false}) {
TimeLimiter limiter = TimeLimiter.of("inventory", TimeLimiterConfig.custom()
.timeoutDuration(Duration.ofMillis(100))
.cancelRunningFuture(cancel)
.build());
AtomicBoolean interrupted = new AtomicBoolean();
AtomicBoolean finished = new AtomicBoolean();
try {
limiter.executeFutureSupplier(() -> pool.submit(() -> {
try {
Thread.sleep(500); // a slow remote call
finished.set(true);
} catch (InterruptedException e) {
interrupted.set(true);
}
return "stock";
}));
} catch (TimeoutException e) {
System.out.println(" cancelRunningFuture=" + cancel + ": " + e.getMessage());
}
Thread.sleep(600);
System.out.println(" task interrupted: " + interrupted + ", ran to the end: "
+ finished);
}
pool.shutdown();
TimeLimiter cfLimiter = TimeLimiter.of("inventory", TimeLimiterConfig.custom()
.timeoutDuration(Duration.ofMillis(100)).build());
AtomicBoolean cfFinished = new AtomicBoolean();
CompletableFuture<String> slow = CompletableFuture.supplyAsync(() -> {
sleep(500);
cfFinished.set(true);
return "stock";
});
try {
cfLimiter.executeFutureSupplier(() -> slow);
} catch (TimeoutException e) {
sleep(600);
System.out.println(" CompletableFuture, cancelRunningFuture=true: cancelled: "
+ slow.isCancelled() + ", task ran to the end: " + cfFinished);
}
System.out.println("Retry (3 attempts) and circuit breaker, in both orders:");
for (boolean retryOutside : new boolean[] {true, false}) {
CircuitBreaker breaker = CircuitBreaker.of("inventory",
CircuitBreakerConfig.ofDefaults());
Retry retry = Retry.of("inventory", RetryConfig.custom()
.maxAttempts(3).waitDuration(Duration.ofMillis(10)).build());
AtomicInteger calls = new AtomicInteger();
Supplier<String> failing = () -> {
calls.incrementAndGet();
throw new IllegalStateException("503");
};
var builder = Decorators.ofSupplier(failing);
// the decorator added last is the outermost one
Supplier<String> decorated = retryOutside
? builder.withCircuitBreaker(breaker).withRetry(retry).decorate()
: builder.withRetry(retry).withCircuitBreaker(breaker).decorate();
try {
decorated.get();
} catch (IllegalStateException e) {
System.out.println(" " + (retryOutside ? "retry outside breaker"
: "breaker outside retry") + ": service called " + calls
+ " times, failed calls in the breaker: "
+ breaker.getMetrics().getNumberOfFailedCalls());
}
}
}
static void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
Time limiter, 100 ms:
cancelRunningFuture=true: TimeLimiter 'inventory' recorded a timeout exception.
task interrupted: true, ran to the end: false
cancelRunningFuture=false: TimeLimiter 'inventory' recorded a timeout exception.
task interrupted: false, ran to the end: true
CompletableFuture, cancelRunningFuture=true: cancelled: true, task ran to the end: true
Retry (3 attempts) and circuit breaker, in both orders:
retry outside breaker: service called 3 times, failed calls in the breaker: 3
breaker outside retry: service called 3 times, failed calls in the breaker: 1
- All three calls failed after 100 ms with a
, whose message names the limiter.TimeoutException - With
, the time limiter cancelled the executor'scancelRunningFuture=true , which interrupted the task: it did not run to the end. WithFuture , the caller stopped waiting but the task kept running and finished, still using its thread and still making its remote call.false - A
was cancelled too, but its task ran to the end anyway:CompletableFuture does not interrupt the thread that computes it. A time limiter protects the caller, not the resources the slow call uses.CompletableFuture.cancel - With the retry outside the breaker, each of the 3 attempts went through the breaker, which recorded 3 failed calls. With the breaker outside, it saw one call, the whole retry sequence, and recorded 1 failure. The service was called 3 times either way. In
, the decorator added last is the outermost one.Decorators
In Spring Boot, each pattern again has properties and an annotation. This configuration and method, from the Resilience4j documentation, set up one of each for the same inventory client; like the previous Spring Boot example, they were not run:
resilience4j:
retry:
instances:
inventory:
max-attempts: 3 # total attempts, including the first call
wait-duration: 200ms
enable-exponential-backoff: true
exponential-backoff-multiplier: 2
ratelimiter:
instances:
inventory:
limit-for-period: 50 # calls allowed ...
limit-refresh-period: 1s # ... per second
timeout-duration: 0 # do not wait for a permit
bulkhead:
instances:
inventory:
max-concurrent-calls: 20
max-wait-duration: 0
timelimiter:
instances:
inventory:
timeout-duration: 2s
cancel-running-future: true
@Retry(name = "inventory")
@CircuitBreaker(name = "inventory", fallbackMethod = "unknownStockLater")
@RateLimiter(name = "inventory")
@TimeLimiter(name = "inventory")
@Bulkhead(name = "inventory")
public CompletableFuture<StockLevel> stockForAsync(String sku) {
return CompletableFuture.supplyAsync(() -> inventory.fetch(sku));
}
- Note the difference in counting: Resilience4j's
includes the first call, while Spring'smax-attempts does not.maxRetries equalsmax-attempts: 3 .maxRetries = 2 works only on methods that return a@TimeLimiter or a reactive type, because it needs something it can stop waiting for. As the program showed, a timed-outCompletableFuture keeps running. For a blocking HTTP call, set the client's connect and read timeouts instead.CompletableFuture uses a semaphore by default, like@Bulkhead .@ConcurrencyLimit runs the call on a separate, bounded thread pool, configured undertype = Bulkhead.Type.THREADPOOL .resilience4j.thread-pool-bulkhead
When several annotations sit on one method, the default order from outermost to innermost is Retry, CircuitBreaker, RateLimiter, TimeLimiter, Bulkhead, then the method. So each retry passes through the breaker and counts in its statistics, as in the "retry outside breaker" line above, and once the breaker opens, the retry gets CallNotPermittedExceptionresilience4j.retry.retry-aspect-order
With Actuator, Resilience4j adds the /actuator/circuitbreakers/actuator/circuitbreakereventsregister-health-indicator: truemanagement.health.circuitbreakers.enabled: trueUPDOWNUNKNOWN
Traps that make resilience code harmful
- Retry storms: three layers that each retry three times turn one user request into up to 64 calls to the bottom service (4 × 4 × 4). Retry in one layer only, usually the one closest to the failing call, and add jitter.
- Retrying what cannot succeed: without
,includes retries everything, including validation errors and HTTP 400 responses. List the transient exceptions explicitly, as the second program does.@Retryable - Retrying what is not safe to repeat: a payment or an email sent twice is worse than one that failed. Retry only idempotent calls, or make the call idempotent with a key the receiver checks.
- Fallbacks that hide outages: a fallback that returns an empty list makes a failure look like "no data". Log and count every fallback, and prefer an explicit "unknown" value the caller can show.
- Self-invocation: all of these annotations work through proxies, so a call from another method of the same bean gets no retry, limit or breaker. The
Spring AOP page explains why. - No timeout at all: a retry, a bulkhead or a breaker cannot help with a call that never returns. Every remote client needs connect and read timeouts first; the patterns build on top of them.
Choosing a resilience tool
| Problem | Tool |
|---|---|
| Short failures that succeed on a later attempt | @Retryableincludes |
| Retry logic outside a bean method, or a policy chosen at run time | RetryTemplateRetryPolicy.builder() |
| A slow dependency that could take every thread | @ConcurrencyLimit@Bulkhead |
| A dependency that is down for minutes, not seconds | Resilience4j @CircuitBreaker |
| A quota on calls per second or per minute | Resilience4j @RateLimiter |
| An asynchronous call that must not wait forever | Resilience4j @TimeLimiterCompletableFuture.orTimeout |
| A blocking HTTP call that must not wait forever | Connect and read timeouts on the HTTP client |
| An existing application on Spring Retry | Keep it working, and move to the built-in @Retryable |
Start with timeouts on every client, add a retry with a short list of transient exceptions, and add a circuit breaker for dependencies whose outages last long enough to matter. The