Class CircuitBreakerClient

java.lang.Object
com.tnsai.llm.resilience.CircuitBreakerClient
All Implemented Interfaces:
com.tnsai.llm.LLMClient

public class CircuitBreakerClient extends Object implements com.tnsai.llm.LLMClient
LLMClient decorator that implements the circuit breaker pattern.

Prevents cascading failures by fast-failing when a provider is consistently down, instead of wasting latency on every request.

States

  • CLOSED — Normal operation. Failures are counted.
  • OPEN — Fast-fail. All requests throw CircuitOpenException.
  • HALF_OPEN — Probe mode. One request is allowed through to test recovery.

State Transitions

   CLOSED ──(N consecutive failures)──► OPEN
   OPEN ────(recovery timeout)────────► HALF_OPEN
   HALF_OPEN ──(probe succeeds)───────► CLOSED
   HALF_OPEN ──(probe fails)──────────► OPEN
 

Usage


 // Wrap any LLMClient
 LLMClient resilient = CircuitBreakerClient.wrap(openaiClient);

 // With custom settings
 LLMClient resilient = CircuitBreakerClient.builder()
     .client(openaiClient)
     .failureThreshold(3)
     .recoveryTimeout(Duration.ofSeconds(60))
     .build();

 // Compose with FallbackRouter for automatic failover
 FallbackRouter router = FallbackRouter.of(
     CircuitBreakerClient.wrap(primary),
     CircuitBreakerClient.wrap(fallback)
 );