Reliable LLM Calling

ReliableClient is in llm4s-core; it wraps the LLMClient of any provider module.

Table of contents

  1. Architecture
  2. Features
  3. Quick Start
  4. Configuration Examples
  5. Provider Examples
  6. Retry Policies
  7. Tool Call Timeouts and Retries
  8. Circuit Breaker
    1. Monitoring
  9. Metrics Integration
  10. Error Handling
  11. Best Practices
    1. 1. Use Default Configuration First
    2. 2. Monitor Circuit Breaker State
    3. 3. Set Appropriate Deadlines
    4. 4. Disable for Testing
  12. Advanced Patterns
    1. Pattern 1: Different Configs Per Environment
    2. Pattern 2: Provider-Specific Configurations
    3. Pattern 3: Operation-Specific Timeouts
    4. Pattern 4: Graceful Degradation
    5. Pattern 5: Circuit Breaker Monitoring
  13. Troubleshooting
    1. Issue: Too Many Retries
    2. Issue: Circuit Breaker Opens Too Quickly
    3. Issue: Timeouts Too Aggressive
    4. Issue: Rate Limits Not Respected
    5. Issue: Circuit Breaker Never Closes
  14. Adding it to an existing client
    1. Wrapping a client
    2. Testing Strategies
  15. Performance Considerations
    1. Latency Impact
    2. Memory Footprint
    3. Thread Safety
    4. Best Practices
  16. Complete Example
  17. API Reference
    1. ReliabilityConfig
    2. RetryPolicy
    3. CircuitBreakerConfig
    4. RateLimitConfig
    5. ReliableClient
  18. Next steps

Production-grade fault tolerance for LLM provider calls through retry logic, circuit breakers, and deadline enforcement. Automatic failure recovery with intelligent retry strategies, circuit breakers to prevent cascading failures, deadline enforcement to prevent unbounded waiting, and built-in metrics for monitoring.

Architecture

The reliability layer wraps any LLMClient implementation, intercepting all operations to apply:

  1. Retry Policy: Determines if/when to retry failed requests
  2. Circuit Breaker: Tracks failure patterns and fails fast when service is unhealthy
  3. Deadline Enforcement: Stops retrying once a call’s attempts have used their time budget
  4. Local Rate Limiting (opt-in): A token bucket consulted before every attempt, retries included
  5. Metrics Collection: Records retry attempts, circuit state transitions, and error types
1
2
3
User Code → ReliableClient → Circuit Breaker → Retry Logic → Deadline → Rate Limit → Provider Client → LLM API
                    ↓                 ↓              ↓
              Metrics Collector  State Tracking  Timeout Control

Features

Configurable Retry Policies - Multiple retry strategies with intelligent error classification:

  • Exponential Backoff (default): 1s → 2s → 4s → 8s → ...
  • Linear Backoff: 2s → 4s → 6s → 8s → ...
  • Fixed Delay: 3s → 3s → 3s → ...
  • Custom Logic: User-defined delay functions
  • Server-Aware: Respects Retry-After headers from providers

Retryable Errors:

  • RateLimitError - 429 responses (uses server retry delay if provided)
  • TimeoutError - Connection/read timeouts
  • ServiceError - 5xx server errors
  • NetworkError - Connection failures, DNS issues

Non-Retryable Errors:

  • AuthenticationError - Invalid credentials (401/403)
  • ValidationError - Malformed requests (400)
  • ConfigurationError - Client misconfiguration

Circuit Breaker Pattern - Three states for service resilience:

1. Closed (Normal Operation)

  • All requests pass through
  • Failures are counted
  • Transitions to Open after N consecutive failures

2. Open (Failing Fast)

  • Requests fail immediately without calling provider
  • Returns a CircuitOpenError carrying retryAfter, the time left before a probe is let through. It is not retried: RetryPolicy.isRetryable is false for it, so neither this client nor an outer retry repeats the fast-fail
  • After recovery timeout, transitions to Half-Open

3. Half-Open (Testing Recovery)

  • Allows limited requests to test service health
  • Success → back to Closed
  • Failure → back to Open

Benefits:

  • Prevents resource exhaustion from calling dead services
  • Reduces latency during outages (fail fast vs. timeout)
  • Automatic recovery testing

Deadline Enforcement - A time budget for all the attempts of one call together:

  • Tracks elapsed time across all retry attempts
  • Checked before each attempt and before each wait: no retry starts once it has passed
  • Returns TimeoutError with context about attempts made
  • Does not interrupt an attempt in flight: a call hung inside the provider client is bounded by that client’s own timeout (llm4s.providers.<name>.timeouts), not by the deadline

Use Cases:

  • Real-time applications requiring bounded latency
  • Long-running batch jobs with time limits
  • User-facing features with UX constraints

Metrics Integration - Comprehensive observability through MetricsCollector interface:

Tracked Metrics:

  • Retry attempt count and delay per provider
  • Circuit breaker state transitions (closed → open → half-open)
  • Error classification by type
  • Operation duration including retries

Integration:

  • Compatible with any metrics backend (Prometheus, Datadog, CloudWatch)
  • No-op implementation for testing
  • Separate collection from business logic

Quick Start

There is one way to make a client reliable: wrap the LLMClient you already have in a ReliableClient.

1
2
3
4
5
6
7
ReliableClient(
  underlying: LLMClient,
  providerName: String,                         // label used in metrics
  config: ReliabilityConfig = ReliabilityConfig.default
): ReliableClient

reliableClient.withMetrics(collector: MetricsCollector): ReliableClient   // optional

From configuration (recommended) - build the client for whichever named provider section application.conf selects, then wrap it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import org.llm4s.config.Llm4sConfig
import org.llm4s.llmconnect.{ LLMClient, LLMConnect }
import org.llm4s.model.ModelRegistryService
import org.llm4s.reliability.{ ReliabilityConfig, ReliableClient }
import org.llm4s.types.Result
import org.llm4s.types.ProviderModelTypes.ProviderName

val clientResult: Result[LLMClient] =
  for
    providerConfig <- Llm4sConfig.defaultProvider()          // or Llm4sConfig.provider(ProviderName("openai-main"))
    registry       <- Llm4sConfig.modelRegistryService()
    given ModelRegistryService = registry
    client <- LLMConnect.getClient(providerConfig)
  yield ReliableClient(client, providerConfig.providerId.asString, ReliabilityConfig.default)

clientResult.foreach { client =>
  // Use like any LLMClient
  val result = client.complete(conversation)
}

Manual Wrapping - any LLMClient, with full control over configuration and metrics:

1
2
3
4
5
6
7
8
9
10
import org.llm4s.reliability.{ ReliableClient, ReliabilityConfig }

import org.llm4s.metrics.MetricsCollector
import org.llm4s.reliability.{ ReliableClient, ReliabilityConfig }

val reliableClient = ReliableClient(
  underlying = baseClient,
  providerName = "openai",
  config = ReliabilityConfig.default
).withMetrics(MetricsCollector.noop) // or your own collector: see Metrics Integration

The provider name is not inferred: pass the provider id (providerConfig.providerId.asString) or any stable label you want on your metrics.

Here and in the fragments below, baseClient is the LLMClient being wrapped - one from LLMConnect.getClient, as in the Quick Start - and conversation is a Conversation.

Configuration Examples

Default (Recommended):

1
2
ReliabilityConfig.default
// 3 retry attempts, 5 failures → open circuit, 5 min deadline

Aggressive - More retries, faster recovery:

1
2
3
4
val client = ReliableClient(baseClient, "anthropic", ReliabilityConfig.aggressive)
// - 5 retry attempts (500ms base delay)
// - Circuit breaker: 10 failures → open for 15s
// - 3 min deadline

Conservative - Fewer retries, longer timeout:

1
2
3
4
ReliabilityConfig.conservative
// - 2 retry attempts
// - Circuit breaker: 3 failures → open for 60s
// - 10 min deadline

Custom:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import org.llm4s.reliability._
import scala.concurrent.duration._

val customConfig = ReliabilityConfig(
  retryPolicy = RetryPolicy.exponentialBackoff(
    maxAttempts = 5,
    baseDelay = 500.millis,
    maxDelay = 30.seconds
  ),
  circuitBreaker = CircuitBreakerConfig(
    failureThreshold = 3,
    recoveryTimeout = 45.seconds,
    successThreshold = 2
  ),
  rateLimit = RateLimitConfig(enabled = true, requestsPerMinute = 120, burstCapacity = 20),
  deadline = Some(2.minutes)
)

val client = ReliableClient(baseClient, "openai", customConfig)

rateLimit is off by default (RateLimitConfig.disabled). When enabled, ReliableClient takes a token before every attempt, retries included; with none available the attempt fails with a RateLimitError whose origin is RateLimitOrigin.LocalThrottle, without reaching the provider, and one ErrorKind.RateLimit metric is recorded. Being a RateLimitError, it is retryable under the default policies.

Provider Examples

ReliableClient wraps any LLMClient, so every provider works the same way - including one supplied by a module llm4s-core has never heard of. Each provider lives in its own module (llm4s-openai, llm4s-anthropic, llm4s-gemini, llm4s-ollama, llm4s-openai-compatible, …); add the dependency, declare a named section in application.conf, and load it with Llm4sConfig.provider(name) (or defaultProvider()) as in the Quick Start:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
llm4s {
  defaultProvider = "openai-main"          # the default: the name of a section below
  providers {
    openai-main {
      provider = "openai"
      model    = "gpt-5.6-luna"        # key from OPENAI_API_KEY via llm4s.credentials.openai.apiKey
    }

    claude {
      provider = "anthropic"
      model    = "claude-sonnet-5-5"
    }
  }
}

See Configuration for every provider’s section keys.

Retry Policies

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// Exponential backoff (default): 2^n * baseDelay
RetryPolicy.exponentialBackoff(
  maxAttempts = 3,
  baseDelay = 1.second,
  maxDelay = 32.seconds
)
// Delays: 1s, 2s, 4s, 8s, 16s, 32s...

// Linear backoff: n * baseDelay
RetryPolicy.linearBackoff(
  maxAttempts = 3,
  baseDelay = 2.seconds
)
// Delays: 2s, 4s, 6s, 8s...

// Fixed delay
RetryPolicy.fixedDelay(
  maxAttempts = 3,
  delay = 3.seconds
)
// Delays: 3s, 3s, 3s...

// No retry
RetryPolicy.noRetry

// Custom policy
RetryPolicy.custom(
  attempts = 5,
  delayFn = (attempt, error) => {
    error match {
      case _: RateLimitError => (attempt * 5).seconds
      case _: TimeoutError   => 1.second
      case _                 => (attempt * 2).seconds
    }
  },
  retryableFn = {
    case _: RateLimitError => true
    case _: NetworkError   => true
    case _                 => false
  }
)

Tool Call Timeouts and Retries

Separate from the LLM-client retry above, a ToolRegistry can bound and retry individual tool calls:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import org.llm4s.toolapi._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._

val request  = ToolCallRequest("get_weather", ujson.Obj("city" -> "Paris"))
val requests = Seq(request, ToolCallRequest("get_weather", ujson.Obj("city" -> "Rome")))

for {
  registry <- ToolRegistry.of(myTools) // your ToolFunctions
  policy   <- ToolRetryPolicy(maxAttempts = 3, baseDelay = 200.millis, backoffFactor = 2.0)
  fourAtATime <- ToolExecutionStrategy.parallelWithLimit(4)
  config = ToolExecutionConfig(timeout = Some(5.seconds), retryPolicy = Some(policy))
} yield {
  ToolExecutor.execute(registry, request, config)      // blocks the calling thread
  ToolExecutor.executeAsync(registry, request, config) // Future
  ToolExecutor.executeAll(registry, requests, fourAtATime, config)
}

ToolExecutor (experimental) works on any ToolRegistry: every attempt goes through the registry’s own execute, so an MCPToolRegistry’s remote tools get the same timeout and retries. ToolRetryPolicy(...) and ToolExecutionStrategy.parallelWithLimit(n) return a Result: a value out of range is a ValidationError, not an exception.

  • What is retried. A Timeout, and an ExecutionError whose cause is an IOException or a TimeoutException. Not retried: an unknown tool, invalid or null arguments, a tool’s own error result, and a cancellation. maxAttempts counts the first try.
  • How long it waits. Before retry n the wait is baseDelay * backoffFactor^(n-1), so the first retry waits baseDelay, and never more than maxDelay (30 seconds unless you set it). Each attempt gets its own timeout.
  • Jitter. Many callers retrying a failing backend on the same schedule hit it again at the same moment. Set jitter (or .withJitter) to a fraction from 0.0 to 1.0 to randomise each wait: it is drawn uniformly between (1 - jitter) * d and d, where d is the wait above, so 0.5 is “equal jitter” and 1.0 is “full jitter”. The default, 0.0, keeps the exact schedule; the wait is never longer than without jitter.
  • executeAsync and executeAll hold no thread while backing off. An attempt occupies a thread of your ExecutionContext for as long as it runs; the wait between attempts is a scheduled delay, and the next attempt is dispatched to your ExecutionContext when it elapses. A small pool therefore keeps serving other work while many calls wait to retry. (Six calls that each fail once and back off 0.8 s finish in about 0.8 s on a two-thread pool; a sleeping backoff needs one 0.8 s wait per wave of two.)
  • execute waits on the calling thread. A synchronous caller has nothing to resume, so it blocks for the backoff. The wait is interruptible: if the thread is interrupted while it waits, the call ends as ToolCallError.Cancelled (the interrupt flag is left set) and is not retried.

Circuit Breaker

Three states: Closed (normal), Open (failing fast), Half-Open (testing recovery).

Configuration:

1
2
3
4
5
CircuitBreakerConfig(
  failureThreshold = 5,      // Open after 5 consecutive failures
  recoveryTimeout = 30.seconds,  // Wait 30s before testing recovery
  successThreshold = 2       // Close after 2 successes in half-open
)

Monitoring

1
2
3
4
5
6
7
8
9
10
11
val reliableClient = ReliableClient(baseClient, "openai", ReliabilityConfig.default)

// Check circuit breaker state
reliableClient.currentCircuitState match {
  case CircuitState.Closed   => println("Circuit healthy")
  case CircuitState.Open     => println("Circuit open - failing fast")
  case CircuitState.HalfOpen => println("Circuit testing recovery")
}

// Reset for testing (not for production use)
reliableClient.resetCircuitBreaker()

Metrics Integration

Track reliability metrics with any MetricsCollector:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import org.llm4s.metrics.{ Metric, MetricsCollector, Outcome }
import org.llm4s.reliability.{ ReliabilityConfig, ReliabilityMetrics, ReliableClient }
import scala.concurrent.duration.FiniteDuration

class MyMetricsCollector extends MetricsCollector {
  // ReliableClient records its retries, circuit-breaker transitions and errors as ReliabilityMetrics
  override def increment(metric: Metric.Counter, labelValues: Seq[String], amount: Double): Unit =
    (metric, labelValues) match {
      case (ReliabilityMetrics.Retries, Seq(provider)) =>
        println(s"$provider: Retry")
      case (ReliabilityMetrics.CircuitBreakerTransitions, Seq(provider, newState)) =>
        println(s"$provider: Circuit breaker → $newState")
      case _ => ()
    }

  // The three methods without a default: per-call latency, tokens and cost
  override def observeRequest(provider: String, model: String, outcome: Outcome, duration: FiniteDuration): Unit = ()
  override def addTokens(provider: String, model: String, inputTokens: Long, outputTokens: Long): Unit = ()
  override def recordCost(provider: String, model: String, costUsd: Double): Unit = ()
}

val metrics = new MyMetricsCollector
val client  = ReliableClient(baseClient, "openai", ReliabilityConfig.default).withMetrics(metrics)

ReliableClient records three counters, declared in ReliabilityMetrics and recorded through the collector’s generic increment: Retries (label provider), CircuitBreakerTransitions (provider, state: open, closed or half-open) and Errors (provider, error_type). A backend that implements increment exports them with no further code: PrometheusMetrics as llm4s_retries_total, llm4s_circuit_breaker_transitions_total and llm4s_reliability_errors_total, MicrometerMetrics under the same names. increment defaults to a no-op; observeRequest, addTokens and recordCost must be implemented. To also get per-call latency and token metrics from the provider client, pass the same collector to LLMConnect.getClient(providerConfig, LlmClientOptions(metrics = metrics)). Both layers then report a failed call: the provider client once per attempt (observeRequest) and ReliableClient once for the final failure (ReliabilityMetrics.Errors). Both backends keep the two apart (llm4s_errors_total and llm4s_reliability_errors_total), so neither counts a failure twice; a collector of your own should do the same.

Error Handling

The reliability layer automatically retries these errors:

  • ✅ RateLimitError - Respects Retry-After header
  • ✅ TimeoutError - Network timeouts
  • ✅ ServiceError with a retryable status - any 5xx, 429 or 408; respects a 503’s Retry-After header
  • ✅ NetworkError - Connection failures
  • ✅ ExecutionError - transient execution failures

Non-retryable errors (fail immediately):

  • ❌ AuthenticationError - Bad API key
  • ❌ ValidationError - Invalid input
  • ❌ ConfigurationError - Client misconfiguration
  • ❌ ServiceError with any other 4xx status - the request itself is wrong, so repeating it cannot succeed
  • ❌ ContextLengthError, ModelNotFoundError - the request does not fit the model, or names one the provider does not know
  • ❌ OptimisticLockFailure - the caller must re-read the record first
  • ❌ CircuitOpenError - worth sending after its remaining time, but repeating the call at once is what an open circuit prevents
  • ❌ CancelledError - the caller stopped the call

One rule. Automatic retry is LLMError.isRetryable: whether repeating the identical request may succeed. RetryPolicy.isRetryable, which ReliableClient applies, and an agent graph node’s default retry both read it, so they cannot disagree about an error, and neither can your own code. RetryPolicy.custom(attempts, delayFn) uses the same rule unless you pass your own retryableFn, so a policy that customises only the delay retries exactly what the other policies retry.

Best Practices

1. Use Default Configuration First

1
2
// Start here (pass providerConfig.providerId.asString when you loaded the client from config)
val client = ReliableClient(baseClient, "openai", ReliabilityConfig.default)

Only customize if you have specific requirements.

2. Monitor Circuit Breaker State

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import org.llm4s.metrics.{ Metric, MetricsCollector, Outcome }
import org.llm4s.reliability.ReliabilityMetrics
import org.slf4j.LoggerFactory
import scala.concurrent.duration.FiniteDuration

// Your paging or chat-ops integration
trait Alerting { def sendAlert(message: String): Unit }

// In production, log circuit breaker transitions
class ProductionMetrics(alerting: Alerting) extends MetricsCollector {
  private val logger = LoggerFactory.getLogger(getClass)

  override def increment(metric: Metric.Counter, labelValues: Seq[String], amount: Double): Unit =
    (metric, labelValues) match {
      case (ReliabilityMetrics.CircuitBreakerTransitions, Seq(provider, newState)) =>
        logger.warn(s"Circuit breaker for $provider transitioned to $newState")
        alerting.sendAlert(s"Circuit breaker: $provider → $newState")
      case _ => ()
    }

  override def observeRequest(provider: String, model: String, outcome: Outcome, duration: FiniteDuration): Unit = ()
  override def addTokens(provider: String, model: String, inputTokens: Long, outputTokens: Long): Unit = ()
  override def recordCost(provider: String, model: String, costUsd: Double): Unit = ()
}

3. Set Appropriate Deadlines

1
2
3
4
5
// Long-running tasks
ReliabilityConfig.default.withDeadline(10.minutes)

// Real-time interactions
ReliabilityConfig.default.withDeadline(30.seconds)

4. Disable for Testing

1
2
3
4
5
6
7
8
9
import org.llm4s.testkit.{ Reply, ScriptedLLMClient } // llm4s-testkit

// In tests, disable reliability for faster failures
val scripted = ScriptedLLMClient.sequence(Reply.text("Hello"))
val testClient = ReliableClient(
  underlying = scripted,
  providerName = "test",
  config = ReliabilityConfig.disabled
)

