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 inCLOSEDstate until failure rates or timeouts cross a threshold. The breaker then trips toOPENto fail fast (or route to a fallback model) before testing recovery with limited probes inHALF_OPEN. - Per-provider and per-model isolation: Keep separate circuit breakers for each provider or model endpoint (such as OpenAI
gpt-4ovs. Anthropicclaude-sonnet) so an outage on one model does not block healthy ones.
Steps
- Define failure and slow-call rules: Count network errors,
5xxserver responses, and request timeouts as failures, while treating valid4xxuser errors (like invalid prompts) separately so bad inputs do not trip the circuit. - 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). - 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. - 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
AbortControllertimeout 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, andHALF_OPENso your team spots provider outages immediately.
You must log in or register to comment.
