How does a Resilience4j circuit breaker work, and which settings control each state transition?

A circuit breaker wraps calls to a remote dependency and stops calling it once it is clearly unhealthy. Callers fail fast instead of tying up threads and connections waiting on timeouts, and the struggling dependency gets less load while it recovers. This matters most to backend and platform engineers whose services make synchronous calls to databases, internal APIs or third-party services, where one slow downstream can exhaust a caller's thread pool.

Resilience4j records call outcomes in a sliding window and evaluates them against thresholds. Each transition is controlled by specific properties:

Transition Governing settings What happens
Closed → Open failureRateThreshold, slowCallRateThreshold (with slowCallDurationThreshold), minimumNumberOfCalls Opens when either rate is equal to or above its threshold, but only after the window holds at least minimumNumberOfCalls calls
Open → Half-open waitDurationInOpenState, automaticTransitionFromOpenToHalfOpenEnabled After the wait, the breaker moves on the next call. If automatic transition is enabled, it moves on a timer instead
Half-open → Closed or Open permittedNumberOfCallsInHalfOpenState Lets that many trial calls through, then recomputes both rates and either closes or reopens

Three special states are entered only through explicit API calls, never through thresholds:

  • Disabled permits every call and records nothing.
  • Forced-open rejects every call.
  • Metrics-only records outcomes and emits events but never opens.

Metrics-only is useful for observing what a configuration would do before you let it reject traffic.

How it works at runtime, call by call

In code, a Resilience4j circuit breaker is a decorator around a function such as a Supplier, Callable or Runnable. You can apply it with CircuitBreaker.decorateSupplier(...), with the Decorators builder, or with the @CircuitBreaker annotation in Spring Boot. Every call through the decorator goes through the same steps:

  1. Permission check. The breaker decides whether the call may proceed. In the open state, and in half-open once the permitted trial calls are used up, it throws CallNotPermittedException and never invokes the dependency.
  2. Execution and timing. If the call is permitted, the breaker runs it and measures how long it takes.
  3. Classification. When the call completes, the breaker classifies the outcome as success, failure or ignored, using recordExceptions, ignoreExceptions and any predicates you configured. Separately, it marks the call as slow or not slow by comparing its duration with slowCallDurationThreshold.
  4. Recording and evaluation. Recorded outcomes go into the sliding window. The breaker recomputes the failure rate and slow-call rate and changes state if a threshold is crossed.
  5. Events. Recorded outcomes, rejected calls and state transitions are published on the breaker's event publisher. The Spring Boot integration exposes these through Actuator endpoints and Micrometer metrics.

All of this state lives in the memory of the process that owns the breaker. There is no coordination between replicas, which is why later sections reason about traffic per instance rather than per service.

+--------------------+                                  +---------------+
|       CLOSED       | failure/slow rate>=threshold and |     OPEN      |
| calls pass; window | calls >= minimumNumberOfCalls    | rejects all   |
|  records outcomes  |--------------------------------->| calls (fast)  |
+--------------------+                                  +---------------+
     ^                                                         |      ^
     | rates below                  waitDurationInOpenState    |      |
     | thresholds                   elapsed; next call, or     |      |
     |                              timer when enabled:        |      |
     |            automaticTransitionFromOpenToHalfOpenEnabled |      |
     |                                                         v      |
     |              +---------------------------------------------+   |
     +--------------|                  HALF-OPEN                  |   |
                    | permittedNumberOfCallsInHalfOpenState calls |   |
                    | allowed through, then rates recomputed      |   |
                    +---------------------------------------------+   |
                                                  | rate >= threshold |
                                                  +-------------------+

+--------------------------------------------------------------------------+
| Special states, entered only via API calls, never via thresholds:        |
|  DISABLED: all calls pass, nothing recorded                              |
|  FORCED_OPEN: all calls rejected                                         |
|  METRICS_ONLY: outcomes recorded and events emitted, never opens         |
+--------------------------------------------------------------------------+

Resilience4j circuit breaker state transitions and the configuration properties that govern each one, with the API-only special states shown separately.

Who should use a Resilience4j circuit breaker?

Resilience4j is a Java library, so this advice applies to teams running JVM services, including Spring Boot applications that use the Resilience4j starter. Within that group, these people benefit most from configuring breakers carefully:

  • Backend engineers who own services with synchronous dependencies. This includes services calling other services over HTTP or gRPC, databases, caches or third-party APIs on a request path. When those calls hang, the service's own threads and connection pools fill up, and a breaker is the piece that stops that from happening.
  • Platform and shared-library teams. These teams provide a common HTTP client or service template, and the defaults they choose for timeouts, windows and exception classification spread to every service that uses it. A bad default here, such as a high minimumNumberOfCalls, quietly disables protection across many services at once.
  • SREs and on-call engineers. They need breaker state, transitions and fallback rates to show up on dashboards and in alerts. They gain from consistent naming and event logging even if they never write the configuration.
  • Teams that have had a cascading failure. If one slow downstream has already taken out an upstream service, a breaker that trips on slow calls addresses that failure mode directly.

