SlidingWindowCircuitBreaker

Sliding-window circuit breaker: trips on a failure rate over the last N calls, rather than CircuitBreaker's consecutive-failure count.

Consecutive-failure tripping is sensitive to call ordering and blind to low-but-nonzero, steady-state error rates: with CircuitBreaker's default failureThreshold = 5, a service failing 1 call in 3 (a serious 33% error rate) never trips at all as long as it never strings together 5 failures in a row. A sliding window instead asks "what fraction of the last N calls failed?", which is what you usually actually want to protect against -- the same approach resilience4j's CircuitBreaker uses by default.

Otherwise behaves like CircuitBreaker: Closed (normal) ->Open (failing fast) ->Half-Open (testing recovery) -> back to Closed or Open, with the same reset-timeout and half-open-success-threshold semantics.

Basic usage:

val breaker = SlidingWindowCircuitBreaker.create(config = SlidingWindowCircuitBreakerConfig(
slidingWindowSize = 20,
minimumNumberOfCalls = 10, // don't trip on the first few calls before the window fills
failureRateThreshold = 0.5, // trip once >= 50% of the last 20 calls failed
))

val result = breaker.execute {
callExternalService()
}

Inspecting the current failure rate:

val stats = breaker.statistics()
println("${stats.callsInWindow} calls in window, ${stats.failureRate * 100}% failing")

Types

Link copied to clipboard

Functions

Link copied to clipboard

Adds a listener for circuit breaker state changes.

Link copied to clipboard

Gets the current state of the circuit breaker.

Link copied to clipboard
suspend fun <T> execute(block: suspend () -> T): T

Executes an operation through the circuit breaker.

Link copied to clipboard
suspend fun <T> executeOrFallback(fallback: suspend (CircuitBreakerOpenException) -> T, block: suspend () -> T): T

Executes an operation with a fallback if the circuit is open.

Link copied to clipboard
suspend fun reset()

Manually resets the circuit breaker to closed state and clears its window.

Link copied to clipboard

Returns a snapshot of the current window's statistics.

Inherited functions

Link copied to clipboard