Advanced Patterns

Pattern 1: Different Configs Per Environment

1
2
3
4
5
6
7
8
9
10
11
12
object ReliabilityProfiles {
  def forEnvironment(env: String): ReliabilityConfig = env match {
    case "production" => ReliabilityConfig.default
    case "staging"    => ReliabilityConfig.aggressive
    case "development" => ReliabilityConfig.disabled
    case _ => ReliabilityConfig.conservative
  }
}

val appEnv = "staging" // from your application's own configuration
val config = ReliabilityProfiles.forEnvironment(appEnv)
val client = ReliableClient(baseClient, "openai", config)

Pattern 2: Provider-Specific Configurations

1
2
3
4
5
6
7
8
9
10
11
12
def configForProvider(provider: String): ReliabilityConfig = provider match {
  case "openai" | "anthropic" =>
    // Reliable services: fewer retries
    ReliabilityConfig.conservative
    
  case "ollama" =>
    // Local service: more aggressive retries, no circuit breaker
    ReliabilityConfig.aggressive.withCircuitBreaker(CircuitBreakerConfig.disabled)
    
  case _ =>
    ReliabilityConfig.default
}

Pattern 3: Operation-Specific Timeouts

1
2
3
4
5
6
7
// Long-running analysis
val analysisConfig = ReliabilityConfig.default.withDeadline(10.minutes)
val analysisClient = ReliableClient(baseClient, "openai", analysisConfig)

// Real-time chat
val chatConfig = ReliabilityConfig.default.withDeadline(30.seconds)
val chatClient = ReliableClient(baseClient, "openai", chatConfig)

Pattern 4: Graceful Degradation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import org.llm4s.config.Llm4sConfig
import org.llm4s.llmconnect.{ LLMClient, LLMConnect }
import org.llm4s.llmconnect.model.{ Completion, Conversation }
import org.llm4s.model.ModelRegistryService
import org.llm4s.reliability.{ ReliabilityConfig, ReliableClient }
import org.llm4s.types.Result
import org.llm4s.types.ProviderModelTypes.ProviderName
import org.slf4j.LoggerFactory

val logger = LoggerFactory.getLogger("fallback")

def callWithFallback(
  primaryClient: LLMClient,
  fallbackClient: LLMClient,
  conversation: Conversation
): Result[Completion] = {
  primaryClient.complete(conversation) match {
    case Right(completion) => Right(completion)
    case Left(error) =>
      logger.warn(s"Primary failed: ${error.message}, trying fallback")
      fallbackClient.complete(conversation)
  }
}

// Usage
for
  registry        <- Llm4sConfig.modelRegistryService()
  given ModelRegistryService = registry
  openAIConfig    <- Llm4sConfig.provider(ProviderName("openai-main"))
  anthropicConfig <- Llm4sConfig.provider(ProviderName("claude"))
  openAIBase      <- LLMConnect.getClient(openAIConfig)
  anthropicBase   <- LLMConnect.getClient(anthropicConfig)
  openAI    = ReliableClient(openAIBase, "openai", ReliabilityConfig.default)
  anthropic = ReliableClient(anthropicBase, "anthropic", ReliabilityConfig.default)
  completion <- callWithFallback(openAI, anthropic, conversation)
yield completion

Pattern 5: Circuit Breaker Monitoring

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import org.llm4s.metrics.{ Metric, MetricsCollector, Outcome }
import org.llm4s.reliability.ReliabilityMetrics
import org.slf4j.LoggerFactory
import scala.collection.mutable
import scala.concurrent.duration.FiniteDuration

// Your paging or chat-ops integration
trait Alerting {
  def sendCritical(message: String): Unit
  def sendInfo(message: String): Unit
}

class ProductionMetrics(alerting: Alerting) extends MetricsCollector {
  private val logger            = LoggerFactory.getLogger(getClass)
  private val circuitOpenAlerts = mutable.Set[String]()
  
  override def increment(metric: Metric.Counter, labelValues: Seq[String], amount: Double): Unit =
    (metric, labelValues) match {
      case (ReliabilityMetrics.CircuitBreakerTransitions, Seq(provider, newState)) => transitioned(provider, newState)
      case _                                                                       => ()
    }

  private def transitioned(provider: String, newState: String): Unit = {
    newState match {
      case "open" =>
        if (!circuitOpenAlerts.contains(provider)) {
          alerting.sendCritical(s"Circuit breaker OPEN for $provider")
          circuitOpenAlerts += provider
        }
        
      case "closed" =>
        if (circuitOpenAlerts.contains(provider)) {
          alerting.sendInfo(s"Circuit breaker CLOSED for $provider - recovered")
          circuitOpenAlerts -= provider
        }
        
      case "half-open" =>
        logger.info(s"Circuit breaker testing recovery for $provider")

      case _ => ()
    }
  }

  override def observeRequest(provider: String, model: String, outcome: Outcome, duration: FiniteDuration): Unit = ()
  override def addTokens(provider: String, model: String, inputTokens: Long, outputTokens: Long): Unit = ()
  override def recordCost(provider: String, model: String, costUsd: Double): Unit = ()
}

Troubleshooting

