CircuitBreaker

Circuit breaker pattern to prevent cascading failures.

The circuit breaker prevents cascading failures by stopping calls to failing services. It has three states: Closed (normal), Open (failing), and Half-Open (testing recovery).

States:

  • Closed: Normal operation, calls are allowed

  • Open: Circuit is broken, calls fail immediately

  • Half-Open: Testing if service has recovered

State transitions:

Closed -> Open: When failure threshold is exceeded
Open -> Half-Open: After reset timeout expires
Half-Open -> Closed: When success threshold is reached
Half-Open -> Open: When any failure occurs

Basic usage:

val breaker = CircuitBreaker.create(config = CircuitBreakerConfig(
failureThreshold = 5,
resetTimeout = 30.seconds
))

val result = breaker.execute {
callExternalService()
}

With fallback:

val result = breaker.executeOrFallback(
fallback = { cachedValue() }
) {
callExternalService()
}

State monitoring:

when (breaker.currentState()) {
CircuitBreakerState.Closed -> println("Service healthy")
CircuitBreakerState.Open -> println("Service unavailable")
CircuitBreakerState.HalfOpen -> println("Testing service...")
}

DSL builder:

val breaker = circuitBreaker {
failureThreshold = 5
resetTimeout = 30.seconds
halfOpenSuccessThreshold = 3
}

Parameters

config

Configuration for circuit breaker behavior

Types

Link copied to clipboard
object Companion

Factory for CircuitBreaker.

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 failures(): Int

Gets the current failure count.

Link copied to clipboard
suspend fun reset()

Manually resets the circuit breaker to closed state.

Link copied to clipboard
suspend fun successes(): Int

Gets the current success count (in half-open state).

Link copied to clipboard
suspend fun trip()

Manually opens the circuit breaker.

Inherited functions

Link copied to clipboard