Your service calls another service. One day that other service gets slow, or goes down. Without protection, every request to your service now waits on the broken one, threads pile up, and your service is down too — a failure in one place spreads to every caller. A circuit breaker stops the spread: after enough failures it stops calling the broken dependency for a while and answers immediately with a fallback, then carefully checks whether the dependency has recovered.
This post starts from that idea and builds a working circuit breaker with Resilience4j on Spring Boot 4.1, then shows every state it moves through from real runs rather than diagrams alone. After that it covers the failures people actually hit: calls that are slow rather than broken, timeouts that do not stop the work, business exceptions that trip the breaker, and a fallback method that silently never runs. It finishes with the rest of the Resilience4j toolbox and a straight answer to the question Spring Framework 7 raised: which of this do you still need Resilience4j for, now that core ships its own @Retryable and @ConcurrencyLimit? Most sections end with a Going deeper panel you can open or ignore.
Versions this was verified against. Spring Boot 4.1.2 (GA, published to Maven Central 22 October 2026), Spring Framework 7.0.10, Resilience4j 2.4.0 via its resilience4j-spring-boot4 module (published to Maven Central 14 March 2026), Eclipse Temurin JDK 25.0.5 LTS. Companion code: resilience4j-circuit-breaker — 20 tests, all passing; every console block below was written by one of those tests and is quoted unedited.
A circuit breaker is a memory for failures
Think of the breaker in a fuse box. While everything is fine it stays closed and current flows. When it detects trouble it opens and nothing flows at all, which protects everything behind it. After a while you try the switch again, cautiously. A software circuit breaker has exactly those three states: CLOSED (calls go through, and the breaker counts how they turn out), OPEN (calls are refused instantly, without touching the dependency), and HALF_OPEN (a few trial calls are let through to see if the dependency is back).
The diagram is the whole mechanism, and every arrow is a number you set in YAML: failureRateThreshold and minimumNumberOfCalls move CLOSED to OPEN, waitDurationInOpenState moves OPEN to HALF_OPEN, and permittedNumberOfCallsInHalfOpenState decides how many probes are needed to close again. The one sentence worth carrying forward: a breaker remembers what happened on previous calls; a retry does not. That difference is why Spring Framework 7’s built-in @Retryable cannot replace it, and the transcripts below and the Spring section later both come back to it.
Going deeper: what the sliding window counts, and the defaults that surprise people
The breaker keeps a sliding window of recent call outcomes, either the last N calls (COUNT_BASED) or the last N seconds (TIME_BASED), and it does not judge anything until the window holds minimumNumberOfCalls results. That floor exists so a fresh breaker does not trip on noise: one connection refused during a deployment should not open a circuit that is about to see healthy traffic.
The library defaults are tuned for high-traffic services, not for a low-traffic internal API. Printed from CircuitBreakerConfig.ofDefaults() in 2.4.0 by ClaimsCheckTest:
slidingWindowType = COUNT_BASED
slidingWindowSize = 100
minimumNumberOfCalls = 100
failureRateThreshold = 50.0
slowCallRateThreshold = 100.0
slowCallDurationThreshold = PT1M
waitIntervalFunctionInOpenState(1) = 60000 ms
permittedNumberOfCallsInHalfOpenState = 10
automaticTransitionFromOpenToHalfOpen = false
With minimumNumberOfCalls = 100, a service that sees ten calls a minute needs about ten minutes of traffic before the breaker will even evaluate the failure rate, and a tripped breaker then stays open for a full minute. Neither is wrong, but if you copied a config from a blog and your breaker never seems to trip, this is the first thing to check.
- Resilience4j reference: CircuitBreaker — the full property list.
- The state rules are small enough to read in source:
io.github.resilience4j.circuitbreaker.CircuitBreaker.State.
The smallest circuit breaker that works
Three things make a working breaker: a dependency, an annotation on the method you want to protect, and a block of YAML. First the dependency. Resilience4j’s annotations work through Spring AOP proxies, so you need the AOP starter next to the Resilience4j one — and on Boot 4 that starter has a new name, which the next section is about. The two dependencies, from the module’s pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aspectj</artifactId>
</dependency>
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-spring-boot4</artifactId>
<version>2.4.0</version>
</dependency>
Then the annotation. @CircuitBreaker wraps the method, and fallbackMethod names what to return when the call fails or the breaker refuses it. This is the whole of R4jPaymentService.java, trimmed to the method and its fallback:
@CircuitBreaker(name = "paymentService", fallbackMethod = "fallback")
public String pay(String orderId) {
return downstream.call();
}
private String fallback(String orderId, Throwable ex) {
return "FALLBACK for " + orderId + ": " + ex.getClass().getSimpleName() + " - " + ex.getMessage();
}
And the numbers, from application.yml. They are deliberately small so the demo trips in a handful of calls; read the table under the block for what each one means.
resilience4j:
circuitbreaker:
instances:
paymentService:
slidingWindowType: COUNT_BASED
slidingWindowSize: 10
minimumNumberOfCalls: 5
failureRateThreshold: 50
waitDurationInOpenState: 2s
permittedNumberOfCallsInHalfOpenState: 2
automaticTransitionFromOpenToHalfOpenEnabled: true
| Key | Plain meaning |
|---|---|
slidingWindowSize: 10 | judge the last 10 calls |
minimumNumberOfCalls: 5 | do not judge anything until 5 calls have been seen |
failureRateThreshold: 50 | open when half or more of the judged calls failed |
waitDurationInOpenState: 2s | stay open for 2 seconds, then allow trial calls |
permittedNumberOfCallsInHalfOpenState: 2 | let 2 trial calls through, and decide from them |
automaticTransitionFromOpenToHalfOpenEnabled: true | move to HALF_OPEN by the clock, without waiting for a call to arrive (shown in the next-but-one section) |
A wrong fallback does not fail. It is silently skipped. An earlier version of this post said a mismatched fallback throwsNoSuchMethodExceptionat call time; running it says otherwise. With a fallback whose parameters do not match, and with a fallback whose name does not exist, the application context starts normally and the original exception simply propagates, as if you had written no fallback at all:fallback exists, wrong parameters -> java.lang.IllegalStateException: downstream down fallback name does not exist -> java.lang.IllegalStateException: downstream down
The fallback must take the protected method’s parameters followed by aThrowable(or a more specific exception type). The fingerprint of the mistake is a raw downstream exception reaching your caller in a method that “has a fallback”. Source: R4jBadFallbackService, test: ClaimsCheckTest.
Going deeper: why the module uses a recorded-exception list, and what the demo downstream is
The config above also carries a recordExceptions entry, trimmed from the block so the table stays readable. It says only DownstreamUnavailableException counts as a failure; the section on which failures should count explains why that matters. The downstream itself is FlakyDownstream, a deterministic fake: you tell it which call number starts succeeding, so every transcript is predictable and a reader can check it call by call. A fake that fails 30% of the time at random teaches nothing you can verify.
- Full application config, including the Actuator keys: application.yml.
- Resilience4j Spring Boot reference: Getting started with Spring Boot 3 (the property keys are unchanged on Boot 4).
The build break, and the rename most guides still get wrong
Every pre-Boot-4 Resilience4j guide — including earlier versions of this post — tells you to add spring-boot-starter-aop alongside the Resilience4j starter, because the annotations need Spring AOP proxying to work. On Boot 4.1, doing that breaks the build before you get anywhere near a running application:
[ERROR] 'dependencies.dependency.version' for org.springframework.boot:spring-boot-starter-aop:jar is missing. @ line 19, column 17
(reproduced and captured by scripts/reproduce-starter-aop-break.sh against a minimal pom that only adds this one dependency: 00-starter-aop-build-error.txt)
It is tempting to read that error as “the starter is gone, assemble the AOP jars by hand instead” — an earlier draft of this section said exactly that. It’s wrong. Maven Central’s maven-metadata.xml for both artifact IDs, read together, settles it: spring-boot-starter-aop‘s last-ever published version is 4.0.0-M2; spring-boot-starter-aspectj‘s first-ever published version is 4.0.0-M3 — the very next milestone in the same 4.0 line, carrying straight through the 4.0.0 GA and every 4.1.x release since. That’s a rename at a specific milestone boundary, not a starter dropped with nothing replacing it. The renamed starter’s own published POM confirms it: it depends on exactly org.springframework:spring-aop:7.0.10 and org.aspectj:aspectjweaver:1.9.25.1, version-managed for you. The fix is a one-line rename, not a two-jar assembly:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aspectj</artifactId>
</dependency>
(from this repo’s pom.xml, which hits and fixes this exact error, and from the sibling resilience/pom.xml module, which already used the renamed starter correctly)
The mechanism behind that trap, for anyone who does hand-assemble instead of using the starter: Resilience4j’s Spring integration (resilience4j-spring6, which is what resilience4j-spring-boot4 actually depends on internally — the “spring-boot4” in the artifact name is about which Boot generation it targets, not an internal module rename, so don’t go looking for a “spring7” module) implements CircuitBreakerAspect, BulkheadAspect, RateLimiterAspect, and RetryAspect as real @Aspect classes — confirmed with unzip -l on the jar. Spring’s AnnotationAwareAspectJAutoProxyCreator needs org.aspectj:aspectjweaver on the classpath just to recognize a bean as an aspect at all. Add spring-aop without aspectjweaver and no proxy gets created for any of them — every Resilience4j annotation in the service silently stops working.
I found this failure mode the way the verification standard on this blog insists on: not by reading, by a failing test, before I’d confirmed the renamed starter was the real fix. CircuitBreakerTripAndRecoverTest failed with the raw DownstreamUnavailableException propagating straight out of R4jPaymentService.pay() — no fallback, no breaker state, nothing between the test and the exception, with only spring-aop on the classpath. Switching to spring-boot-starter-aspectj fixed every failing test in the same run, with no other changes.
If your Resilience4j annotations look like they’re doing nothing after a Boot 4 upgrade, check that you’re usingspring-boot-starter-aspectjand not a hand-assembledspring-aopdependency missingaspectjweaver. There is no startup warning either way. The fastest way to notice is exactly what caught it here: a test that asserts the fallback method ran, not just that the call returned something.
Watch it trip, stay open and recover
Now run it. The test sends six calls at a downstream that is permanently down, then three more while the breaker is open, then waits past waitDurationInOpenState, repairs the downstream, and sends two probes. The interesting lines, quoted from the full run in CircuitBreakerTripAndRecoverTest (01-circuitbreaker-trip.txt):
call 5 -> FALLBACK for order-5: DownstreamUnavailableException - payment-gateway rejected call #5 [breaker state=OPEN]
call 6 -> FALLBACK for order-6: CallNotPermittedException - CircuitBreaker 'paymentService' is OPEN and does not permit further calls [breaker state=OPEN]
call 7 -> FALLBACK for order-7: CallNotPermittedException - CircuitBreaker 'paymentService' is OPEN and does not permit further calls [breaker state=OPEN, downstream calls so far=5]
call 8 -> FALLBACK for order-8: CallNotPermittedException - CircuitBreaker 'paymentService' is OPEN and does not permit further calls [breaker state=OPEN, downstream calls so far=5]
call 9 -> FALLBACK for order-9: CallNotPermittedException - CircuitBreaker 'paymentService' is OPEN and does not permit further calls [breaker state=OPEN, downstream calls so far=5]
half-open probe 1 -> OK (call #1) [breaker state=HALF_OPEN]
half-open probe 2 -> OK (call #2) [breaker state=CLOSED]
Read the downstream calls so far=5 counter across calls 7, 8 and 9: it does not move. Three calls, zero downstream traffic. Call 5 is the call that tripped the breaker — the fifth failure met minimumNumberOfCalls at a 100% failure rate — and call 6 is the first one the breaker refused, with a different exception: CallNotPermittedException. That exception is how you recognise an open breaker in logs: it means the dependency was not even asked.
The recovery is the half-open state doing its job. After the wait, the breaker lets exactly two probes through; both succeed, so it closes. But the happy ending is only one of the two possible outcomes of HALF_OPEN. The second test keeps the downstream dead and watches the breaker’s own event stream instead of guessing from return values (StateTransitionsTest):
after 5 failing calls: state=OPEN
after waiting 2.2s (no call): state=HALF_OPEN
after 2 failing half-open probes: state=OPEN (downstream calls during probing: 2)
transitions recorded, in order:
CLOSED -> OPEN
OPEN -> HALF_OPEN
HALF_OPEN -> OPEN
Three things to read here. The breaker moved to HALF_OPEN after the 2.2 second sleep with no call arriving — that is automaticTransitionFromOpenToHalfOpenEnabled; without it the state would stay OPEN until the next call checked the clock. Both probes reached the downstream (2 calls during probing) and failed, so the breaker went straight back to OPEN, and the wait restarts from zero. And the recorded transitions are exactly the arrows of the diagram, in order.
Half-open is a probe, not a recovery. If your dependency is down for ten minutes and waitDurationInOpenState is 30 seconds, the breaker will send probes about twenty times and each failed set costs real calls. That is by design — it is how the breaker notices recovery — but it is why the half-open call count should be small, and why a production wait of a few seconds is often too short for a dependency that restarts slowly.
Going deeper: seeing the same states from outside the process
The event publisher used above is the same stream Actuator exposes over HTTP at /actuator/circuitbreakerevents, and the state itself is at /actuator/circuitbreakers. How to read both, with a real OPEN breaker captured over HTTP, is in the monitoring section below. Registering a listener takes four lines, quoted from StateTransitionsTest:
List<String> transitions = new ArrayList<>();
cb.getEventPublisher().onStateTransition(e ->
transitions.add(e.getStateTransition().getFromState() + " -> " + e.getStateTransition().getToState()));
In a real service the useful thing to do in that callback is log the transition at WARN with the breaker name — a breaker opening is the single most useful line you can have in an incident timeline.
- Resilience4j reference: CircuitBreaker events and metrics.
Testing state transitions without sleeping
The test above waits 2.2 seconds, which is fine once and painful across a suite. For everything that is not the timing itself — does the fallback run when the breaker is open, does the downstream stay untouched, does a probe succeed — you can set the breaker’s state directly instead of earning it with real failures. The registry hands you the same breaker the annotation uses:
cb.transitionToOpenState();
String whileOpen = service.pay("order-x");
t.line("OPEN -> " + whileOpen);
assertThat(whileOpen).startsWith("FALLBACK").contains("CallNotPermittedException");
assertThat(downstream.callsSoFar()).isZero();
cb.transitionToHalfOpenState();
String probe = service.pay("order-y");
t.line("HALF_OPEN -> " + probe);
assertThat(probe).startsWith("OK");
cb.transitionToClosedState();
t.line("CLOSED -> " + service.pay("order-z"));
cb.transitionToForcedOpenState();
t.line("FORCED_OPEN -> " + service.pay("order-w"));
That is a slice of StateTransitionsTest, and the whole test, all four states, runs in well under a second:
OPEN -> FALLBACK for order-x: CallNotPermittedException - CircuitBreaker 'paymentService' is OPEN and does not permit further calls
HALF_OPEN -> OK (call #1)
CLOSED -> OK (call #2)
FORCED_OPEN -> FALLBACK for order-w: CallNotPermittedException - CircuitBreaker 'paymentService' is FORCED_OPEN and does not permit further calls
elapsed under 1s, no Thread.sleep: true
FORCED_OPEN is a fourth state you never reach by failing: you set it yourself, and it refuses calls, which makes it a handy “kill switch” for a dependency you want to stop calling while you fix it. The Resilience4j documentation says it stays refusing until you change the state again; this test shows only the refusal, and the refusal message says FORCED_OPEN, not OPEN.
Forcing a state tests your wiring, not your thresholds. A test that callstransitionToOpenState()proves the fallback runs and the dependency is left alone; it cannot prove that yourfailureRateThresholdis the number you meant. Keep one real-time test, like the trip-and-recover one, per breaker configuration — thresholds are a contract, and a typo in YAML is the usual way to break it. Also assert that the fallback ran, not merely that the call returned: this is how the AOP-starter problem in the section above was caught while writing this post.
Going deeper: keeping breaker tests independent
Breakers live in a shared CircuitBreakerRegistry, so state leaks between tests in the same Spring context. These tests either start with cb.reset() or carry @DirtiesContext so each class gets a fresh context; pick one deliberately. Two further rules that paid for themselves here: drive the downstream with a deterministic fake whose call counter you can assert on, and assert on the breaker’s state and the downstream call count, never on log text.
- The test sources: StateTransitionsTest, CircuitBreakerTripAndRecoverTest.
- Run them:
cd resilience4j-circuit-breaker && mvn test; the new console blocks in this post are written totarget/transcripts/, so a plain test run adds nothing to your working tree.
Slow is a failure too: slow calls and timeouts
A dependency does not have to throw to hurt you. A call that succeeds after eight seconds ties up a thread for eight seconds, and a hundred of them in parallel is an outage with no exceptions in the logs. Resilience4j has two separate tools for this and they do different things: the breaker can treat slow calls as a reason to open, and the TimeLimiter bounds how long a caller waits.
The breaker first. Two extra keys, slowCallDurationThreshold and slowCallRateThreshold, define “slow” and “too many slow calls”:
resilience4j:
circuitbreaker:
instances:
slowBreaker:
slidingWindowType: COUNT_BASED
slidingWindowSize: 4
minimumNumberOfCalls: 4
failureRateThreshold: 50
slowCallDurationThreshold: 200ms
slowCallRateThreshold: 50
waitDurationInOpenState: 5s
The test makes four calls that all succeed, two fast and two taking 400 ms (LatencyAndTimeoutTest):
call 1 (10ms) -> ok:c1 [state=CLOSED]
call 2 (400ms) -> ok:c2 [state=CLOSED]
call 3 (10ms) -> ok:c3 [state=CLOSED]
call 4 (400ms) -> ok:c4 [state=OPEN]
failureRate=0.0% slowCallRate=50.0% numberOfFailedCalls=0 numberOfSlowCalls=2
call 5 -> FALLBACK:c5:CallNotPermittedException
Zero failed calls, yet the breaker is open: half the window was slower than 200 ms, which meets the 50% slow-call threshold. Latency alone opened it, and the fifth call never ran.
Now the timeout. @TimeLimiter gives up waiting after timeoutDuration, but it can only do that for a method that returns a CompletableFuture (or a reactive type), because it needs something it can stop waiting for. From R4jTimeLimiterService.java:
@TimeLimiter(name = "slowLookup", fallbackMethod = "timedOut")
public CompletableFuture<String> lookup(String id, long sleepMillis) {
return CompletableFuture.supplyAsync(() -> slow(id, sleepMillis));
}
private CompletableFuture<String> timedOut(String id, long sleepMillis, TimeoutException ex) {
return CompletableFuture.completedFuture("TIMED_OUT:" + id);
}
resilience4j:
timelimiter:
instances:
slowLookup:
timeoutDuration: 500ms
cancelRunningFuture: true
2000ms call -> TIMED_OUT:b (caller waited about 500ms, not 2000ms: true)
The two-second call is answered after about half a second with the fallback, instead of making the caller wait. That is the point of the tool. Now the part that is easy to get wrong:
The diagram shows what the next transcript measures (ClaimsCheckTest). The caller was released at 500 ms, but the call it gave up on kept running — cancelRunningFuture: true did not stop it, because cancelling a CompletableFuture does not interrupt the thread computing it:
caller got: TIMED_OUT:z
finished work right after timeout: 0
finished work 1.5s later: 1
Right after the timeout the counter of completed work was 0; a second and a half later it was 1. The slow call finished, quietly, after nobody was listening. If that call was a payment, it happened. This is why a TimeLimiter is not a substitute for a client timeout: set a connect and read timeout on the HTTP client itself so the work really stops, and use the TimeLimiter to bound what your callers experience.
Finally, put the two together. With @CircuitBreaker and @TimeLimiter on the same method, each timeout is recorded by the breaker as a failure, so a dependency that is merely slow eventually opens the circuit just like one that is down (LatencyAndTimeoutTest):
call 1 -> FALLBACK:k1:TimeoutException [state=CLOSED, took ~500ms]
call 2 -> FALLBACK:k2:TimeoutException [state=CLOSED, took ~500ms]
call 3 -> FALLBACK:k3:TimeoutException [state=CLOSED, took ~500ms]
call 4 -> FALLBACK:k4:TimeoutException [state=OPEN, took ~500ms]
call 5 -> FALLBACK:k5:CallNotPermittedException [state=OPEN, took <100ms]
Four 500 ms timeouts trip it; the fifth call is refused in under 100 ms with CallNotPermittedException. That is the combination you usually want: the timeout turns “slow” into “failed”, and the breaker turns “repeatedly failed” into “stop asking”.
Fingerprint: threads are busy, error rate is zero. If a service is saturated but nothing is throwing, suspect slow calls. Slow-call thresholds on the breaker and a real client timeout are the two fixes; a TimeLimiter alone only improves what callers see.
Going deeper: the production-shaped version, and where the Hystrix timeout went
The tested code above sleeps on a thread; a real client makes an HTTP call. The pattern, a RestClient call wrapped in a future with both annotations, is in PaymentAsyncClient.java (download). It compiles against the module’s classpath but is not run against a server, so treat it as a template; the tested equivalent is guardedLookup in R4jTimeLimiterService.
For synchronous code you do not have to convert everything to futures: set the timeout on the HTTP client, and let the breaker’s slowCallDurationThreshold handle chronic slowness. Spring Framework 7’s own @Retryable(timeout=...) is a retry budget, not a call timeout — the deep-dive linked below measured a single 1500 ms call with timeout=500 running the full 1500 ms.
The configuration that template pairs with, with a longer timeout as you would set for a real payment call (illustrative, not run):
resilience4j:
timelimiter:
instances:
paymentService:
timeoutDuration: 2s
cancelRunningFuture: true
- Resilience4j reference: TimeLimiter.
- Migrating from Hystrix? Its thread timeout maps to
TimeLimiteronly for async methods — see the property table under “Pitfalls” below.
Which failures should count
By default every exception your protected method throws counts as a failure. That includes the ones that are really normal answers: “product not found”, “validation failed”, “insufficient funds”. A burst of those looks, to the breaker, exactly like a dependency falling over, and it will open a circuit in front of a perfectly healthy service.
The fix is ignoreExceptions. The test below runs the same method behind two breakers that differ in one line of YAML (R4jLookupService, config in application.yml), and calls each four times with a product that does not exist:
resilience4j:
circuitbreaker:
instances:
lookupIgnored:
slidingWindowSize: 4
minimumNumberOfCalls: 4
failureRateThreshold: 50
waitDurationInOpenState: 5s
ignoreExceptions:
- com.ankurm.resilience.r4j.ProductNotFoundException
lookupCounted after 4 'not found': state=OPEN failed=4
lookupIgnored after 4 'not found': state=CLOSED failed=0 buffered=0
Same four calls, same exception. The counting breaker saw four failures and opened; the one with ignoreExceptions is closed and, tellingly, has buffered=0 — an ignored exception is recorded as neither a success nor a failure, so it does not even enter the window. Source: IgnoreExceptionsAndRateLimiterTest.
Decide per dependency what an outage looks like. Timeouts, connection failures and 5xx responses are outages; 404s, 409s and validation errors are answers. List the second group underignoreExceptions, or list only the first group underrecordExceptionsas this module’spaymentServicedoes. Retries need the same care: retry only what is transient, and only operations that are safe to repeat.
Going deeper: recordExceptions versus ignoreExceptions
The two lists answer different questions. recordExceptions is an allow-list of what counts as a failure; once you set it, the breaker records only those exceptions as failures and treats other exceptions as successes. ignoreExceptions is a deny-list for the window: matching exceptions count as neither. Use the allow-list when you know the few exceptions that mean “the dependency is unhealthy”; use the deny-list when almost everything should count and you are carving out a few business exceptions. These semantics come from the Resilience4j documentation; this repo executes the ignoreExceptions case above and the recordExceptions configuration used by paymentService in every transcript, but has no test that isolates the “other exceptions count as successes” rule.
- Resilience4j reference: CircuitBreaker configuration.
The rest of the toolbox: retry, rate limiter, bulkhead
The circuit breaker is one of four resilience patterns Resilience4j packages the same way. They all use an annotation, a named instance, and YAML, so once you can read the breaker config you can read these.
Retry repeats a failed call a few times with a growing delay. It is the right answer to a brief glitch and the wrong one to an outage, which is exactly the gap the breaker fills. The tested configuration, from application.yml and R4jRetryService:
resilience4j:
retry:
instances:
inventoryService:
maxAttempts: 3
waitDuration: 200ms
enableExponentialBackoff: true
exponentialBackoffMultiplier: 2
Executed output of this retry, including the counting rule that differs from Spring’s (maxAttempts counts the first call), is in 03d and 03e. Only retry idempotent operations: retrying a POST that timed out after the server processed it is how duplicate payments happen. A production-shaped configuration adds retryExceptions and ignoreExceptions (illustrative values, not run):
resilience4j:
retry:
instances:
inventoryService:
maxAttempts: 3
waitDuration: 500ms
enableExponentialBackoff: true
exponentialBackoffMultiplier: 2 # 500ms, 1s, 2s
retryExceptions:
- java.io.IOException
ignoreExceptions:
- com.example.BusinessValidationException
and the Java around it, a RestClient call, is in InventoryClient.java (download; compiled, not run against a server).
Rate limiter caps calls per time period. Here, three calls per second with no waiting, so the fourth is answered by the fallback immediately (R4jRateLimiterService, test: IgnoreExceptionsAndRateLimiterTest):
resilience4j:
ratelimiter:
instances:
searchApi:
limitForPeriod: 3
limitRefreshPeriod: 1s
timeoutDuration: 0
@RateLimiter(name = "searchApi", fallbackMethod = "tooMany")
public String search(String q) {
return "results:" + q;
}
private String tooMany(String q, RequestNotPermitted ex) {
return "RATE_LIMITED:" + q;
}
call 1 -> results:q1
call 2 -> results:q2
call 3 -> results:q3
call 4 -> RATE_LIMITED:q4
after 1.1s -> results:q5
A production-sized configuration uses the same keys with bigger numbers (illustrative, not run):
resilience4j:
ratelimiter:
instances:
publicApi:
limitForPeriod: 100 # 100 calls
limitRefreshPeriod: 1s # per second
timeoutDuration: 0ms # fail immediately when exhausted
This limiter lives inside one process. With three replicas behind a load balancer your effective limit is three times the configured one, so per-client or cluster-wide limits belong at a gateway. Core Spring Framework 7 has no rate limiter at all.
Bulkhead caps how many calls run at once, so one slow dependency cannot use up every thread. The tested pieces (R4jBulkheadService.java):
resilience4j:
bulkhead:
instances:
slowOp:
maxConcurrentCalls: 2
maxWaitDuration: 100ms
@Bulkhead(name = "slowOp", fallbackMethod = "fallback")
public String slowCall(String id, long sleepMillis) throws InterruptedException {
Thread.sleep(sleepMillis);
return "done:" + id;
}
The reason this still earns a place over core’s @ConcurrencyLimit is the bounded wait. Four concurrent callers against a limit of two, each holding its slot for 300 ms, under three configurations:
| Policy | Outcome |
|---|---|
@ConcurrencyLimit BLOCK | all 4 succeed; total wall time 601ms (queues, no timeout) |
@ConcurrencyLimit REJECT | 2 succeed in ~300ms, 2 rejected in ~0ms (never waits at all) |
Resilience4j @Bulkhead | 2 succeed ~300ms, 2 rejected after ~110-120ms (waited, then gave up) |
(summarised from the three transcripts linked below, each run independently)
Neither of core’s two policies offers that middle option — wait, but only briefly. Full transcripts: 04a, 04b, 04c, from ConcurrencyLimitTest.
Going deeper: the concurrency-limit comparison in full
Core’s BLOCK policy queues without limit and so offers no timeout; its REJECT policy never waits at all. Resilience4j’s maxWaitDuration is the middle option: wait briefly, then give up. If your overflow can safely wait forever, @ConcurrencyLimit is one annotation and one fewer dependency; if it cannot, you need the bounded wait. The numbers above are summarised from three independently run transcripts, whose timings drift slightly between runs, so read them as indicative rather than exact.
- Transcripts: 04a, 04b, 04c, produced by ConcurrencyLimitTest.
- Resilience4j references: Retry, RateLimiter, Bulkhead.
What actually moved into Spring Framework 7 core
Everything so far is Resilience4j. Spring Framework 7 now ships a small resilience API of its own, and anyone upgrading from Boot 3 asks the same question: which of my Resilience4j config can I delete? This section answers it for the parts that moved into core. The exhaustive, call-by-call measurement of core’s annotations is in a companion post, linked in the going-deeper list at the end of this section.
Framework 7 added a real package, org.springframework.resilience, with two annotations: @Retryable (declarative retry with delay, multiplier, jitter, and a max attempt count) and @ConcurrencyLimit (cap concurrent calls to a method, either by queuing or by rejecting). Both are switched on with @EnableResilientMethods — which Spring Boot 4.1 does not add for you automatically. I checked: grepping the listing of spring-boot-autoconfigure-4.1.2.jar for “resilien” returns nothing. No starter, no autoconfiguration class, no default. You add @EnableResilientMethods to a configuration class yourself, or the annotations are inert — no error, no log line, the method just runs unprotected.
One counting gotcha worth flagging even though the linked deep-dive covers it in full: Resilience4j’s @Retry(maxAttempts=3) counts the initial call — three calls total. Core’s @Retryable(maxRetries=3) counts retries after the initial call — four calls total. I verified both independently in this repo’s R4jRetryTest: a permanently-failing downstream gets exactly 3 calls under Resilience4j’s maxAttempts=3 and exactly 4 under core’s maxRetries=3 (03e, 03b). Porting a number from one config to the other by name alone is off by one.
Going deeper: what to read next on the Spring side
- Spring Framework 7’s Built-in Resilience: @Retryable, @ConcurrencyLimit, and What’s Left for Resilience4j — the off-by-one in
maxRetries, the timeout that does not time anything out, jitter that only ever adds. - The code that backs the counting claim: R4jRetryTest and SpringRetryableTest.
- Core’s
@Retryablehas no memory between calls: two consecutive calls against a dead downstream each pay the full retry cost (03b). That is the property from the first section, seen from the other side.
Monitoring with Actuator
management:
endpoints:
web:
exposure:
include: health,metrics,circuitbreakers,circuitbreakerevents
endpoint:
health:
show-details: always
health:
circuitbreakers:
enabled: true
(application.yml) Real output, captured over HTTP against a running embedded server with the breaker actually OPEN — and it corrects a claim the version of this post from Boot 3 days made. GET /actuator/health in this version does not nest per-breaker detail; the circuitBreakers key in the real response body is just this, verbatim (the rest of the response — disk space, SSL chain checks — is environment detail, not shown here):
"circuitBreakers":{"status":"UNKNOWN"}
The per-breaker detail lives at a different endpoint, GET /actuator/circuitbreakers, not nested under health at all. This is the real, complete, unedited response body:
{"circuitBreakers":{"paymentService":{"bufferedCalls":5,"failedCalls":5,"failureRate":"100.0%","failureRateThreshold":"50.0%","notPermittedCalls":1,"slowCallRate":"0.0%","slowCallRateThreshold":"100.0%","slowCalls":0,"slowFailedCalls":0,"state":"OPEN"}}}
Full transcript with both requests side by side: 05-actuator-health-tripped.txt, from ActuatorHealthTest. If your health-check dashboard or alert rule was written against the old nested shape, it silently stopped seeing per-breaker state on this version and nobody told it.
The resilience4j_circuitbreaker_state and resilience4j_circuitbreaker_calls_seconds Micrometer metrics under /actuator/metrics feed straight into the Prometheus & Grafana stack. Core’s annotations register no metrics at all — the linked deep-dive’s companion app has to hand-roll a counter from MethodRetryEvent to get even a basic retry count, and notes that event fires on every failed attempt including ones that will never be retried, so it counts failures, not retries. If you need a dashboard your on-call engineer can actually read at 3am, that gap alone is a reason to keep Resilience4j.
Pitfalls that bite every migration
Hand-assembling spring-aop instead of using spring-boot-starter-aspectj. Covered above — the one most guides, including earlier versions of this one, still get wrong. No error, no log line, annotations silently inert.
A fallback that does not match. As measured above, the fallback must mirror the protected method’s parameters plus a Throwable last. Get it wrong and nothing complains: the original exception just reaches the caller.
Self-invocation. The annotations work via Spring AOP proxies. Calling an annotated method from within the same class bypasses the proxy entirely — no breaker, no retry, no error. This bites core’s @Retryable exactly the same way; see 03c for it caught live. A related trap showed up while writing this post’s tests: a public field read on a proxied bean is not the real field. The bean the container hands you is a generated subclass, so read state through a method.
Counting business exceptions as failures. Shown above: four “not found” results opened a breaker. Use ignoreExceptions.
Believing a timeout stopped the work. Shown above: the call the TimeLimiter abandoned still ran to completion. Set client timeouts.
Copying a config without checking the defaults. minimumNumberOfCalls = 100 and a 60-second open wait are the library defaults; a low-traffic service may never evaluate its breaker.
Reference: Hystrix → Resilience4j property mapping
Still relevant if you’re one of the teams that hasn’t finished migrating off Hystrix yet — it’s been in maintenance mode since 2018 and nothing about Boot 4.1 changes that assessment.
| Hystrix property | Resilience4j equivalent |
|---|---|
| circuitBreaker.requestVolumeThreshold | minimumNumberOfCalls |
| circuitBreaker.errorThresholdPercentage | failureRateThreshold |
| circuitBreaker.sleepWindowInMilliseconds | waitDurationInOpenState |
| execution.isolation.thread.timeoutInMilliseconds | TimeLimiter timeoutDuration (async only!) |
| threadpool.coreSize | Bulkhead maxConcurrentCalls (semaphore) or THREADPOOL bulkhead |
Should you drop Resilience4j? If all you use is retry and a plain concurrency cap, yes — core’s@Retryableand@ConcurrencyLimitdo both, with one fewer dependency. Recount yourmaxAttemptsasmaxRetrieson the way. If you use a circuit breaker, a rate limiter, the Bulkhead’s bounded wait, afallbackMethod, or the Actuator/Micrometer dashboards — and most services that reach for Resilience4j in the first place do — keep it. Don’t combine core’s@Retryablewith Resilience4j’s@CircuitBreakeron the same method without excludingCallNotPermittedExceptionfrom the retry: the linked deep-dive measured the retry wrapping the open breaker and burning three seconds on an answer it already had.
Frequently Asked Questions
Do I still need spring-boot-starter-aop? That artifact ID was renamed to spring-boot-starter-aspectj starting at Boot 4.0.0-M3 — the old name’s last published version is a Boot 4.0 milestone, 4.0.0-M2. Use spring-boot-starter-aspectj, which bundles spring-aop and aspectjweaver for you. See above.
Can I run Resilience4j and core’s @Retryable in the same service? Yes, on different methods, with no conflict. On the same method alongside @CircuitBreaker, be careful — see the callout above.
Does Resilience4j work with virtual threads? Yes. Semaphore-based bulkheads and circuit breakers are agnostic to the carrier thread; avoid the THREADPOOL bulkhead with virtual threads since it defeats their purpose.
AI Prompts for Resilience4j on Boot 4.1
Audit a Boot 4 Upgrade for the AOP Trap
Here is my pom.xml and my Resilience4j-annotated service classes: [paste here]. Check whether spring-boot-starter-aop is present (it was renamed to spring-boot-starter-aspectj starting at Boot 4.0.0-M3) and whether the renamed starter or an equivalent aspectjweaver dependency is actually on the classpath given my Resilience4j usage. Flag anything that would silently disable the annotations.
What it does: Catches the exact silent failure this post is about before it reaches production.
Decide What to Keep
Given these Resilience4j-annotated methods: [paste here], classify each as (a) replaceable by core Spring Framework 7’s @Retryable/@ConcurrencyLimit with no loss of behaviour, or (b) dependent on a circuit breaker, rate limiter, bounded-wait bulkhead, fallback method, or metrics that only Resilience4j provides.
What it does: Turns the “should you even do this” callout above into a per-method audit of a real codebase.
Convert Hystrix Class
Convert this Hystrix-annotated class to Resilience4j 2.4.0 on Spring Boot 4.1: [paste class here]. Map every hystrix.command property to the resilience4j YAML equivalent, fix fallback signatures to include Throwable, and flag any timeout behaviour that changes.
What it does: Mechanical conversion plus surfacing the semantic timeout/isolation differences explicitly.
Write Breaker Contract Tests
Write JUnit 5 tests for this Resilience4j-protected service: [paste here]. Cover the breaker tripping after the configured failures, the downstream call count staying flat while OPEN, fallback invocation, half-open recovery, and ignored exceptions not affecting the failure rate. Use CircuitBreakerRegistry directly to assert state transitions.
What it does: Generates the state-transition tests most teams skip until the breaker misbehaves in production — the same shape as this repo’s own CircuitBreakerTripAndRecoverTest.
Further reading
- resilience4j-circuit-breaker — companion module (inside the spring-boot-demo container repo): every test and the services behind each console block above. Run
mvn test; new transcripts land intarget/transcripts/. - Spring Framework 7’s Built-in Resilience: @Retryable, @ConcurrencyLimit, and What’s Left for Resilience4j — the exhaustive, invocation-by-invocation companion piece
- Monitoring Spring Boot Microservices with Prometheus & Grafana
- Spring Cloud Netflix to Modern Alternatives: Complete Migration Guide
- Downloads: InventoryClient.java (retry with RestClient), PaymentAsyncClient.java (TimeLimiter + CircuitBreaker with RestClient)
- Resilience4j official documentation
No Comments yet!