How do you implement circuit breakers for third-party LLM providers in microservices architectures? | A1Lab@HamzaM to AI & LLMEnglish • 3 days ago

How do you implement circuit breakers for third-party LLM providers in microservices architectures?

message-square
0

Overview

Third-party LLM providers can suffer sudden latency spikes, rate limits (429), or outages (5xx). A circuit breaker stops your microservices from sending doomed requests to a failing provider, preventing thread/socket exhaustion and cascading failures across your system.

  • Three-state protection (CLOSED -> OPEN -> HALF_OPEN): Requests flow normally in CLOSED state until failure rates or timeouts cross a threshold. The breaker then trips to OPEN to fail fast (or route to a fallback model) before testing recovery with limited probes in HALF_OPEN.
  • Per-provider and per-model isolation: Keep separate circuit breakers for each provider or model endpoint (such as OpenAI gpt-4o vs. Anthropic claude-sonnet) so an outage on one model does not block healthy ones.

Steps

  1. Define failure and slow-call rules: Count network errors, 5xx server responses, and request timeouts as failures, while treating valid 4xx user errors (like invalid prompts) separately so bad inputs do not trip the circuit.
  2. Track sliding-window health and trip to OPEN: Record recent outcomes over a rolling window and open the circuit when failures exceed your threshold (such as 5 failures in 10 seconds or a 50% error rate).
  3. Fail fast or route to a fallback provider while OPEN: Reject calls immediately without waiting on network timeouts, or automatically reroute traffic to a secondary LLM provider.
  4. Probe recovery in HALF_OPEN: After a cooldown period, allow a small number of test requests through; close the circuit if they succeed, or re-open immediately if any probe fails.

Example

export type CircuitState = "CLOSED" | "OPEN" | "HALF_OPEN";

export interface CircuitBreakerOptions {
  name: string;
  failureThreshold: number; // Failures needed to trip OPEN
  cooldownMs: number; // Wait time before testing HALF_OPEN
  halfOpenMaxProbes: number; // Concurrent/total probes allowed in HALF_OPEN
  timeoutMs: number; // Max latency per LLM request
}

export class CircuitOpenError extends Error {
  constructor(providerName: string) {
    super(`Circuit breaker is OPEN for LLM provider: \${providerName}`);
    this.name = "CircuitOpenError";
  }
}

export class LlmCircuitBreaker {
  private state: CircuitState = "CLOSED";
  private consecutiveFailures = 0;
  private openedAtMs = 0;
  private halfOpenProbesInFlight = 0;
  private halfOpenSuccesses = 0;

  constructor(private readonly options: CircuitBreakerOptions) {}

  getState(): CircuitState {
    if (
      this.state === "OPEN" &&
      Date.now() - this.openedAtMs >= this.options.cooldownMs
    ) {
      this.state = "HALF_OPEN";
      this.halfOpenProbesInFlight = 0;
      this.halfOpenSuccesses = 0;
    }
    return this.state;
  }

  async execute<T>(fn: (signal: AbortSignal) => Promise<T>): Promise<T> {
    const currentState = this.getState();

    if (currentState === "OPEN") {
      throw new CircuitOpenError(this.options.name);
    }

    if (currentState === "HALF_OPEN") {
      if (this.halfOpenProbesInFlight >= this.options.halfOpenMaxProbes) {
        throw new CircuitOpenError(this.options.name);
      }
      this.halfOpenProbesInFlight += 1;
    }

    const controller = new AbortController();
    const timer = setTimeout(() => controller.abort(), this.options.timeoutMs);

    try {
      const result = await fn(controller.signal);
      this.onSuccess();
      return result;
    } catch (error) {
      if (this.isTransientFailure(error)) {
        this.onFailure();
      }
      throw error;
    } finally {
      clearTimeout(timer);
      if (currentState === "HALF_OPEN" && this.halfOpenProbesInFlight > 0) {
        this.halfOpenProbesInFlight -= 1;
      }
    }
  }

  private onSuccess(): void {
    if (this.state === "HALF_OPEN") {
      this.halfOpenSuccesses += 1;
      if (this.halfOpenSuccesses >= this.options.halfOpenMaxProbes) {
        this.state = "CLOSED";
        this.consecutiveFailures = 0;
        this.halfOpenSuccesses = 0;
      }
      return;
    }

    this.consecutiveFailures = 0;
  }

  private onFailure(): void {
    if (this.state === "HALF_OPEN") {
      this.tripOpen();
      return;
    }

    this.consecutiveFailures += 1;
    if (this.consecutiveFailures >= this.options.failureThreshold) {
      this.tripOpen();
    }
  }

  private tripOpen(): void {
    this.state = "OPEN";
    this.openedAtMs = Date.now();
    this.halfOpenProbesInFlight = 0;
    this.halfOpenSuccesses = 0;
  }

  private isTransientFailure(error: unknown): boolean {
    if (error instanceof Error && error.name === "AbortError") {
      return true;
    }
    const status = (error as { status?: number })?.status;
    if (typeof status === "number") {
      return status === 429 || status >= 500;
    }
    return true; // Network / socket errors
  }
}

// Multi-provider router using per-provider circuit breakers
export class ResilientLlmRouter {
  private readonly breakers = new Map<string, LlmCircuitBreaker>();

  registerProvider(options: CircuitBreakerOptions): void {
    this.breakers.set(options.name, new LlmCircuitBreaker(options));
  }

  async callWithFallback<T>(
    providers: Array<{
      name: string;
      invoke: (signal: AbortSignal) => Promise<T>;
    }>
  ): Promise<{ provider: string; data: T }> {
    let lastError: unknown;

    for (const provider of providers) {
      const breaker = this.breakers.get(provider.name);
      if (!breaker) {
        throw new Error(`No circuit breaker registered for \${provider.name}`);
      }

      try {
        const data = await breaker.execute(provider.invoke);
        return { provider: provider.name, data };
      } catch (err) {
        lastError = err;
      }
    }

    throw lastError ?? new Error("All LLM providers failed or have OPEN circuits.");
  }
}

Tips

  • Share breaker state in Redis when scaling many pods: An in-memory breaker protects a single container, while a Redis-backed state lets all microservice replicas stop hitting a dead LLM provider together.
  • Set strict timeouts before retries: Always abort hung LLM requests with an AbortController timeout before retrying, otherwise stalled sockets will pile up and exhaust memory.
  • Emit metrics on state transitions: Log and alert whenever a breaker moves between CLOSED, OPEN, and HALF_OPEN so your team spots provider outages immediately.