Resilience4j in Spring Boot: A Timeout, One Retry, a Circuit Breaker, a Bulkhead and a Fallback, Measured Against a Slow Dependency
Toxiproxy adds 3,000 ms to billing, and a ticket list that never calls billing gets a p95 of 8,931 ms because all 10 threads are waiting. A 500 ms timeout, a bulkhead of three, a breaker over ten calls and one retry bring it to 6 ms, with 2,292 plan calls answered by the fallback. Remove the delay and the breaker closes by itself.
What you will learn
- Show how one slow dependency fills every request thread, using Toxiproxy and k6
- Set a read timeout on RestClient so a thread is never held forever
- Configure a Resilience4j circuit breaker, bulkhead and retry in plain Java and wrap one call in the right order
- Return a planned fallback and watch the breaker close again on its own
Before you start
- Spring Boot REST controllers and RestClient
- Docker Compose basics
A slow dependency can take down features that never call it. This article shows that happening on a small Spring Boot desk called FuseBox, then fixes it with a timeout, a circuit breaker, a bulkhead, one retry and a fallback from Resilience4j. Toxiproxy sits in front of the billing service so the slowness repeats on cue. The same patterns for model calls, with retry budgets, are in retry budgets and circuit breakers for LLM calls.
One slow call takes every thread
The desk has 10 request threads (server.tomcat.threads.max: 10) and two features that matter here. /api/tickets calls nothing. /api/plan calls billing. (A third endpoint, /api/breaker, reports the breaker state.)
@GetMapping("/tickets")
Map<String, Object> tickets() {
return Map.of("open", 3); // no dependency at all
}
@GetMapping("/plan")
Map<String, Object> plan() {
return billing.plan(); // depends on billing
}
Billing is healthy, and the desk reaches it through Toxiproxy. One call to the proxy adds a latency toxic of 3,000 ms:
$ curl -s localhost:18320/api/plan
{"plan":"pro"}
$ curl -s -X POST localhost:18474/proxies/billing/toxics -o /dev/null -w "%{http_code}" -d '{"name":"slow","type":"latency","attributes":{"latency":3000}}'
200
With protection off, the client waits as long as billing takes:
Map<String, Object> plan() {
if (!settings.protect()) {
return fetch(); // waits as long as billing takes
}
...
}
k6 then sends 30 plan clients and 5 ticket clients for 8 seconds:
$ docker compose --profile load run --rm --no-deps k6
tickets 100% ok p95 8931 ms
plan live 50 fallback 0 failed 0
Each plan call holds a thread for three seconds, so all ten fill up, and the ticket list waits for a free one. Ten threads over three seconds is about three plan calls a second. The ticket list never calls billing, yet its p95 is almost nine seconds.
Four tools, a few numbers each
Think of a fuse box. A short in the kitchen trips the kitchen breaker and the lights stay on. The fuse box does not prevent the short. It stops it spreading. FuseBox builds its protection as plain Resilience4j objects:
@Configuration
@ConditionalOnProperty(name = "fusebox.role", havingValue = "desk")
class Resilience {
@Bean
CircuitBreaker billingBreaker() {
return CircuitBreaker.of("billing", CircuitBreakerConfig.custom()
.slidingWindowSize(10)
.minimumNumberOfCalls(5)
.failureRateThreshold(50)
.waitDurationInOpenState(Duration.ofSeconds(10))
.permittedNumberOfCallsInHalfOpenState(3)
.build());
}
@Bean
Bulkhead billingBulkhead() {
return Bulkhead.of("billing", BulkheadConfig.custom()
.maxConcurrentCalls(3)
.maxWaitDuration(Duration.ZERO)
.build());
}
@Bean
Retry billingRetry() {
return Retry.of("billing", RetryConfig.custom()
.maxAttempts(2)
.waitDuration(Duration.ofMillis(100))
.ignoreExceptions(CallNotPermittedException.class,
BulkheadFullException.class)
.build());
}
}
- The breaker watches the last ten calls. When half of them fail, it opens and calls fail at once. After ten seconds it goes half-open and lets three trial calls through. If they succeed, it closes.
- The bulkhead lets billing use three threads at a time, with no waiting. A fourth call is refused at once, so the other seven threads stay free for tickets.
- The retry is one more attempt after 100 ms. It ignores a refused call from the breaker or bulkhead, since retrying those only adds load.
Be careful with retries. Thirty callers with one try each is 30 calls. With two tries each it is 60, on a service that is already struggling. A timeout protects the caller, and a retry can hurt the service you are calling. Keep retries few and spaced out, and put them behind a breaker.
Wrap the call, and plan the fallback
BillingClient(FuseSettings settings, CircuitBreaker breaker,
Bulkhead bulkhead, Retry retry) {
var factory = new SimpleClientHttpRequestFactory();
if (settings.protect()) {
factory.setReadTimeout(Duration.ofMillis(500)); // never wait forever
}
this.http = RestClient.builder().requestFactory(factory)
.baseUrl(settings.billingUrl()).build();
...
}
Map<String, Object> plan() {
if (!settings.protect()) {
return fetch(); // waits as long as billing takes
}
Supplier<Map<String, Object>> call =
Bulkhead.decorateSupplier(bulkhead, this::fetch);
call = CircuitBreaker.decorateSupplier(breaker, call);
call = Retry.decorateSupplier(retry, call);
try {
return call.get();
} catch (Exception failed) {
return Map.of("plan", "unknown", "degraded", true); // the fallback
}
}
The timeout comes first: half a second, then the thread is free. The call is then wrapped three times, with the bulkhead inside, the breaker around it and the retry outside. Any failure ends in the fallback, a smaller answer that still says something true: the plan is unknown right now.
$ PROTECT=true docker compose up -d desk
$ docker compose --profile load run --rm --no-deps k6
tickets 100% ok p95 6 ms
plan live 0 fallback 2292 failed 0
$ curl -s localhost:18320/api/breaker
{"state":"OPEN"}
$ curl -s localhost:18320/api/plan
{"degraded":true,"plan":"unknown"}
Same spike. The ticket list p95 drops from 8,931 ms to 6 ms, 2,292 plan calls got the fallback, and none failed outright. The breaker is open, so a plan call returns at once.
When billing is back, the breaker closes
$ curl -s -X DELETE localhost:18474/proxies/billing/toxics/slow
$ sleep 11; for i in 1 2 3; do curl -s localhost:18320/api/plan; echo; done; curl -s localhost:18320/api/breaker
{"plan":"pro"}
{"plan":"pro"}
{"plan":"pro"}
{"state":"CLOSED"}
After the ten-second wait, the breaker lets three trial calls through. They succeed, so it closes. No one had to restart anything.
Recap
| Tool | Setting here | What it protects |
|---|---|---|
| Timeout | 500 ms read timeout | The caller's thread |
| Retry | 2 attempts, 100 ms apart | Against a short blip, at the cost of extra load |
| Circuit breaker | Window 10, 50%, open 10 s, 3 trials | Both sides: fails fast while billing is down |
| Bulkhead | 3 concurrent calls, no wait | The other 7 threads, for features that do not need billing |
| Fallback | plan: unknown, degraded: true | The user, who still gets an answer |
Try it yourself: set maxAttempts(10) and drop the breaker. Every slow call becomes ten, and the struggling service gets ten times the load. The gates that protect a service from its own callers are covered in rate limiting, backpressure and load shedding.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)