Issue: Too Many Retries

Symptoms: Operations take too long, excessive API calls

Solution:

1
2
3
4
5
6
7
// Reduce retry attempts
val config = ReliabilityConfig.default.withRetryPolicy(
  RetryPolicy.exponentialBackoff(maxAttempts = 2)
)

// Or disable for specific operations
val noReliability = ReliabilityConfig.disabled

Issue: Circuit Breaker Opens Too Quickly

Symptoms: Circuit opens during temporary issues, failing valid requests

Solution:

1
2
3
4
5
6
7
8
// Increase failure threshold
val config = ReliabilityConfig.default.withCircuitBreaker(
  CircuitBreakerConfig(
    failureThreshold = 10,  // More failures before opening
    recoveryTimeout = 30.seconds,
    successThreshold = 3     // More successes before closing
  )
)

Issue: Timeouts Too Aggressive

Symptoms: Operations frequently timeout, but would succeed with more time

Solution:

1
2
3
4
5
// Increase deadline
val config = ReliabilityConfig.default.withDeadline(5.minutes)

// Or remove deadline entirely
val noDeadline = ReliabilityConfig.default.withDeadline(None)

Issue: Rate Limits Not Respected

Symptoms: Getting 429 errors despite retries

Cause: Provider returns rate limit but client retries too quickly

Solution: The framework automatically respects Retry-After headers. If still seeing issues:

1
2
3
4
5
6
7
8
// Use longer base delay
val config = ReliabilityConfig.default.withRetryPolicy(
  RetryPolicy.exponentialBackoff(
    maxAttempts = 3,
    baseDelay = 5.seconds,  // Start with longer delay
    maxDelay = 60.seconds
  )
)

To stay under the provider’s quota in the first place, enable local rate limiting. ReliableClient applies it itself, taking a token before every attempt (retries included):

1
2
3
4
val config = ReliabilityConfig.default.withRateLimit(
  RateLimitConfig(enabled = true, requestsPerMinute = 60, burstCapacity = 10)
)
val client = ReliableClient(baseClient, "openai", config)

A request rejected locally fails with a RateLimitError of origin RateLimitOrigin.LocalThrottle - it never reached the provider - and records one ErrorKind.RateLimit metric.

Issue: Circuit Breaker Never Closes

Symptoms: Circuit stuck in open state, manual intervention needed

Diagnosis:

1
2
3
4
5
val reliableClient = ReliableClient(baseClient, "openai", ReliabilityConfig.default)
reliableClient.currentCircuitState // Check state

// For emergencies only (not for production automation)
reliableClient.resetCircuitBreaker()

Solution: fix the underlying service issue and wait for auto-recovery: the circuit tests recovery by itself after recoveryTimeout. Reset it by hand only in an emergency.

Adding it to an existing client

Wrapping a client

Before:

1
2
3
4
5
6
7
val clientResult =
  for
    providerConfig <- Llm4sConfig.defaultProvider()
    registry       <- Llm4sConfig.modelRegistryService()
    given ModelRegistryService = registry
    client <- LLMConnect.getClient(providerConfig)
  yield client

After:

1
2
3
4
5
6
7
val clientResult =
  for
    providerConfig <- Llm4sConfig.defaultProvider()
    registry       <- Llm4sConfig.modelRegistryService()
    given ModelRegistryService = registry
    client <- LLMConnect.getClient(providerConfig)
  yield ReliableClient(client, providerConfig.providerId.asString, ReliabilityConfig.default)

ReliableClient is an LLMClient, so nothing that uses the client changes.

Testing Strategies

Unit Tests (Disable Reliability):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import org.llm4s.reliability.{ ReliabilityConfig, ReliableClient }
import org.llm4s.testkit.{ Reply, ScriptedLLMClient } // llm4s-testkit
import org.scalatest.flatspec.AnyFlatSpec

class MyServiceTest extends AnyFlatSpec {
  val scripted = ScriptedLLMClient.sequence(Reply.text("A scripted answer"))

  // No retries in tests for fast failures
  val testClient = ReliableClient(scripted, "test", ReliabilityConfig.disabled)

  "MyService" should "handle LLM responses" in {
    // Test logic
  }
}

Integration Tests (Verify Reliability):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import org.llm4s.error.RateLimitError
import org.llm4s.llmconnect.model.{ Conversation, UserMessage }
import org.llm4s.reliability.{ ReliabilityConfig, ReliableClient, RetryPolicy }
import org.llm4s.testkit.{ Reply, ScriptedLLMClient } // llm4s-testkit
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import scala.concurrent.duration._

class ReliabilityIntegrationTest extends AnyFlatSpec with Matchers {
  "ReliableClient" should "retry on rate limits" in {
    // Two rate-limit failures, then an answer
    val scripted = ScriptedLLMClient.sequence(
      Reply.failure(RateLimitError("test")),
      Reply.failure(RateLimitError("test")),
      Reply.text("Recovered")
    )
    // A short fixed delay keeps the test fast
    val config         = ReliabilityConfig.default.withRetryPolicy(RetryPolicy.fixedDelay(maxAttempts = 3, delay = 10.millis))
    val reliableClient = ReliableClient(scripted, "test", config)

    val result = reliableClient.complete(Conversation(Seq(UserMessage("Hello"))))

    result.map(_.content) shouldBe Right("Recovered")
    scripted.callCount shouldBe 3 // Verify it retried
  }
}

Performance Considerations

Latency Impact

Without Reliability:

  • Single request: 100ms (API latency only)
  • Failed request: 100ms + error handling

With Reliability (Success):

  • Single request: 100ms + minimal overhead
  • Failed request: 100ms + retries + backoff delays

Example Retry Timeline:

1
2
3
4
5
6
Attempt 1: 0ms → failure at 100ms
Delay: 1000ms
Attempt 2: 1100ms → failure at 1200ms  
Delay: 2000ms
Attempt 3: 3200ms → success at 3300ms
Total: 3300ms (3.3s)

Memory Footprint

Per ReliableClient:

  • Circuit breaker state: atomic integers and references for thread-safe state management
  • Configuration: immutable case classes
  • Memory overhead is minimal and designed to be efficient

Safe to wrap many clients without memory concerns.

Thread Safety

All reliability features are thread-safe:

  • Circuit breaker state uses AtomicInteger and AtomicReference for safe concurrent access
  • All state transitions are atomic using compare-and-set operations
  • Metrics collection is caller-controlled
  • Safe to share ReliableClient instances across threads

Best Practices

  1. Reuse Clients: Create once, use many times
  2. Set Appropriate Deadlines: Balance UX vs. success rate
  3. Monitor Circuit Breaker: Alert on open state
  4. Log Retry Attempts: Track retry frequency in production
  5. Test Failure Scenarios: Verify retry logic with mocks

Complete Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
import org.llm4s.reliability.{ CircuitBreakerConfig, ReliableClient, ReliabilityConfig, RetryPolicy }
import org.llm4s.llmconnect.{ LLMConnect, LlmClientOptions }
import org.llm4s.model.ModelRegistryService
import org.llm4s.llmconnect.model.{ Conversation, UserMessage, CompletionOptions }
import org.llm4s.metrics.{ Metric, MetricsCollector, Outcome }
import org.llm4s.reliability.ReliabilityMetrics
import org.llm4s.config.Llm4sConfig
import scala.concurrent.duration._

object ProductionExample {
  def main(args: Array[String]): Unit = {
    // Production metrics with alerting
    val metrics = new ProductionMetrics()

    // Production reliability config
    val reliabilityConfig = ReliabilityConfig(
      retryPolicy = RetryPolicy.exponentialBackoff(
        maxAttempts = 5,
        baseDelay = 1.second,
        maxDelay = 32.seconds
      ),
      circuitBreaker = CircuitBreakerConfig(
        failureThreshold = 5,
        recoveryTimeout = 30.seconds,
        successThreshold = 2
      ),
      deadline = Some(3.minutes)
    )

    // Create reliable client using Llm4sConfig to load provider configuration
    // (the default named section in application.conf, e.g. provider = "openai"
    // whose key comes from OPENAI_API_KEY - see getting-started/configuration)
    val clientResult = for {
      providerConfig <- Llm4sConfig.defaultProvider()
      registry       <- Llm4sConfig.modelRegistryService()
      given ModelRegistryService = registry
      baseClient     <- LLMConnect.getClient(providerConfig, LlmClientOptions(metrics = metrics))
    } yield ReliableClient(baseClient, providerConfig.providerId.asString, reliabilityConfig).withMetrics(metrics)

    clientResult match {
      case Right(client) =>
        try {
          val conversation = Conversation(Seq(
            UserMessage("Analyze this production incident...")
          ))

          val startTime = System.currentTimeMillis()
          
          client.complete(conversation) match {
            case Right(completion) =>
              val duration = System.currentTimeMillis() - startTime
              println(s"✅ Success after ${duration}ms")
              println(s"Response: ${completion.content.take(100)}...")

            case Left(error) =>
              val duration = System.currentTimeMillis() - startTime
              println(s"❌ Failed after ${duration}ms: ${error.message}")
              // Trigger fallback logic, alerting, etc.
          }
        } finally {
          client.close()
        }

      case Left(error) =>
        println(s"❌ Failed to create client: ${error.message}")
    }
  }

  class ProductionMetrics extends MetricsCollector {
    private var retryCount = 0
    
    // what ReliableClient records, by metric
    override def increment(metric: Metric.Counter, labelValues: Seq[String], amount: Double): Unit =
      (metric, labelValues) match {
        case (ReliabilityMetrics.Retries, Seq(provider))                             => retried(provider)
        case (ReliabilityMetrics.CircuitBreakerTransitions, Seq(provider, newState)) => transitioned(provider, newState)
        case (ReliabilityMetrics.Errors, Seq(provider, errorType)) => println(s"❌ Error: $errorType for $provider")
        case _                                                     => ()
      }

    private def retried(provider: String): Unit = {
      retryCount += 1
      println(s"Retry for $provider (total retries: $retryCount)")
      
      // Alert if retry rate is high
      if (retryCount > 100) {
        // alerting.sendWarning(s"High retry rate: $retryCount retries")
      }
    }

    private def transitioned(provider: String, newState: String): Unit = {
      println(s"Circuit breaker: $provider → $newState")
      
      newState match {
        case "open" =>
          // alerting.sendCritical(s"Circuit breaker OPEN for $provider")
          println(s"❌ CRITICAL: Circuit open for $provider")
          
        case "closed" =>
          // alerting.sendInfo(s"Circuit breaker recovered for $provider")
          println(s"✅ Circuit recovered for $provider")
          
        case _ => // half-open
      }
    }

    override def observeRequest(
      provider: String,
      model: String,
      outcome: Outcome,
      duration: FiniteDuration
    ): Unit = {
      // Send to metrics backend (Prometheus, Datadog, etc.)
      outcome match {
        case Outcome.Success =>
          println(s"✅ Request succeeded in ${duration.toMillis}ms")
        case Outcome.Error(kind) =>
          println(s"❌ Request failed with $kind in ${duration.toMillis}ms")
      }
    }

    override def addTokens(
      provider: String,
      model: String,
      inputTokens: Long,
      outputTokens: Long
    ): Unit = {
      println(s"Tokens: $inputTokens in, $outputTokens out")
    }

    override def recordCost(
      provider: String,
      model: String,
      costUsd: Double
    ): Unit = {
      println(f"Cost: $$${costUsd}%.4f")
    }
  }
}

API Reference

ReliabilityConfig

1
2
3
4
5
6
7
final case class ReliabilityConfig private (
  retryPolicy: RetryPolicy = RetryPolicy.exponentialBackoff(),
  circuitBreaker: CircuitBreakerConfig = CircuitBreakerConfig.default,
  rateLimit: RateLimitConfig = RateLimitConfig.disabled,
  deadline: Option[FiniteDuration] = Some(5.minutes),
  enabled: Boolean = true
)

Build one with ReliabilityConfig(...) (every argument has the default shown) or start from a preset, and change it with the with* setters: the constructor and .copy are private, so fields can be added without breaking callers. The same holds for CircuitBreakerConfig and RateLimitConfig below.

Setters: withRetryPolicy, withCircuitBreaker, withRateLimit, withDeadline, withDeadline(None), withEnabled. validate returns the configuration, or a ValidationError naming the first setting a client cannot run with (a failureThreshold or burstCapacity below 1, a negative requestsPerMinute); a ReliableClient given such a configuration returns that error from every call and from validate().

Factory Methods:

  • ReliabilityConfig.default - Recommended starting point
  • ReliabilityConfig.conservative - Fewer retries, longer timeouts
  • ReliabilityConfig.aggressive - More retries, shorter timeouts
  • ReliabilityConfig.disabled - No reliability features (testing)

RetryPolicy

1
2
3
4
5
sealed trait RetryPolicy {
  def maxAttempts: Int
  def delayFor(attemptNumber: Int, error: LLMError): FiniteDuration
  def isRetryable(error: LLMError): Boolean // default: error.isRetryable
}

Factory Methods:

  • RetryPolicy.exponentialBackoff(...) - 2^n * baseDelay
  • RetryPolicy.linearBackoff(...) - n * baseDelay
  • RetryPolicy.fixedDelay(...) - constant delay
  • RetryPolicy.noRetry - Fail immediately
  • RetryPolicy.custom(...) - User-defined logic

CircuitBreakerConfig

1
2
3
4
5
final case class CircuitBreakerConfig private (
  failureThreshold: Int = 5,
  recoveryTimeout: FiniteDuration = 30.seconds,
  successThreshold: Int = 2
)

Factory Methods:

  • CircuitBreakerConfig.default - 5 failures, 30s recovery
  • CircuitBreakerConfig.conservative - 3 failures, 60s recovery
  • CircuitBreakerConfig.aggressive - 10 failures, 15s recovery
  • CircuitBreakerConfig.disabled - Never opens (testing)

RateLimitConfig

1
2
3
4
5
final case class RateLimitConfig private (
  enabled: Boolean = false,
  requestsPerMinute: Int = 60,
  burstCapacity: Int = 60
)

RateLimitConfig.disabled is the default, and RateLimitConfig.default is the same value (RateLimitConfig()): turn it on with withEnabled(true) or RateLimitConfig(enabled = true). Builders: withRequestsPerMinute, withBurstCapacity, withEnabled.

ReliableClient

1
2
3
4
5
6
7
8
9
10
11
12
object ReliableClient {
  def apply(
    underlying: LLMClient,
    providerName: String,
    config: ReliabilityConfig = ReliabilityConfig.default
  ): ReliableClient
}

// final class ReliableClient extends LLMClient; its constructor is private
def withMetrics(collector: MetricsCollector): ReliableClient   // a new client: call it where the client is built
def currentCircuitState: CircuitState   // Closed | Open | HalfOpen
def resetCircuitBreaker(): Unit         // testing / emergencies only

Next steps

  1. Start with ReliabilityConfig.default.
  2. Monitor circuit breaker transitions in production.
  3. Tune retry attempts from the failure rates you observe.
  4. Set deadlines that suit each use case.
  5. Send the metrics to your backend: see Monitoring.

See also the source and the Providers guide.