Breakers are a weaker fit for teams whose dependencies are mostly asynchronous, very low-volume or have no meaningful fallback. The section on when to avoid a circuit breaker covers those cases and the alternatives.

Why do Resilience4j circuit breakers never trip on low-traffic endpoints?

A breaker in the closed state does not evaluate the failure rate threshold until it has recorded at least minimumNumberOfCalls outcomes. Before that point, a 100% failure rate opens nothing. slidingWindowType and slidingWindowSize determine whether that minimum can ever be reached.

Window type slidingWindowSize means Low-traffic risk
Count-based Last N calls Eligibility takes a long time, and the window can span hours of old outcomes
Time-based Calls in the last N seconds Eligibility may never happen if fewer than the minimum calls arrive per window

Illustrative estimate

Assume a dependency receives 6 calls per minute in total, spread across 3 replicas. That is 2 calls per minute per instance. Assume minimumNumberOfCalls is 50.

  • Count-based window: Each instance needs 25 minutes of traffic before it can evaluate the failure rate.
  • Time-based window of 60 seconds: At most 2 calls fall inside any window. The minimum of 50 is never reached, so the breaker never trips.

Scaling to 6 replicas halves the per-instance rate to 1 call per minute. Each replica keeps its own breaker state, so the count-based case now takes 50 minutes. The dependency's total load is unchanged.

Trade-offs

  • Small windows and low minimums trip quickly, but they also trip on brief blips such as a two-call timeout spike.
  • A high minimumNumberOfCalls leaves low-traffic dependencies effectively unprotected.
  • Count-based windows cover different time periods as load varies. During off-peak hours the window may still be counting failures from a recovered outage.
  • Time-based windows aggregate calls into per-second buckets. They react to sustained trends rather than to individual calls, which makes them coarser.

How do you make a breaker trip on slow calls and the right exceptions?

A failure-rate-only breaker only reacts to calls that throw. A dependency that accepts connections and then stalls produces no exceptions, so the failure rate stays at zero while threads and connection pools fill up. slowCallDurationThreshold marks any call slower than the given duration as slow. slowCallRateThreshold opens the breaker when the share of slow calls in the window crosses that percentage. Slow calls count toward this rate even when they eventually succeed.

A call is only recorded once it completes. If a request hangs with no timeout, it is never recorded at all. Put a client or TimeLimiter timeout at or slightly above the slow-call duration, and record the resulting TimeoutException as a failure. Do not set the duration close to normal p99. At that point roughly 1% of healthy traffic is already slow, and a GC pause or cold cache can push the rate over the threshold. Set the duration well above p99 and below the point where callers start to suffer.

recordExceptions lists the exceptions that count as failures. ignoreExceptions lists exceptions that count as neither success nor failure, and it takes precedence over recordExceptions. For HTTP clients, a recordFailurePredicate that inspects the status code is usually clearer than a list of exception classes.

Outcome Signals Count as failure?
Timeout TimeoutException Yes
Connection refused ConnectException Yes
5xx response HttpServerErrorException Yes
4xx or validation error HttpClientErrorException, validation exceptions No, ignore

A 4xx response means the caller sent a bad request. Counting it as a failure lets one misbehaving client open the circuit for everyone else.

resilience4j:
  circuitbreaker:
    instances:
      inventoryService:
        slidingWindowType: COUNT_BASED
        slidingWindowSize: 50
        minimumNumberOfCalls: 20          # avoid opening on a handful of calls
        failureRateThreshold: 50          # % of recorded failures
        # Catch stalls that never throw: well above p99, below caller pain.
        slowCallDurationThreshold: 2s
        slowCallRateThreshold: 50         # % of slow calls, even if they succeed
        waitDurationInOpenState: 30s
        permittedNumberOfCallsInHalfOpenState: 5
        # Dependency unhealthiness: count as failures.
        recordExceptions:
          - java.util.concurrent.TimeoutException
          - java.net.ConnectException
          # RestTemplate wraps I/O errors such as connection refused in this type
          - org.springframework.web.client.ResourceAccessException
          - org.springframework.web.client.HttpServerErrorException
        # Caller errors: neither success nor failure. Takes precedence over recordExceptions.
        ignoreExceptions:
          - org.springframework.web.client.HttpClientErrorException
          - jakarta.validation.ConstraintViolationException
  timelimiter:
    instances:
      inventoryService:
        # Slightly above the slow-call threshold so a hung call ends as a
        # recorded TimeoutException instead of never completing.
        timeoutDuration: 2200ms
        cancelRunningFuture: true

A circuit breaker that opens on either error rate or slow-call rate, paired with a TimeLimiter just above the slow-call threshold, recording timeouts, connection failures and 5xx while ignoring 4xx and validation errors.

How should you configure the half-open state to avoid flapping?

When the breaker is open, it rejects calls until waitDurationInOpenState elapses. It then moves to half-open and lets through exactly permittedNumberOfCallsInHalfOpenState calls. Once those calls complete, it compares their failure rate (and slow-call rate) against the same thresholds used in the closed state. If the rate is below the threshold, the breaker closes. If not, it reopens and the wait starts over.

By default, the open-to-half-open transition happens lazily, on the first call after the wait expires. On an idle endpoint the breaker can therefore stay open long after the wait has passed. Setting automaticTransitionFromOpenToHalfOpenEnabled makes the transition happen on a timer instead.

Too few probes cause flapping

With one or two permitted calls, a single lucky success can close the breaker against a dependency that is still mostly failing. The next sliding window then fills with failures, the breaker opens again, and the cycle repeats.

Illustrative estimate, assuming a dependency failing 70% of calls and a 50% threshold:

  • One probe: the breaker closes 30% of the time.
  • Ten probes: it closes only if four or fewer fail, which happens about 5% of the time.

Sizing the probes and the wait

Probes: Choose enough probes that one outcome cannot move the rate across the threshold. Roughly, 1/N should be well below the gap between the threshold and the failure rate you expect during an outage. For thresholds near 50%, ten probes is a sensible floor. Lower thresholds need more probes.

Wait duration: Don't size it to the worst outage you can imagine. A long wait only delays recovery after the dependency is healthy again. Instead, match it to how quickly the dependency typically recovers, such as a pod restart or failover time, and let repeated half-open failures handle longer outages.

import io.github.resilience4j.circuitbreaker.CircuitBreaker;
import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig;
import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig.SlidingWindowType;
import java.time.Duration;

public class InventoryBreaker {

    public static CircuitBreaker create() {
        CircuitBreakerConfig config = CircuitBreakerConfig.custom()
            // Closed state: judge health over the last 50 calls.
            .slidingWindowType(SlidingWindowType.COUNT_BASED)
            .slidingWindowSize(50)
            .minimumNumberOfCalls(20)
            // Half-open probes are compared against these same thresholds.
            .failureRateThreshold(50.0f)
            .slowCallRateThreshold(80.0f)
            .slowCallDurationThreshold(Duration.ofSeconds(2))
            // Match typical recovery time (e.g. pod restart or failover),
            // not the worst outage you can imagine. Longer waits only
            // delay recovery once the dependency is healthy.
            .waitDurationInOpenState(Duration.ofSeconds(30))
            // Ten probes: one success or failure moves the rate by 10
            // points, so a single lucky call cannot close the breaker
            // against a dependency that is still mostly failing.
            // With a lower threshold, raise this number.
            .permittedNumberOfCallsInHalfOpenState(10)
            // Move to half-open on a timer instead of waiting for the
            // first call after the wait, so idle endpoints recover too.
            .automaticTransitionFromOpenToHalfOpenEnabled(true)
            .build();

        return CircuitBreaker.of("inventory-service", config);
    }
}

A Resilience4j circuit breaker config that uses ten half-open probes against a 50% failure threshold to resist flapping, a wait duration sized to typical recovery time, and automatic open-to-half-open transition.

How does decorator ordering change what a Spring Boot resilience setup counts?

The same four primitives produce very different counts depending on which one wraps which. With annotations, the Resilience4j Spring Boot integration applies aspects in a fixed default order: Retry outermost, then CircuitBreaker, RateLimiter, TimeLimiter, and Bulkhead innermost. Stacking @Retry and @CircuitBreaker on one method therefore means every retry attempt is a separate call the breaker records. Programmatically, the Decorators builder wraps in call order: each with... call wraps everything added before it, so the last one added becomes the outermost layer.

Arrangement What the breaker records Main risk
Retry outside breaker Every attempt Load amplification and an inflated failure rate that trips the breaker early. Retrying CallNotPermittedException wastes attempts.
Retry inside breaker One outcome per logical call Transient failures are absorbed, so the breaker trips late.
TimeLimiter inside breaker Timeouts as failures None, if timeouts are listed as recorded exceptions

If retry stays outside the breaker, exclude CallNotPermittedException from retryable exceptions. Otherwise you retry against a breaker that has already decided. Keep the bulkhead innermost so that a rejected call never consumes a dependency connection.

An open breaker only fails fast. Whether users see an error or a degraded response depends entirely on the fallback. Cached or default fallback data is where correctness bugs hide: a pricing service that returns yesterday's prices looks healthy on every latency dashboard. Emit a metric or log tag every time a fallback executes, and alert on the fallback rate separately from the error rate.

// PricingService.java: annotation style. The default aspect order puts Retry outside
// CircuitBreaker, so the breaker records every attempt, not every logical call.
@Retry(name = "pricing")
@CircuitBreaker(name = "pricing", fallbackMethod = "cachedPrices")
public PriceList currentPrices(String sku) {
    return pricingClient.fetch(sku);
}

// The fallback takes the same parameters plus a Throwable. Count every execution,
// because stale prices look healthy on latency and error dashboards.
private PriceList cachedPrices(String sku, Throwable ex) {
    meterRegistry.counter("pricing.fallback", "cause", ex.getClass().getSimpleName()).increment();
    return priceCache.lastKnown(sku); // possibly stale: alert on the fallback rate
}

// PricingDecorators.java: programmatic style. Each with... call wraps everything
// added before it, so the last one added is the outermost layer.
Retry retry = Retry.of("pricing", RetryConfig.custom()
    .maxAttempts(3)
    .waitDuration(Duration.ofMillis(200))
    .ignoreExceptions(CallNotPermittedException.class) // don't retry a breaker that is already open
    .build());
CircuitBreaker breaker = CircuitBreaker.ofDefaults("pricing");
Bulkhead bulkhead = Bulkhead.ofDefaults("pricing");

Supplier<PriceList> guarded = Decorators
    .ofSupplier(() -> pricingClient.fetch(sku))
    .withBulkhead(bulkhead)        // innermost: a rejected call never takes a connection
    .withCircuitBreaker(breaker)   // records each retry attempt as its own outcome
    .withRetry(retry)              // outermost: amplifies load on the dependency
    .withFallback(
        List.of(CallNotPermittedException.class, BulkheadFullException.class),
        ex -> cachedPrices(sku, ex)) // only these exceptions degrade; others propagate
    .decorate();

The same retry-outside-breaker arrangement written with annotations and with the Decorators builder, including a fallback that records a metric every time it serves cached data.

How can you verify a circuit breaker actually trips before production does it for you?

Make breaker state visible before you need it. With the Resilience4j Spring Boot starter and Actuator on the classpath, the circuitbreakers and circuitbreakerevents endpoints show current state and recent transitions. Setting registerHealthIndicator: true on an instance adds it to the health endpoint. Through Micrometer, each instance publishes metrics such as resilience4j.circuitbreaker.state, resilience4j.circuitbreaker.failure.rate, resilience4j.circuitbreaker.slow.call.rate and resilience4j.circuitbreaker.calls, tagged with the breaker name. Name breakers after the dependency, such as inventory-service, not after the calling class. An on-call engineer can then go from "checkout is failing" to "the inventory breaker opened at 14:02" without reading code.

Subscribe to onStateTransition on each breaker's event publisher and log every transition with the breaker name and the failure and slow-call rates at that moment. Alert on CLOSED→OPEN and on repeated OPEN→HALF_OPEN→OPEN cycles. Repeated cycles usually mean the wait duration is too short.

Test the behaviour, not only the configuration. Write a test that loads your real configuration, points the client at a stub that returns errors or delays responses past slowCallDurationThreshold, and sends enough calls to fill minimumNumberOfCalls. Then assert that the state is OPEN and that the next call is rejected with CallNotPermittedException. Calling transitionToOpenState() manually only proves your fallback works, not that your thresholds can ever trip.

In staging, run fault-injection drills: add latency or drop connections to one dependency and watch the dashboard. If the breaker stays closed during the drill, you have found a misconfiguration at the cost of an afternoon rather than an outage.

When should you avoid a circuit breaker, and what are the alternatives?

Some dependencies are poor candidates for a breaker. With very low call volume, the sliding window rarely fills, so the breaker either never trips or trips on two unlucky calls. If there is no viable fallback, an open breaker returns the same error the dependency would have, just sooner. That still helps when it frees threads, but not otherwise. Asynchronous and queue-based flows already decouple the caller: messages wait in the queue while the consumer pauses or slows down. Idempotent background jobs are usually better served by retry with exponential backoff and jitter, because a delayed job costs little and a failed one only needs to run again later.

