← Blog

Claude API Circuit Breaker Pattern Implementation

2026-11-24 · 5 min read · SubToAPI Team

What a circuit breaker does for Claude API calls

A circuit breaker is a stateful wrapper around outbound requests that stops your application from hammering a failing dependency. When Claude API calls start timing out, returning 529 overloaded errors, or failing repeatedly, the circuit breaker "opens" and short-circuits further calls for a cooldown period, returning an immediate failure (or a fallback) instead of letting every request queue up and wait for a timeout. This protects your own service's latency and resource usage when the upstream API is degraded.

If you're searching for how to implement this pattern specifically against the Claude API, the short answer is: track failures and timeouts per endpoint, open the circuit after a threshold is crossed, reject fast while open, then probe with a limited number of test requests after a cooldown before fully closing again. Below is a working implementation you can drop into a Node.js service, plus guidance on thresholds that make sense for LLM APIs specifically (which behave differently from typical REST backends because of long response times and streaming).

Why Claude API calls need this more than typical REST calls

Three things make circuit breakers especially valuable for LLM API integrations:

The three states

A circuit breaker has three states:

  1. Closed — requests flow normally. Failures are counted.
  2. Open — too many failures occurred; all requests are rejected immediately (or routed to a fallback) without touching the API.
  3. Half-open — after a cooldown, a small number of test requests are allowed through. If they succeed, the circuit closes. If they fail, it reopens.

Implementation in Node.js

Here's a minimal, dependency-free circuit breaker tailored to Claude API calls:

class ClaudeCircuitBreaker {
  constructor({ failureThreshold = 5, cooldownMs = 30000, halfOpenMaxCalls = 2 } = {}) {
    this.failureThreshold = failureThreshold;
    this.cooldownMs = cooldownMs;
    this.halfOpenMaxCalls = halfOpenMaxCalls;
    this.state = "closed";
    this.failureCount = 0;
    this.openedAt = null;
    this.halfOpenCalls = 0;
  }

  canRequest() {
    if (this.state === "closed") return true;
    if (this.state === "open") {
      if (Date.now() - this.openedAt >= this.cooldownMs) {
        this.state = "half-open";
        this.halfOpenCalls = 0;
        return true;
      }
      return false;
    }
    // half-open
    if (this.halfOpenCalls < this.halfOpenMaxCalls) {
      this.halfOpenCalls++;
      return true;
    }
    return false;
  }

  onSuccess() {
    this.failureCount = 0;
    this.state = "closed";
  }

  onFailure() {
    this.failureCount++;
    if (this.state === "half-open") {
      this.open();
      return;
    }
    if (this.failureCount >= this.failureThreshold) {
      this.open();
    }
  }

  open() {
    this.state = "open";
    this.openedAt = Date.now();
  }
}

Wrap your actual API call with it:

const breaker = new ClaudeCircuitBreaker({
  failureThreshold: 5,
  cooldownMs: 30000,
});

async function callClaude(messages) {
  if (!breaker.canRequest()) {
    throw new Error("circuit_open: skipping call, upstream degraded");
  }

  try {
    const res = await fetch("https://api.anthropic.com/v1/messages", {
      method: "POST",
      headers: {
        "x-api-key": process.env.ANTHROPIC_API_KEY,
        "anthropic-version": "2023-06-01",
        "content-type": "application/json",
      },
      body: JSON.stringify({
        model: "claude-sonnet-4-20250514",
        max_tokens: 1024,
        messages,
      }),
      signal: AbortSignal.timeout(20000),
    });

    if (res.status === 529 || res.status >= 500) {
      breaker.onFailure();
      throw new Error(`upstream_error_${res.status}`);
    }

    const data = await res.json();
    breaker.onSuccess();
    return data;
  } catch (err) {
    breaker.onFailure();
    throw err;
  }
}

Key design decisions worth calling out:

Pairing the breaker with a fallback

A circuit breaker is most useful combined with a fallback path — a cached response, a smaller/faster model, or a queued retry for later. When canRequest() returns false, don't just throw: return a degraded response, enqueue the request for a background retry, or route to a secondary model. This is the piece most implementations skip, and it's the difference between "fails fast" and "fails usefully."

Where SubToAPI fits

If you're running Claude access through SubToAPI, you still want a circuit breaker at the application layer — it protects your service from slow dependencies regardless of which provider sits behind the endpoint. SubToAPI gives you a stable HTTPS interface (sub_live_... keys, standard JSON responses, streaming) over https://api.subtoapi.app/v1/messages, so your breaker logic doesn't need provider-specific error handling scattered across your codebase — you classify failures once against a consistent API shape. See /docs/messages and /docs/streaming for the request/response format, and /docs/quickstart to wire up a key. Plans start at the Solo tier with a free trial at /signup.

Questions

Does the circuit breaker replace retry logic? No. Retries handle transient single-request failures with backoff; the circuit breaker handles sustained failure patterns across many requests. Use both — retry a few times within a call, and let the breaker track failures across calls.

What threshold and cooldown values should I start with? A failure threshold of 5 consecutive failures and a 30-second cooldown is a reasonable default for most services. Tune based on your traffic volume — high-throughput services should use shorter windows with request-rate-based thresholds instead of raw counts.

Should the circuit breaker be per-model or global? Per-model (or per-endpoint) is almost always correct. A degraded model or region shouldn't trip the breaker for traffic going to a different model, especially if you're doing fallback model switching as part of your resilience strategy.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →