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

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 @Transactional: an annotation on a bean method, and a proxy that runs the pattern around the call. That brings the same limits. A call on this skips the proxy, and so skips the retry or the breaker.

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:

Where each pattern comes from in a Spring Boot 4 application
PatternSpring Framework 7 (built in)Resilience4j 2.4
Retry with backoff@Retryable, RetryTemplate@Retry
Bulkhead (concurrent calls)@ConcurrencyLimit@Bulkhead, semaphore or thread pool
Circuit breakerNone@CircuitBreaker
Rate limiter (calls per period)None@RateLimiter
Time limiterNone for synchronous calls@TimeLimiter, for asynchronous calls
Fallback methodNone; catch the exceptionfallbackMethod attribute
Metrics and healthMethodRetryEvent, RetryListenerMicrometer 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:

Java
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"));
        }
    }
}
Output
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
  • @EnableResilientMethods turned on the processing of the annotation, and the bean became a CGLIB proxy, PriceClient$$SpringCGLIB$$0. The proxy catches the exception and calls the real method again.
  • The gaps were about 100, 200 and 400 ms: delay = 100 is the first wait, and multiplier = 2 doubles it after each failure. The fourth attempt succeeded, so the caller received the result and never saw the three exceptions.
  • maxRetries counts retries, not attempts. With maxRetries = 4, the method may run up to five times in total: one first call and four retries.

Without attributes, @Retryable retries every exception up to 3 times, 1 second apart. Two more attributes shape the delay. maxDelay caps how large the doubling may grow. jitter adds a random amount to each delay, so that a hundred clients that failed at the same moment do not all retry at the same moment too. Each numeric attribute also has a String form, such as delayString = "${pricing.retry-delay}", that reads the value from configuration.

The annotation also works on methods that return a Reactor Mono or Flux. There it adds Reactor's own retry operator to the pipeline instead of looping around a blocking call.

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:

Java
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);
                }
            }
        }
    }
}
Output
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: TransientException is in includes, so the method ran 3 times, the first call plus maxRetries = 2. The caller then got the last original exception, the one that says "attempt 3", not a wrapper.
  • expired: InvalidCardException is not included, so the proxy gave up after 1 attempt and rethrew it at once.
  • wrapped: the thrown IllegalStateException is not in includes, but its cause is a TransientException. Spring matches the causes too, so this call was retried 3 times as well.
  • 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 RetryException and has isRetryAborted() set, marking the point where the proxy stopped retrying.

Three attributes choose the exceptions. The includes attribute lists the ones to retry, and value is a shortcut for it, so @Retryable(TransientException.class) means the same. The excludes attribute lists ones that must never be retried. The predicate attribute takes a MethodRetryPredicate class for decisions that need more than the type, such as retrying an HTTP error only when its status code is 503; it runs after includes and excludes.

The program also shows why the counter is read through attempts(). A CGLIB proxy is a subclass with its own copy of every field, so reading client.attempts directly on the proxy returns 0 whatever the real bean has counted. Read state of a proxied bean through its methods.

Programmatic retries with RetryTemplate

RetryTemplate retries a block of code without an annotation or a proxy, which suits code that is not a bean method or needs a different policy per call. This program uses a rates service that always fails, so both policies run until they give up, one by count and one by time:

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 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());
        }
    }
}
Output
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 fetchRates ran 4 times. The listener's onRetryFailure fired only for calls 2 to 4, the retries, not for the first call.
  • execute threw the checked RetryException, which keeps all 4 exceptions in getExceptions() and the last one in getLastException(). Its message names the operation from Retryable.getName(); a plain lambda would be named by its generated class instead.
  • 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.
  • invoke takes a Supplier or Runnable and rethrows the last original exception, like @Retryable does. Use it when the caller only cares about the final failure.

RetryPolicy.withDefaults(), which new RetryTemplate() uses, matches the annotation's defaults: 3 retries, 1 second apart. timeout also exists on the annotation, and is the right way to bound a retry loop that sits inside a request with its own deadline.

Retries and transactions

When a method has both @Retryable and @Transactional, the order of the two proxies decides what a retry repeats. A transfer that hits a lock timeout after its insert shows it:

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.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));
        }
    }
}
Output
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 TransientDataAccessResourceException. Its transaction rolled back, removing the row.
  • 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, so a cached result is never retried. With @Async the order is reversed: the method is handed to the executor once, and all retries run on that one pool thread.

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 that charged a card before the response was lost is not: retrying it charges the card twice, unless the remote API accepts an idempotency key that lets it ignore the duplicate. See Spring @Transactional for how the transaction proxy works.

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:

Java
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());
        }
    }
}
Output
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 BLOCK policy and a limit of 2, no more than 2 calls were inside render at once. The other four waited, so the six calls took about 300 ms, three rounds of two, instead of 100 ms.
  • With policy = ThrottlePolicy.REJECT and a limit of 1, the second call did not wait. It failed at once with InvocationRejectedException, a subclass of RejectedExecutionException, while the first call finished normally.

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 reads the limit from configuration.

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 (COUNT_BASED) or the last N seconds (TIME_BASED).
  • OPEN: once the failure rate passes the threshold, calls are rejected at once with CallNotPermittedException, without touching the service, for 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-circuitbreaker module. The programs in this section and the next use the core modules directly: resilience4j-all 2.4.0 for the Decorators builder, with circuit breaker, bulkhead, time limiter and core 2.4.0, and the rate limiter and retry modules 2.3.0, the newest available here. This program configures a small breaker, sends calls to a service that is down, then brings the service back:

Java
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");
    }
}
Output
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 OPEN. On a service with little traffic, such a breaker would almost never open, which is why the program sets smaller values.
  • The failure rate printed as -1% until 5 calls were recorded: below minimumNumberOfCalls, the breaker does not compute a rate at all.
  • X-9 threw UnknownSkuException, which is in ignoreExceptions, so the buffered calls stayed at 1. The fallback still ran for it: withFallback catches every exception, ignored or not.
  • The fifth recorded call, A-5, made the rate 100%, and the event listener printed the transition from CLOSED to OPEN. The next call, A-6, never reached the service: the fallback received a CallNotPermittedException. Without a fallback, the caller gets that exception with the message shown.
  • After 300 ms, longer than the 200 ms wait, the next call moved the breaker to HALF_OPEN and was let through. Two successful trial calls, the permittedNumberOfCallsInHalfOpenState, closed it, and closing reset the window, so the metrics started again from 0.

The transition to HALF_OPEN happened on the first call after the wait, not on a timer. Set automaticTransitionFromOpenToHalfOpenEnabled(true) to have a scheduler do it, which matters when the state is shown on a health endpoint.

In Spring Boot, the same breaker is configured with properties and applied with an annotation. Resilience4j 2.4.0 added the resilience4j-spring-boot4 module for Spring Boot 4; Spring Boot 3 uses resilience4j-spring-boot3. That module is not available here, so the configuration and annotated class below were checked against the Resilience4j documentation but not run. The annotations are processed by an aspect, so the application also needs the AspectJ starter, which Spring Boot 4 renamed from spring-boot-starter-aop to spring-boot-starter-aspectj:

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

YAML
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
Java
@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: sliding-window-size to slidingWindowSize, ignore-exceptions to ignoreExceptions, and so on.
  • 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. ignore-exceptions excludes business errors, such as an unknown product code, that say nothing about the health of the service.
  • The fallback must be in the same class, with the same parameters plus one exception parameter. It runs for any failure, including CallNotPermittedException when the breaker is open. With several fallbacks, the one whose exception type matches most closely is chosen.

Besides the three main states, a breaker can be put in DISABLED, FORCED_OPEN or METRICS_ONLY by hand, for example to stop all calls during a known outage.

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:

Java
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();
    }
}
Output
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 RequestNotPermitted, because timeoutDuration is zero. After 600 ms a new period had started, and the second round got 3 permits again.
  • 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, getAvailableConcurrentCalls() was 0, and callers 3 and 4 got BulkheadFullException without waiting, because maxWaitDuration is zero.
  • Callers 1 and 2 finished normally once released. A bulkhead with a non-zero wait would have queued callers 3 and 4 instead, as @ConcurrencyLimit with the BLOCK policy did earlier.

A time limiter needs something it can stop waiting for, a Future or a CompletableFuture. The second program times out three slow tasks, then combines a retry and a circuit breaker in both orders:

Java
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();
        }
    }
}
Output
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 TimeoutException, whose message names the limiter.
  • With cancelRunningFuture=true, the time limiter cancelled the executor's Future, which interrupted the task: it did not run to the end. With false, the caller stopped waiting but the task kept running and finished, still using its thread and still making its remote call.
  • A CompletableFuture was cancelled too, but its task ran to the end anyway: CompletableFuture.cancel does not interrupt the thread that computes it. A time limiter protects the caller, not the resources the slow call uses.
  • 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 Decorators, the decorator added last is the outermost one.

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:

YAML
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
Java
@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 max-attempts includes the first call, while Spring's maxRetries does not. max-attempts: 3 equals maxRetries = 2.
  • @TimeLimiter works only on methods that return a CompletableFuture or a reactive type, because it needs something it can stop waiting for. As the program showed, a timed-out CompletableFuture keeps running. For a blocking HTTP call, set the client's connect and read timeouts instead.
  • @Bulkhead uses a semaphore by default, like @ConcurrencyLimit. type = Bulkhead.Type.THREADPOOL runs the call on a separate, bounded thread pool, configured under 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 CallNotPermittedException straight away. Properties such as resilience4j.retry.retry-aspect-order change the order; a higher value means the aspect runs further out.

With Actuator, Resilience4j adds the /actuator/circuitbreakers and /actuator/circuitbreakerevents endpoints, similar ones for the other patterns, and Micrometer metrics for each instance. Setting register-health-indicator: true on an instance, and management.health.circuitbreakers.enabled: true, adds the breaker to the health endpoint: closed maps to UP, open to DOWN and half-open to UNKNOWN. The Actuator page covers those endpoints.

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, @Retryable retries everything, including validation errors and HTTP 400 responses. List the transient exceptions explicitly, as the second program does.
  • 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

Which tool fits which problem in Spring Boot 4
ProblemTool
Short failures that succeed on a later attempt@Retryable with includes, a delay and a multiplier
Retry logic outside a bean method, or a policy chosen at run timeRetryTemplate with RetryPolicy.builder()
A slow dependency that could take every thread@ConcurrencyLimit, or Resilience4j @Bulkhead
A dependency that is down for minutes, not secondsResilience4j @CircuitBreaker with a fallback
A quota on calls per second or per minuteResilience4j @RateLimiter
An asynchronous call that must not wait foreverResilience4j @TimeLimiter, or CompletableFuture.orTimeout
A blocking HTTP call that must not wait foreverConnect and read timeouts on the HTTP client
An existing application on Spring RetryKeep it working, and move to the built-in @Retryable when upgrading to Spring Framework 7

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 Spring Retry page covers the older Spring Retry project, which earlier Spring Boot versions used.