Alternative Protects against Main limitation
Timeouts alone Threads blocked on hung calls Keeps sending load to a failing dependency
Bulkhead One dependency exhausting a shared pool Does not reduce calls to the failing dependency
Rate limiter Exceeding a known capacity Fixed limits go stale as capacity changes
Adaptive concurrency limit Overload as latency rises Harder to reason about and tune
Load shedding Server-side overload Rejects work instead of degrading it
Service-mesh outlier detection One bad upstream instance Ejects hosts; cannot express application fallbacks

Resilience4j breaker state lives in each instance's memory. Every replica decides on its own, so during a partial outage some replicas may stay open while others stay closed.

Each breaker also has an ongoing cost: a per-dependency config, tests, dashboards and fallback code that must change with the dependency. Add one where a cascading failure would cost more than that upkeep. That usually means synchronous, high-volume calls on a user-facing path.

How can a correctly configured circuit breaker save engineering time?

A breaker that trips when it should saves time in four places.

Shorter, smaller incidents. When a downstream dependency stalls, a working breaker contains the damage to the features that depend on it. Without one, the stall spreads: threads block, connection pools drain and unrelated endpoints on the same service start failing. Engineers then have to work out which of several failing services is the actual cause, and that triage is usually the slowest part of a cascading incident. With a breaker in place, the failure is local and the cause is already named.

Faster diagnosis. Breakers named after dependencies, with state transitions logged and exported as metrics, answer "what broke first?" from a dashboard. On-call engineers can skip correlating timeouts across service logs and see which breaker opened, at what time, and at what failure or slow-call rate.

Less hand-written resilience code. Without a library, teams tend to write ad hoc timeout, retry and "stop calling it for a while" logic in each client, and each version behaves slightly differently. Shared configs.default values plus per-instance overrides replace that code with declarative configuration that is reviewed in one place and covered by one style of test.

Problems found before production. The tests and fault-injection drills described above surface a breaker that can never trip, such as one with a minimumNumberOfCalls higher than its per-instance traffic can reach, during working hours rather than during an outage.

Illustrative estimate, using assumed inputs only: suppose a team has two cascading incidents a year caused by a stalled dependency. Assume each involves three engineers for four hours of triage and recovery, because the failure has spread to several services. That is 24 engineer-hours a year. If a correctly tripping breaker turns each incident into a single service degrading behind a visible fallback, and assumed triage drops to one engineer for one hour, the total falls to 2 engineer-hours. Against that saving, count the upkeep from the previous section: configuration, tests, dashboards and fallback code for each dependency. Substitute your own incident history before deciding. These numbers are assumptions, not measurements.

The saving depends on the breaker actually tripping. A breaker that is misconfigured, for example one that never reaches its minimum call count or does not record timeouts, costs the same upkeep and saves nothing. That is the reason for the checklist below.

Checklist: deriving per-dependency Resilience4j settings from observed traffic

Give each dependency its own named instance. One shared default treats a payment gateway that handles hundreds of calls per second the same as a nightly reporting API, and it will be wrong for at least one of them. Work through this list for each dependency:

  1. Measure call rate per instance, not per service. Divide the dependency's total call rate by your replica count. Each replica keeps its own window, so this per-instance number decides whether a window ever fills. Recheck it whenever autoscaling limits change.
  2. Pick the window from detection time. Choose slidingWindowType and slidingWindowSize so that minimumNumberOfCalls is reached within the outage length you are willing to tolerate. If one replica sees two calls per second and you need detection within 30 seconds, a minimum of 100 calls cannot work. (Illustrative estimate.)
  3. Derive slow-call thresholds from percentiles. Set slowCallDurationThreshold above normal p99, with enough headroom that routine tail latency does not count as slow. Keep it below the timeout so slow calls are recorded before they become failures.
  4. Classify exceptions explicitly. Put server errors, timeouts and connection failures in recordExceptions. Put validation errors and 4xx-style business errors in ignoreExceptions.
  5. Size half-open probes. Set permittedNumberOfCallsInHalfOpenState high enough to give a meaningful failure rate. Set waitDurationInOpenState to roughly how long the dependency takes to recover.
  6. Fix decorator order and document it next to the configuration.
  7. Make every fallback emit a metric and an alert, so degraded responses are visible.
  8. Schedule fault-injection drills for each instance.

In the template, put shared values under configs.default. Each entry under instances then declares baseConfig: default and overrides only the values derived above.

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to resilience4j circuit breaker configuration, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Changing a shared variable is one edit and one review instead of editing every service's .env by hand.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.