Skip to content

    System Design

    Resilience4j in Spring: Retry, Circuit Breaker, Bulkhead and Time Limiter

    Wire Resilience4j into a Spring Boot 4 service with annotations and YAML, learn the documented defaults and aspect order, and run a lab on a fake clock.

    By Published 11 min read

    Share

    Standard lessonintermediateSpring Boot labBackend System Design

    Before this: Circuit Breaker and Bulkhead

    What you'll learn: By the end of this lesson you will be able to add Resilience4j to a Spring Boot service, configure retry, circuit breaker, bulkhead and time limiter in YAML, state their documented defaults, explain the order in which the annotations wrap a call and what that order does to your statistics, write a fallback that matches the library's rules, and read the output of a lab that exercises all four against a controllable fake dependency and a fake clock.

    A restaurant kitchen has all four controls without calling them that. A timer on each dish says when to stop waiting for the sauce. If the sauce splits, the cook tries once or twice more. If a supplier keeps delivering spoiled fish, the kitchen stops ordering from them for a while and puts a substitute on the menu. And only so many burners can be given to one dish, so one slow braise cannot stop every other order. Resilience4j is those four habits as code you attach to a method.

    The concepts are taught in the previous lesson, circuit breaker and bulkhead, and in timeouts, retries, backoff and jitter. This lesson is the Spring wiring: what to put in the build, what each property is called and defaults to, how the pieces nest, and the surprises that appear when they interact.

    Verified with Java 25, Spring Boot 4.1.2 and Resilience4j 2.4.0 (resilience4j-spring-boot4), on 2026-12-01. Defaults are quoted from the Resilience4j documentation pages listed at the end.

    The core idea

    Resilience4j is a library of small, composable decorators (retry, circuit breaker, bulkhead, time limiter) that you attach to a call, in Spring most easily as annotations whose behaviour is configured by name in application.yml. The decisions that matter are not the annotations but the numbers behind them, the order they nest in, and what the caller gets when one of them refuses.

    Three illustrations run through it, each labelled:

    • Minimal example: the lab report below, six small scenarios against a fake dependency.
    • Realistic example: ShopStream's payment and recommendation clients, in "In practice".
    • Failure example: a retry that keeps hammering an open breaker and holds threads for seconds, in "The 2 a.m. failure".

    Setup for Spring Boot 4

    Resilience4j publishes a separate Spring Boot module per Boot generation. The Maven Central metadata for io.github.resilience4j:resilience4j-spring-boot4 lists a single release, 2.4.0, which is the one used here. The Resilience4j documentation for the Boot 3 module says it expects the actuator and AOP starters to be present at runtime. Spring Boot 4 renamed the AOP starter: its migration guide says spring-boot-starter-aop "has been renamed to spring-boot-starter-aspectj". The lab's build therefore needs:

    dependencies {
        implementation("org.springframework.boot:spring-boot-starter")
        implementation("org.springframework.boot:spring-boot-starter-aspectj")
        implementation("io.github.resilience4j:resilience4j-spring-boot4:2.4.0")
    }

    The lab runs without the actuator starter and its context starts, so the annotations themselves do not need it. They are Spring AOP aspects, which is why the AspectJ starter is on the list.

    The four decorators and their documented defaults

    Each decorator is configured per named instance under resilience4j.<module>.instances.<name>, and an annotation refers to the instance by name.

    Decorator Annotation Properties used in this lesson Documented defaults
    Retry @Retry maxAttempts, waitDuration, ignoreExceptions maxAttempts 3, which includes the first call; waitDuration 500 ms, a fixed wait between attempts; retries every exception unless told otherwise
    Circuit breaker @CircuitBreaker slidingWindowType, slidingWindowSize, minimumNumberOfCalls, failureRateThreshold, waitDurationInOpenState, permittedNumberOfCallsInHalfOpenState COUNT_BASED, 100, 100, 50 percent, 60,000 ms, 10
    Bulkhead @Bulkhead maxConcurrentCalls, maxWaitDuration 25 and 0
    Time limiter @TimeLimiter timeoutDuration, cancelRunningFuture 1 second and true, from the library's TimeLimiterConfig source

    Two things in the table deserve attention. First, the circuit breaker defaults assume a busy service: with a window of 100 and a minimum of 100 calls, a breaker on a dependency that receives a few calls a minute needs a long time to judge anything, so tune the window and the minimum to your real traffic. Second, the retry default retries every exception, which includes the rejection an open breaker throws (see the lab).

    The library also documents ignoreExceptions and recordExceptions for the breaker, and for retry a retryExceptions list and predicates. Configuration can also be shared through named configs that instances extend; the documentation's YAML example shows the shape.

    The order in which they nest

    The Spring Boot documentation states the default order in which the annotation aspects apply: Retry ( CircuitBreaker ( RateLimiter ( TimeLimiter ( Bulkhead ( Function ) ) ) ) ). Retry is outermost, the bulkhead is next to your method. It also documents aspect order properties, for example resilience4j.retry.retryAspectOrder and resilience4j.circuitbreaker.circuitBreakerAspectOrder, where a higher value means higher priority. The order of the annotations in your source does not matter.

    flowchart LR accTitle: Default nesting of the Resilience4j aspects accDescr: A call enters Retry first, then the circuit breaker, then the rate limiter, then the time limiter, then the bulkhead, and finally reaches the method. The result or exception travels back out the same way. R[Retry] --> C[Circuit breaker] --> L[Rate limiter] --> T[Time limiter] --> B[Bulkhead] --> M[Your method]

    Figure 1. The default order, outermost on the left. How to read this: each retry attempt passes through every decorator to its right, so the circuit breaker sees each attempt as its own call and the bulkhead releases its slot between attempts. If you moved the breaker outside the retry, it would see only the final outcome of each group of attempts.

    Fallbacks

    A fallback is a method named in the annotation (fallbackMethod). The documentation's rules: it must have the same signature as the protected method with just one extra parameter, the exception; it should be in the same class; when several fallbacks fit, the closest match to the exception type is used. A fallback that takes only CallNotPermittedException therefore answers an open breaker and nothing else: any other exception still reaches the caller, which is what the lab's chargeOnce does.

    Build it

    This lab is a Spring Boot 4.1.2 context (@SpringBootTest) with no web server and no Docker. Fake dependencies take their next outcome from a script (OK, FAIL or HANG) and count their calls, a ManualClock stands in for time, and every number printed comes from those counters or from Resilience4j's own metrics, never from a wall clock.

    Setup. From the repository's examples/spring-labs folder:

    cd examples/spring-labs && ./gradlew :labs:resilience4j-spring:test

    It runs 6 behaviour tests and a golden test that compares the report below with the committed file (add -PwriteGolden to rewrite it after a deliberate change). The configuration the lab uses is:

    resilience4j:
      circuitbreaker:
        instances:
          payments:
            slidingWindowType: COUNT_BASED
            slidingWindowSize: 4
            minimumNumberOfCalls: 4
            failureRateThreshold: 50
            waitDurationInOpenState: 30s
            permittedNumberOfCallsInHalfOpenState: 2
      retry:
        instances:
          payments:
            maxAttempts: 3
            waitDuration: 10ms
          paymentsStrict:
            maxAttempts: 3
            waitDuration: 10ms
            ignoreExceptions:
              - io.github.resilience4j.circuitbreaker.CallNotPermittedException
      bulkhead:
        instances:
          recommendations:
            maxConcurrentCalls: 2
            maxWaitDuration: 0
      timelimiter:
        instances:
          recommendations:
            timeoutDuration: 100ms
            cancelRunningFuture: true

    The protected methods are plain annotated Java:

    @Retry(name = "payments")
    @CircuitBreaker(name = "payments")
    public String charge() {
        return payments.call();
    }
    
    @CircuitBreaker(name = "payments", fallbackMethod = "deferred")
    public String chargeOnce() {
        return payments.call();
    }
    
    public String deferred(CallNotPermittedException e) {
        return "deferred: breaker open";
    }

    The only wiring that is not configuration is the clock. A CircuitBreakerConfigCustomizer swaps the clock the payments breaker reads, so 30 seconds of open state pass instantly:

    @Bean
    CircuitBreakerConfigCustomizer paymentsClock(ManualClock clock) {
        return CircuitBreakerConfigCustomizer.of("payments", builder -> builder.clock(clock));
    }

    Expected output, captured from a real run (Spring Boot 4.1.2, Resilience4j 2.4.0, compiled for Java 25, 2026-12-01):

    1. Retry rescues a blip (payments script: fail, fail, ok; retry maxAttempts 3)
      result: payments ok
      calls that reached payments: 3
      breaker recorded 2 failed and 1 successful calls; state CLOSED
    
    2. Retry in front of the breaker, payments down (window 4, minimum 4 calls, 50%)
      request 1: DownstreamException; calls that reached payments: 3; rejected by the breaker: 0; state CLOSED
      request 2: CallNotPermittedException; calls that reached payments: 4; rejected by the breaker: 2; state OPEN
    
    3. Same outage, but the retry instance ignores CallNotPermittedException
      request 1: DownstreamException; calls that reached payments: 3; rejected by the breaker: 0; state CLOSED
      request 2: CallNotPermittedException; calls that reached payments: 4; rejected by the breaker: 1; state OPEN
    
    4. Breaker states on a fake clock (window 4, minimum 4 calls, 50%, open 30 s, 2 trial calls)
      t (ms)  result    state     event
           0  ok        CLOSED    healthy call
         100  failed    CLOSED    failure
         200  ok        CLOSED    success
         300  failed    OPEN      4th call: 2 of 4 failed (50%), the breaker opens
         400  fallback  OPEN      open: the fallback answers, payments is not called
       30300  fallback  OPEN      30000 ms after opening: still open
       30301  failed    HALF_OPEN 1 ms later: half-open, trial call 1 fails
       30302  failed    OPEN      trial call 2 fails: back to open
       60302  fallback  OPEN      30000 ms after reopening: still open
       60303  ok        HALF_OPEN half-open, trial call 1 succeeds
       60304  ok        CLOSED    trial call 2 succeeds: closed
    calls that reached payments: 8 of 11 attempted
    
    5. Semaphore bulkhead: 2 concurrent calls, no waiting (maxConcurrentCalls 2, maxWaitDuration 0)
      2 calls are inside and hung; free slots: 0
      a third call returns at once: [] (fallback: bulkhead full)
      calls that reached recommendations: 2
      a hung call finishes: recommendations ok
      a hung call finishes: recommendations ok
      free slots after they finish: 2
    
    6. Time limiter: timeoutDuration 100 ms, cancelRunningFuture true
      the caller gets: [] (fallback: time limit)
      calls still running inside recommendations: 1
      after release: 0

    Scenario 1 is retry doing its job: two failures then success, three calls reached the dependency, and the breaker recorded all three attempts. Scenarios 2 and 3 are the trap. With the retry outside the breaker, the second request's first attempt is the fourth recorded failure, so the breaker opens; the second and third attempts are then rejected by the breaker, and the retry, which retries every exception, tried the rejection twice (2 rejections). The paymentsStrict instance ignores CallNotPermittedException, so retry stops at the first rejection (1 rejection). Both made the same 4 calls to the dependency; the difference is the pointless extra attempt, and in production the extra wait between attempts.

    sequenceDiagram accTitle: A retry outside a circuit breaker retries the rejection accDescr: On the second request the first attempt reaches the dependency and fails, which opens the breaker. The retry waits and tries again twice, and the breaker rejects both attempts without calling the dependency. The caller finally receives the rejection exception. participant C as Caller participant R as Retry participant B as Circuit breaker participant P as Payments C->>R: charge R->>B: attempt 1 B->>P: call P-->>B: fails, 4th recorded failure opens the breaker B-->>R: DownstreamException Note over R: waits waitDuration R->>B: attempt 2 B-->>R: CallNotPermittedException, no call made Note over R: waits waitDuration R->>B: attempt 3 B-->>R: CallNotPermittedException, no call made R-->>C: CallNotPermittedException

    Figure 2. The second request of scenario 2. How to read this: only the first attempt touches the dependency. The next two are rejections that the retry still waits for and repeats, which is exactly what paymentsStrict avoids. Scenario 4 walks the breaker through a full cycle on the fake clock: opens at the fourth call at 50 percent, is still open 30,000 ms later, becomes half-open at the first call 1 ms after that, is reopened by two failed trials and closed by two good ones; 8 of the 11 calls reached the dependency. Scenario 5 is the bulkhead: the third concurrent call gets the fallback at once. Scenario 6 is the time limiter: the caller got its fallback after 100 ms, but one call is still running inside the dependency.

    That last line is the caveat. The documented Java behaviour of CompletableFuture.cancel(boolean) is that the argument has no effect, because interrupts are not used to control its processing. Cancelling the future frees the caller, not the worker. A time limiter therefore bounds how long a caller waits, and it needs a bulkhead (or a bounded pool) next to it to bound how many abandoned calls pile up.

    sequenceDiagram accTitle: A time limiter frees the caller but not the worker accDescr: The caller invokes the asynchronous method. The time limiter starts the call on a worker thread and the call hangs in the dependency. After 100 milliseconds the time limiter answers the caller with the fallback, while the worker is still inside the dependency. participant C as Caller participant T as Time limiter participant W as Worker thread participant D as Dependency C->>T: listAsync T->>W: run the call W->>D: call, it hangs Note over T: 100 ms pass T-->>C: fallback result Note over W,D: still running until the dependency answers

    Figure 3. Scenario 6. How to read this: the caller's wait ends at the time limit, but the worker's does not, so the number of abandoned calls is bounded only by something else, such as a bulkhead.

    Break it. In application.yml, delete the ignoreExceptions entry of paymentsStrict: its retry now retries the rejection too, so scenario 3 shows 2 rejections, and the golden test and aRetryThatIgnoresTheRejectionStopsAtTheFirstOne fail. Restore the file and run the tests again.

    What the lab leaves out. The web layer, the actuator endpoints and metrics, real timing, rate limiting, the thread-pool bulkhead and everything outside one process.

    Trade-offs

    Choice Gain Cost Wrong when
    Annotations Little code, config in YAML The order is implicit You need to compose by hand or per call
    Retry outside the breaker (default) The breaker sees each attempt A rejected call can be retried The retry ignores rejections
    Retry ignoring CallNotPermittedException Fails fast when the breaker is open One more setting to remember Your fallback is to try later
    Time limiter The caller stops waiting The worker keeps running No bulkhead bounds abandoned calls
    Library defaults Quick start Sized for busy services Traffic is low or latency is long

    In practice: ShopStream's payment and recommendation clients

    This is the realistic example, an educational scenario on the course's running example ShopStream. Nothing in it describes a real company, and every number is an illustrative assumption.

    This is a realistic scenario, not a case history.

    The situation

    ShopStream's order service calls a payment provider at up to 58 checkouts per second at peak (the course's shared number) and an optional recommendations service from the product page.

    Starting architecture

    ShopStream order service with Resilience4j clientsShoppers to Order service (requests); Order service to Payments client (checkout); Order service to Recommender client (product page); Payments client to Payment provider; Recommender client to RecommenderShoppersShoppersOrder service: Spring BootOrder serviceSpring BootPayments client: retry, breakerPaymentsclientretry, breakerRecommender client: bulkhead, limiterRecommenderclientbulkhead, limiterPayment providerPaymentproviderRecommenderRecommenderrequestscheckoutproduct page

    Figure 4. Two clients, two sets of decorators. How to read this: each client is a Spring bean whose methods carry the annotations of its own dependency, so the payment breaker and the recommendations bulkhead never share state.

    Options considered

    Option Behaviour when the provider fails Risk
    A. Library defaults The breaker needs 100 calls before judging and stays open 60 s; retry waits 500 ms between attempts Slow to open, long to recover, slow rejections
    B. Tuned breaker, default retry Opens sooner, but each rejected request is retried and waits Held threads while "failing fast"
    C. Tuned breaker, retry ignoring rejections Opens sooner and rejects at once More settings, must be tested

    The decision

    Option C, with a window and minimum sized from the real call rate, a retry only for idempotent operations (the payment call is retried only with an idempotency key, the subject of the lesson on idempotency keys and safe retries), and a fallback that accepts the order as payment pending.

    Rollout and verification

    The team would add the lab's scenarios as integration tests with a fake provider and a manual clock, then watch the library's metrics. The Resilience4j Micrometer documentation names resilience4j.circuitbreaker.state, resilience4j.circuitbreaker.not.permitted.calls and resilience4j.bulkhead.available.concurrent.calls, among others. Verification is that rejections rise while the provider fails, retries do not.

    The 2 a.m. failure

    The page reads: checkout latency is up while the breaker is open. Traffic is accepted as "payment pending" as designed, yet each request takes about a second. The cause is scenario 2: the retry wraps the breaker, the breaker rejects, and the retry waits its default 500 ms before each further attempt, so a request that should fail in microseconds holds a thread for a second. At the course's peak of 58 per second that is about 58 threads busy doing nothing (illustrative).

    The checks: compare the breaker's not-permitted count with the retry counts, and look at per-request latency while open. The mitigation is to ignore CallNotPermittedException in the retry configuration, as paymentsStrict does. The lasting fix is a test like the lab's scenario 3 that fails if rejections are retried.

    Architect's notes

    • Set every number. The defaults are documented, but they describe nobody's traffic.
    • Know the order. It decides what each decorator counts.
    • Ignore rejections in retry. An open breaker and a full bulkhead are answers, not faults to repeat.
    • Pair a time limiter with a bulkhead. Giving up on a call does not stop it.
    • Test with fakes and a clock. State machines are easiest to verify when time is injected.

    Common mistakes

    • Leaving the breaker's window and minimum at 100. On quiet services it never opens.
    • Retrying non-idempotent calls. Retry only with a safe key.
    • Reading the order from the source file. It comes from the aspect order, not from line order.

    Key takeaways

    • Four named decorators, configured in YAML under resilience4j.<module>.instances.<name> and attached by annotation.
    • Defaults are documented and sized for busy services; set your own.
    • Default order: Retry ( CircuitBreaker ( RateLimiter ( TimeLimiter ( Bulkhead ( call ) ) ) ) ).
    • Fallbacks take the exception as one extra parameter, and the closest match wins.
    • A time limiter frees the caller, not the worker.

    Practice exercises

    Exercise 1 (30 min). Run the lab. Predict scenarios 2 and 3 before looking.

    Exercise 2 (45 min). Change slidingWindowSize and minimumNumberOfCalls to 6 and predict scenario 4.

    Exercise 3 (1 hour). Run "Break it", confirm the tests fail, restore the file and run the tests again.

    Exercise 4 (2 hours). Add a @TimeLimiter instance plus a bulkhead to a second method and show with counters that abandoned calls stay bounded.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments