resilience4j-circuit-breaker: add state-transition, slow-call, TimeLimiter, ignoreExceptions and RateLimiter tests on Boot 4.1.2

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b74uRrp2Tiu2PngyuY
This commit is contained in:
2026-11-12 10:54:24 +05:30
co-authored by Claude Sonnet 5.5
parent ae696369ba
commit dc8a5a2c7c
12 changed files with 406 additions and 5 deletions
+9 -3
View File
@@ -17,9 +17,9 @@ to stay independently reproducible from its own module.
| Component | Version | Notes | | Component | Version | Notes |
|---|---|---| |---|---|---|
| JDK | 25 (Temurin 25.0.4.1+1) | latest LTS | | JDK | 25 (Temurin 25.0.5+8) | latest LTS |
| Spring Boot | 4.1.1 | latest GA at time of writing; 4.2.0-M1 exists but is a milestone | | Spring Boot | 4.1.2 | latest GA at time of writing; 4.2.0-RC2 exists but is a release candidate |
| Spring Framework | 7.0.9 | latest GA; 7.1.0-M1 exists but is a milestone | | Spring Framework | 7.0.10 | managed by Boot 4.1.2 |
| Resilience4j | 2.4.0 (`resilience4j-spring-boot4`) | depends internally on `resilience4j-spring6`, not a "spring7" module — see [docs/01](docs/01-two-resilience-stacks.md) | | Resilience4j | 2.4.0 (`resilience4j-spring-boot4`) | depends internally on `resilience4j-spring6`, not a "spring7" module — see [docs/01](docs/01-two-resilience-stacks.md) |
## Quickstart ## Quickstart
@@ -47,6 +47,12 @@ local cache); `-o` works for subsequent builds.
| `@ConcurrencyLimit` REJECT policy | same | same | [`04b`](docs/output/04b-concurrencylimit-reject.txt) | | `@ConcurrencyLimit` REJECT policy | same | same | [`04b`](docs/output/04b-concurrencylimit-reject.txt) |
| Resilience4j `@Bulkhead` (bounded wait) for comparison | [`R4jBulkheadService`](src/main/java/com/ankurm/resilience/r4j/R4jBulkheadService.java) | same | [`04c`](docs/output/04c-r4j-bulkhead-comparison.txt) | | Resilience4j `@Bulkhead` (bounded wait) for comparison | [`R4jBulkheadService`](src/main/java/com/ankurm/resilience/r4j/R4jBulkheadService.java) | same | [`04c`](docs/output/04c-r4j-bulkhead-comparison.txt) |
| Real `/actuator/health` + `/actuator/circuitbreakers` with a breaker OPEN | [`R4jPaymentService`](src/main/java/com/ankurm/resilience/r4j/R4jPaymentService.java) | [`ActuatorHealthTest`](src/test/java/com/ankurm/resilience/r4j/ActuatorHealthTest.java) | [`05`](docs/output/05-actuator-health-tripped.txt) | | Real `/actuator/health` + `/actuator/circuitbreakers` with a breaker OPEN | [`R4jPaymentService`](src/main/java/com/ankurm/resilience/r4j/R4jPaymentService.java) | [`ActuatorHealthTest`](src/test/java/com/ankurm/resilience/r4j/ActuatorHealthTest.java) | [`05`](docs/output/05-actuator-health-tripped.txt) |
| State transitions through the event publisher (`CLOSED -> OPEN -> HALF_OPEN -> OPEN`) | [`R4jPaymentService`](src/main/java/com/ankurm/resilience/r4j/R4jPaymentService.java) | [`StateTransitionsTest`](src/test/java/com/ankurm/resilience/r4j/StateTransitionsTest.java) | printed by the test (`-Dtranscript.dir=<dir>`) |
| Testing without sleeping: force the breaker state | same | same | same |
| Slow-call rate opens the breaker with zero failures | [`R4jSlowCallService`](src/main/java/com/ankurm/resilience/r4j/R4jSlowCallService.java) | [`LatencyAndTimeoutTest`](src/test/java/com/ankurm/resilience/r4j/LatencyAndTimeoutTest.java) | same |
| `@TimeLimiter`, alone and combined with `@CircuitBreaker` | [`R4jTimeLimiterService`](src/main/java/com/ankurm/resilience/r4j/R4jTimeLimiterService.java) | same | same |
| `ignoreExceptions` for business errors | [`R4jLookupService`](src/main/java/com/ankurm/resilience/r4j/R4jLookupService.java) | [`IgnoreExceptionsAndRateLimiterTest`](src/test/java/com/ankurm/resilience/r4j/IgnoreExceptionsAndRateLimiterTest.java) | same |
| `@RateLimiter` | [`R4jRateLimiterService`](src/main/java/com/ankurm/resilience/r4j/R4jRateLimiterService.java) | same | same |
## Endpoints (from `scripts/run.sh`) ## Endpoints (from `scripts/run.sh`)
+1 -1
View File
@@ -7,7 +7,7 @@
<parent> <parent>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId> <artifactId>spring-boot-starter-parent</artifactId>
<version>4.1.1</version> <version>4.1.2</version>
<relativePath/> <relativePath/>
</parent> </parent>
@@ -0,0 +1,11 @@
package com.ankurm.resilience.r4j;
/**
* A business outcome ("no such product"), not a sign the dependency is unhealthy.
* The breaker instance lookupIgnored lists it under ignoreExceptions.
*/
public class ProductNotFoundException extends RuntimeException {
public ProductNotFoundException(String id) {
super("no product " + id);
}
}
@@ -0,0 +1,23 @@
package com.ankurm.resilience.r4j;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import org.springframework.stereotype.Service;
/**
* The same "not found" method behind two breakers that differ in one line of YAML:
* lookupCounted counts ProductNotFoundException as a failure (the default),
* lookupIgnored lists it under ignoreExceptions so it counts as neither success nor failure.
*/
@Service
public class R4jLookupService {
@CircuitBreaker(name = "lookupCounted")
public String findCounted(String id) {
throw new ProductNotFoundException(id);
}
@CircuitBreaker(name = "lookupIgnored")
public String findIgnored(String id) {
throw new ProductNotFoundException(id);
}
}
@@ -0,0 +1,22 @@
package com.ankurm.resilience.r4j;
import io.github.resilience4j.ratelimiter.RequestNotPermitted;
import io.github.resilience4j.ratelimiter.annotation.RateLimiter;
import org.springframework.stereotype.Service;
/**
* In-process rate limiter: 3 calls per 1s period, no waiting (timeoutDuration=0).
* Config: resilience4j.ratelimiter.instances.searchApi.
*/
@Service
public class R4jRateLimiterService {
@RateLimiter(name = "searchApi", fallbackMethod = "tooMany")
public String search(String q) {
return "results:" + q;
}
private String tooMany(String q, RequestNotPermitted ex) {
return "RATE_LIMITED:" + q;
}
}
@@ -0,0 +1,23 @@
package com.ankurm.resilience.r4j;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import org.springframework.stereotype.Service;
/**
* A call that always SUCCEEDS but can be slow. The breaker "slowBreaker" has
* slowCallDurationThreshold=200ms and slowCallRateThreshold=50, so it opens on latency alone,
* with a failure rate of zero. Config: resilience4j.circuitbreaker.instances.slowBreaker.
*/
@Service
public class R4jSlowCallService {
@CircuitBreaker(name = "slowBreaker", fallbackMethod = "fallback")
public String call(String id, long sleepMillis) throws InterruptedException {
Thread.sleep(sleepMillis);
return "ok:" + id;
}
private String fallback(String id, long sleepMillis, Throwable ex) {
return "FALLBACK:" + id + ":" + ex.getClass().getSimpleName();
}
}
@@ -0,0 +1,51 @@
package com.ankurm.resilience.r4j;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import io.github.resilience4j.timelimiter.annotation.TimeLimiter;
import org.springframework.stereotype.Service;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeoutException;
/**
* Resilience4j's TimeLimiter. It only works on methods that return a CompletableFuture
* (or a reactive type) because it has to be able to stop waiting for something that is still
* running on another thread. Config: resilience4j.timelimiter.instances.slowLookup.
*/
@Service
public class R4jTimeLimiterService {
/** TimeLimiter alone: a call slower than 500ms is answered by the fallback. */
@TimeLimiter(name = "slowLookup", fallbackMethod = "timedOut")
public CompletableFuture<String> lookup(String id, long sleepMillis) {
return CompletableFuture.supplyAsync(() -> slow(id, sleepMillis));
}
/**
* TimeLimiter plus CircuitBreaker: every timeout is recorded as a failure by the breaker,
* so a dependency that is merely slow will eventually open the circuit.
*/
@CircuitBreaker(name = "timeoutBreaker", fallbackMethod = "breakerFallback")
@TimeLimiter(name = "slowLookup")
public CompletableFuture<String> guardedLookup(String id, long sleepMillis) {
return CompletableFuture.supplyAsync(() -> slow(id, sleepMillis));
}
private String slow(String id, long sleepMillis) {
try {
Thread.sleep(sleepMillis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException("interrupted", e);
}
return "found:" + id;
}
private CompletableFuture<String> timedOut(String id, long sleepMillis, TimeoutException ex) {
return CompletableFuture.completedFuture("TIMED_OUT:" + id);
}
private CompletableFuture<String> breakerFallback(String id, long sleepMillis, Throwable ex) {
return CompletableFuture.completedFuture("FALLBACK:" + id + ":" + ex.getClass().getSimpleName());
}
}
@@ -30,6 +30,46 @@ resilience4j:
automaticTransitionFromOpenToHalfOpenEnabled: true automaticTransitionFromOpenToHalfOpenEnabled: true
recordExceptions: recordExceptions:
- com.ankurm.resilience.FlakyDownstream$DownstreamUnavailableException - com.ankurm.resilience.FlakyDownstream$DownstreamUnavailableException
# Opens on latency alone: every call succeeds, but 2 of 4 take longer than 200ms.
slowBreaker:
slidingWindowType: COUNT_BASED
slidingWindowSize: 4
minimumNumberOfCalls: 4
failureRateThreshold: 50
slowCallDurationThreshold: 200ms
slowCallRateThreshold: 50
waitDurationInOpenState: 5s
# Sits behind @TimeLimiter: each timeout is one recorded failure.
timeoutBreaker:
slidingWindowType: COUNT_BASED
slidingWindowSize: 4
minimumNumberOfCalls: 4
failureRateThreshold: 50
waitDurationInOpenState: 5s
# Identical pair; the only difference is ignoreExceptions.
lookupCounted:
slidingWindowSize: 4
minimumNumberOfCalls: 4
failureRateThreshold: 50
waitDurationInOpenState: 5s
lookupIgnored:
slidingWindowSize: 4
minimumNumberOfCalls: 4
failureRateThreshold: 50
waitDurationInOpenState: 5s
ignoreExceptions:
- com.ankurm.resilience.r4j.ProductNotFoundException
timelimiter:
instances:
slowLookup:
timeoutDuration: 500ms
cancelRunningFuture: true
ratelimiter:
instances:
searchApi:
limitForPeriod: 3
limitRefreshPeriod: 1s
timeoutDuration: 0
bulkhead: bulkhead:
instances: instances:
slowOp: slowOp:
@@ -18,7 +18,7 @@ public final class Transcript {
private final Path outFile; private final Path outFile;
private Transcript(String fileName) { private Transcript(String fileName) {
this.outFile = Paths.get("docs/output", fileName); this.outFile = Paths.get(System.getProperty("transcript.dir", "docs/output"), fileName);
} }
public static Transcript start(String fileName, String header) { public static Transcript start(String fileName, String header) {
@@ -0,0 +1,55 @@
package com.ankurm.resilience.r4j;
import com.ankurm.resilience.Transcript;
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import static org.assertj.core.api.Assertions.assertThat;
/** Output: 11-ignore-exceptions.txt, 12-rate-limiter.txt. */
@SpringBootTest
@DirtiesContext
class IgnoreExceptionsAndRateLimiterTest {
@Autowired R4jLookupService lookup;
@Autowired R4jRateLimiterService limiter;
@Autowired CircuitBreakerRegistry registry;
@Test
void businessExceptionsShouldNotTripTheBreaker() {
Transcript t = Transcript.start("11-ignore-exceptions.txt",
"Same exception, two breakers, one line of YAML apart");
CircuitBreaker counted = registry.circuitBreaker("lookupCounted");
CircuitBreaker ignored = registry.circuitBreaker("lookupIgnored");
for (int i = 1; i <= 4; i++) {
try { lookup.findCounted("p" + i); } catch (ProductNotFoundException ignoredEx) { }
try { lookup.findIgnored("p" + i); } catch (ProductNotFoundException ignoredEx) { }
}
t.line("lookupCounted after 4 'not found': state=" + counted.getState()
+ " failed=" + counted.getMetrics().getNumberOfFailedCalls());
t.line("lookupIgnored after 4 'not found': state=" + ignored.getState()
+ " failed=" + ignored.getMetrics().getNumberOfFailedCalls()
+ " buffered=" + ignored.getMetrics().getNumberOfBufferedCalls());
assertThat(counted.getState()).isEqualTo(CircuitBreaker.State.OPEN);
assertThat(ignored.getState()).isEqualTo(CircuitBreaker.State.CLOSED);
assertThat(ignored.getMetrics().getNumberOfBufferedCalls()).isZero();
t.save();
}
@Test
void rateLimiterRejectsTheFourthCallInAOneSecondWindow() throws InterruptedException {
Transcript t = Transcript.start("12-rate-limiter.txt", "limitForPeriod=3, limitRefreshPeriod=1s");
for (int i = 1; i <= 4; i++) {
t.line("call " + i + " -> " + limiter.search("q" + i));
}
Thread.sleep(1100);
String after = limiter.search("q5");
t.line("after 1.1s -> " + after);
assertThat(after).startsWith("results:");
t.save();
}
}
@@ -0,0 +1,75 @@
package com.ankurm.resilience.r4j;
import com.ankurm.resilience.Transcript;
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Slow is a failure mode too. Output: 08-slow-call-rate.txt, 09-timelimiter.txt,
* 10-timelimiter-plus-breaker.txt.
*/
@SpringBootTest
@DirtiesContext
class LatencyAndTimeoutTest {
@Autowired R4jSlowCallService slow;
@Autowired R4jTimeLimiterService timeLimited;
@Autowired CircuitBreakerRegistry registry;
@Test
void breakerOpensOnLatencyAloneWithZeroFailures() throws Exception {
Transcript t = Transcript.start("08-slow-call-rate.txt",
"slowCallDurationThreshold=200ms, slowCallRateThreshold=50: opens with zero failures");
CircuitBreaker cb = registry.circuitBreaker("slowBreaker");
long[] sleeps = {10, 400, 10, 400};
for (int i = 0; i < sleeps.length; i++) {
String r = slow.call("c" + (i + 1), sleeps[i]);
t.line("call " + (i + 1) + " (" + sleeps[i] + "ms) -> " + r + " [state=" + cb.getState() + "]");
}
var m = cb.getMetrics();
t.line("failureRate=" + m.getFailureRate() + "% slowCallRate=" + m.getSlowCallRate()
+ "% numberOfFailedCalls=" + m.getNumberOfFailedCalls()
+ " numberOfSlowCalls=" + m.getNumberOfSlowCalls());
t.line("call 5 -> " + slow.call("c5", 10));
assertThat(m.getNumberOfFailedCalls()).isZero();
assertThat(cb.getState()).isEqualTo(CircuitBreaker.State.OPEN);
t.save();
}
@Test
void timeLimiterAnswersSlowCallsWithTheFallback() throws Exception {
Transcript t = Transcript.start("09-timelimiter.txt", "@TimeLimiter timeoutDuration=500ms");
long s1 = System.nanoTime();
String fast = timeLimited.lookup("a", 100).get();
t.line("100ms call -> " + fast + " (" + (System.nanoTime() - s1) / 1_000_000 / 100 * 100 + "ms bucket)");
long s2 = System.nanoTime();
String late = timeLimited.lookup("b", 2000).get();
long ms = (System.nanoTime() - s2) / 1_000_000;
t.line("2000ms call -> " + late + " (caller waited about 500ms, not 2000ms: " + (ms < 1000) + ")");
assertThat(fast).isEqualTo("found:a");
assertThat(late).isEqualTo("TIMED_OUT:b");
assertThat(ms).isBetween(450L, 1000L);
t.save();
}
@Test
void timeoutsCountAsFailuresAndEventuallyOpenTheBreaker() throws Exception {
Transcript t = Transcript.start("10-timelimiter-plus-breaker.txt",
"@CircuitBreaker + @TimeLimiter: timeouts are recorded as failures");
CircuitBreaker cb = registry.circuitBreaker("timeoutBreaker");
for (int i = 1; i <= 5; i++) {
long s = System.nanoTime();
String r = timeLimited.guardedLookup("k" + i, 2000).get();
t.line("call " + i + " -> " + r + " [state=" + cb.getState() + ", took "
+ ((System.nanoTime() - s) / 1_000_000 < 100 ? "<100ms" : "~500ms") + "]");
}
assertThat(cb.getState()).isEqualTo(CircuitBreaker.State.OPEN);
t.save();
}
}
@@ -0,0 +1,95 @@
package com.ankurm.resilience.r4j;
import com.ankurm.resilience.FlakyDownstream;
import com.ankurm.resilience.Transcript;
import io.github.resilience4j.circuitbreaker.CircuitBreaker;
import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import java.util.ArrayList;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Every state transition the post draws, observed through the breaker's own event stream
* instead of guessed from return values. Output: 06-state-transitions.txt, 07-fast-state-tests.txt.
*/
@SpringBootTest
@DirtiesContext
class StateTransitionsTest {
@Autowired R4jPaymentService service;
@Autowired FlakyDownstream downstream;
@Autowired CircuitBreakerRegistry registry;
@Test
void halfOpenFailureSendsTheBreakerStraightBackToOpen() throws InterruptedException {
Transcript t = Transcript.start("06-state-transitions.txt",
"State transitions seen through the event publisher (downstream stays dead)");
CircuitBreaker cb = registry.circuitBreaker("paymentService");
cb.reset();
List<String> transitions = new ArrayList<>();
cb.getEventPublisher().onStateTransition(e ->
transitions.add(e.getStateTransition().getFromState() + " -> " + e.getStateTransition().getToState()));
downstream.configure(Integer.MAX_VALUE);
for (int i = 1; i <= 5; i++) service.pay("order-" + i);
t.line("after 5 failing calls: state=" + cb.getState());
assertThat(cb.getState()).isEqualTo(CircuitBreaker.State.OPEN);
int callsBefore = downstream.callsSoFar();
Thread.sleep(2200); // waitDurationInOpenState=2s, automatic transition enabled
t.line("after waiting 2.2s (no call): state=" + cb.getState());
assertThat(cb.getState()).isEqualTo(CircuitBreaker.State.HALF_OPEN);
service.pay("probe-1");
service.pay("probe-2");
t.line("after 2 failing half-open probes: state=" + cb.getState()
+ " (downstream calls during probing: " + (downstream.callsSoFar() - callsBefore) + ")");
assertThat(cb.getState()).isEqualTo(CircuitBreaker.State.OPEN);
t.blank();
t.line("transitions recorded, in order:");
transitions.forEach(s -> t.line(" " + s));
assertThat(transitions).containsExactly(
"CLOSED -> OPEN", "OPEN -> HALF_OPEN", "HALF_OPEN -> OPEN");
t.save();
}
@Test
void youCanTestFallbackWithoutSleepingByForcingTheState() {
Transcript t = Transcript.start("07-fast-state-tests.txt",
"Testing without sleeping: force the state, assert the behaviour");
CircuitBreaker cb = registry.circuitBreaker("paymentService");
cb.reset();
downstream.configure(0); // healthy downstream
long start = System.nanoTime();
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"));
cb.transitionToClosedState();
long ms = (System.nanoTime() - start) / 1_000_000;
t.line("elapsed under 1s, no Thread.sleep: " + (ms < 1000));
assertThat(ms).isLessThan(1000);
t.save();
}
}