Isolating external API failures with Resilience4j in Spring
Isolate external API outages using Resilience4j CircuitBreaker and Bulkhead in Spring Boot, covering sliding windows, aspect ordering, and Actuator metrics.
Timeouts alone don’t stop your service from repeatedly hitting an external API that is already down. This post walks through how I added Resilience4j’s CircuitBreaker to fail fast on repeated errors and Bulkhead to cap concurrent calls in a Spring Boot service.
Tested with Spring Boot 3.5.3, Java 21, Kotlin 2.1.21, and Resilience4j 2.3.0 (
resilience4j-spring-boot3).
Background
After a slow university notice board API stalled our entire club registration service, I first fixed RestClient timeouts and connection pool limits. That kept the server alive, but a second problem showed up the next time the notice API went completely offline: every incoming request still waited the full 3-second read timeout before failing, tying up Tomcat worker threads the entire time.
When an upstream service is clearly down, waiting three seconds on every request wastes threads. A CircuitBreaker detects a high failure or slow-call rate and short-circuits subsequent calls immediately with a fallback response. Pairing it with a Bulkhead caps how many concurrent calls can target that upstream API at once so it can never starve other endpoints.
CircuitBreaker state transitions and internals
flowchart TD
C["CLOSED (normal calls)"] -->|"Failure or slow-call threshold exceeded"| O["OPEN (fail fast)"]
O -->|"wait-duration elapsed"| H["HALF_OPEN (probe calls)"]
H -->|"Probe calls succeed"| C
H -->|"Probe calls fail"| O
Under the hood, CircuitBreakerStateMachine stores the current state in an AtomicReference and checks acquirePermission() before every call. In the OPEN state, it throws CallNotPermittedException right away without touching the network. Once a call completes, the outcome is recorded in a sliding window and the failure thresholds are recalculated.
Resilience4j offers two sliding window types. COUNT_BASED tracks the last N calls in a ring buffer (FixedSizeSlidingWindowMetrics), subtracting the oldest entry and adding the newest in O(1) time. TIME_BASED accumulates partial aggregates across N one-second buckets (SlidingTimeWindowMetrics). Because our club service has bursty traffic with quiet periods in between, time-based windows often carry too few samples to react predictably, so I picked a COUNT_BASED window of 20 calls.
Slow calls are just as dangerous as outright errors. Any call exceeding slow-call-duration-threshold counts as slow even if it returns HTTP 200, and exceeding slow-call-rate-threshold trips the circuit. Set slow-call-duration-threshold shorter than your read timeout so the breaker spots degradation before requests start timing out.
Semaphore vs. ThreadPool Bulkhead
| Aspect | Semaphore Bulkhead | ThreadPool Bulkhead |
|---|---|---|
| Execution model | Runs on the caller thread, limits concurrent entries | Runs on a dedicated thread pool |
| Return type | Any return type | Requires CompletableFuture |
| Defaults | 25 concurrent calls, 0 wait | Core-sized pool, queue capacity 100 |
| Best fit | Synchronous RestClient calls | Async composition or enforcing a hard total timeout |
For a synchronous Spring MVC service, a semaphore bulkhead is enough. A thread pool bulkhead frees the caller thread, but you pay for context switching and rewriting your call chain around CompletableFuture.
There are clear cases when not to use these patterns. If an endpoint only sees a few requests per minute, it may never reach minimum-number-of-calls to trip the circuit—timeouts and limited retries are simpler. Never attach a “pretend it succeeded” fallback to critical writes like payments, where returning a synthetic success corrupts state. Wrapping internal database queries in a circuit breaker is usually overkill as well.
Aspect ordering and configuration
When you stack Resilience4j annotations on the same method, the default execution order from outermost to innermost is:
Retry → CircuitBreaker → RateLimiter → TimeLimiter → Bulkhead → target method
Because Retry wraps CircuitBreaker from the outside, every retry attempt is recorded as a separate call by the circuit breaker. You can adjust the order via properties like resilience4j.retry.retry-aspect-order (higher values run earlier). Note that @TimeLimiter only works on CompletableFuture or reactive return types; for synchronous calls, your HTTP client’s read timeout handles the per-call bound.
1
2
3
4
5
6
7
8
// build.gradle.kts
dependencies {
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.springframework.boot:spring-boot-starter-aop")
implementation("org.springframework.boot:spring-boot-starter-actuator")
implementation("io.github.resilience4j:resilience4j-spring-boot3:2.3.0")
runtimeOnly("io.micrometer:micrometer-registry-prometheus")
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# src/main/resources/application.yml
resilience4j:
circuitbreaker:
instances:
noticeApi:
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: 60
wait-duration-in-open-state: 30s
permitted-number-of-calls-in-half-open-state: 3
automatic-transition-from-open-to-half-open-enabled: true
register-health-indicator: true
record-exceptions:
- org.springframework.web.client.ResourceAccessException
- org.springframework.web.client.HttpServerErrorException
ignore-exceptions:
- io.github.resilience4j.bulkhead.BulkheadFullException
bulkhead:
instances:
noticeApi:
max-concurrent-calls: 10
max-wait-duration: 0
retry:
instances:
noticeApi:
max-attempts: 2
wait-duration: 300ms
retry-exceptions:
- org.springframework.web.client.ResourceAccessException
management:
health:
circuitbreakers:
enabled: true
endpoint:
health:
show-details: always
endpoints:
web:
exposure:
include: health,metrics,prometheus,circuitbreakers,circuitbreakerevents
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// src/main/kotlin/com/example/club/notice/NoticeQueryService.kt
package com.example.club.notice
import io.github.resilience4j.bulkhead.annotation.Bulkhead
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker
import io.github.resilience4j.retry.annotation.Retry
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
@Service
class NoticeQueryService(
private val noticeApiClient: NoticeApiClient,
private val noticeCache: NoticeCache,
) {
private val log = LoggerFactory.getLogger(javaClass)
@Retry(name = "noticeApi", fallbackMethod = "fallback")
@CircuitBreaker(name = "noticeApi")
@Bulkhead(name = "noticeApi", type = Bulkhead.Type.SEMAPHORE)
fun getNotices(): List<NoticeResponse> {
val notices = noticeApiClient.fetchNotices()
noticeCache.save(notices)
return notices
}
// Must live in the same class with the same parameters plus a trailing exception parameter
fun fallback(e: Exception): List<NoticeResponse> {
log.warn("Using fallback response for notice API: {}", e.javaClass.simpleName)
return noticeCache.lastKnown()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// src/main/kotlin/com/example/club/notice/NoticeCache.kt
package com.example.club.notice
import org.springframework.stereotype.Component
import java.util.concurrent.atomic.AtomicReference
@Component
class NoticeCache {
private val latest = AtomicReference<List<NoticeResponse>>(emptyList())
fun save(notices: List<NoticeResponse>) = latest.set(notices)
fun lastKnown(): List<NoticeResponse> = latest.get()
}
Placing fallbackMethod on the outermost @Retry annotation is intentional. If you put the fallback on @CircuitBreaker instead, it swallows the exception inside the breaker and @Retry never sees a failure to retry. Also, when the circuit is OPEN, Resilience4j throws CallNotPermittedException, which isn’t listed in retry-exceptions, so it skips retries and goes straight to the fallback.
Verification and Actuator monitoring
1
2
3
4
5
6
7
8
9
# Check circuit breaker state (defaults: CLOSED=UP, OPEN=CIRCUIT_OPEN, HALF_OPEN=CIRCUIT_HALF_OPEN)
curl -s localhost:8080/actuator/health | jq '.components.circuitBreakers'
# Inspect recent state transitions and recorded failures
curl -s localhost:8080/actuator/circuitbreakerevents/noticeApi | jq '.circuitBreakerEvents[-3:]'
# Query Prometheus/Micrometer metrics for breaker state and available bulkhead slots
curl -s "localhost:8080/actuator/metrics/resilience4j.circuitbreaker.state?tag=name:noticeApi&tag=state:open"
curl -s "localhost:8080/actuator/metrics/resilience4j.bulkhead.available.concurrent.calls?tag=name:noticeApi"
Stop the go-httpbin mock server from my RestClient timeout and connection pool post and call /api/notices 15 times. Since Retry tries twice per request, the fifth request pushes recorded calls to minimum-number-of-calls (10) and trips the breaker to OPEN. Every request after that returns the cached notices in a few milliseconds without making a network call. Bring the mock server back up after 30 seconds, and three successful probe calls in HALF_OPEN move the circuit back to CLOSED.
Production caveats and checklist
Once you define
record-exceptions, any exception not on that list is counted as a success. Always put local protection errors likeBulkheadFullExceptionintoignore-exceptionsso they don’t skew your failure rate. Also avoid settingallow-health-indicator-to-fail: trueon health checks wired into Kubernetes or Docker readiness/liveness probes—otherwise an external API outage marks your own containerDOWNand triggers a restart cascade.
- Are
sliding-window-sizeandminimum-number-of-callsmatched to your actual request volume? - Is
slow-call-duration-thresholdshorter than your HTTP client’s read timeout? - Is
fallbackMethodplaced on the outermost aspect so retries still run? - Are 4xx client errors excluded from
record-exceptionsso bad requests don’t trip the breaker? - Are alerts wired to
resilience4j.circuitbreaker.stateso you notice immediately when a circuit opens?