Coroutine-aware circuit breaker for resilient Kotlin services
implementation com.philiprehberger:circuit-breakerCoroutine-aware circuit breaker for resilient Kotlin services.
implementation("com.philiprehberger:circuit-breaker:0.2.0")
<dependency>
<groupId>com.philiprehberger</groupId>
<artifactId>circuit-breaker</artifactId>
<version>0.2.0</version>
</dependency>
import com.philiprehberger.circuitbreaker.*
import kotlin.time.Duration.Companion.seconds
val breaker = circuitBreaker("my-service") {
failureThreshold = 5
successThreshold = 2
resetTimeout = 30.seconds
onStateChange { from, to -> println("Circuit: $from -> $to") }
}
val result = breaker.execute {
callExternalService()
}
CLOSED ──(failures >= threshold)──> OPEN
^ │
│ (timeout elapsed)
│ v
└──(successes >= threshold)── HALF_OPEN
│
(failure) │
v
OPEN
val breaker = circuitBreaker("api") {
failureThreshold = 3
recordException<IOException>() // Only count these as failures
ignoreException<ValidationException>() // Never count these
}
val result = breaker.executeWithFallback(
fallback = { cachedResponse() }
) {
callExternalService()
}
breaker.forceOpen() // Stop all requests
breaker.forceClosed() // Resume requests
breaker.forceHalfOpen() // Enter test mode
breaker.reset() // Full reset to closed
val metrics = breaker.metrics()
println("State: ${metrics.state}, Failures: ${metrics.totalFailures}")
| Class / Function | Description |
|---|---|
circuitBreaker() | DSL builder for creating circuit breaker instances |
CircuitBreaker | Main class with execute() and state property |
CircuitState | Enum: CLOSED, OPEN, HALF_OPEN |
CircuitBreakerConfig | Configuration data class with thresholds and timeout |
CircuitOpenException | Thrown when the circuit is open |
CircuitBreaker.executeWithFallback() | Execute with automatic fallback when open |
CircuitBreaker.forceOpen() | Force circuit to OPEN state |
CircuitBreaker.forceClosed() | Force circuit to CLOSED state |
CircuitBreaker.forceHalfOpen() | Force circuit to HALF_OPEN state |
CircuitBreaker.reset() | Reset to CLOSED with zeroed counters |
CircuitBreaker.metrics() | Get current state and failure/success counts |
CircuitMetrics | Data class with state, failures, successes |
./gradlew test # Run tests
./gradlew check # Run all checks
./gradlew build # Build JAR
If you find this project useful: