AI Agent Circuit Breaker 2026

🤖 Agents 2026-07-16 · Updated 2026-11-25 4 min read

The worst batch job is the one where the upstream starts returning 429 and 5xx while the retry loop keeps hammering it every few milliseconds. A circuit breaker cuts power after a failure threshold, fails fast, then sends a single probe after a cooldown.

📜 Table of Contents

📖 Keep reading

Circuit Breakers for AI Agents

An upstream starts returning 429 and 5xx at 3am. Your retry loop keeps hammering it, and the overnight bill covers a month of normal usage. A circuit breaker stops that: trip after a failure threshold, fail fast, probe once after a cooldown.

Three states

State Behaviour Enter when Leave when
Closed Requests pass, failures counted Start Threshold reached
Open Reject immediately, no upstream call Failures exceed threshold Cooldown elapses
Half-open Allow a few probes Cooldown over Probe succeeds → closed; fails → open

Half-open is what makes it usable. Without it a breaker either never trips or never recovers.

Parameters

Parameter Typical Note
Failure threshold 5-10 Too low trips on noise
Window 30-60 s Count failures inside the window, not forever
Cooldown from 30 s Honour Retry-After on 429
Probes in half-open 1-3 One is enough; more floods a recovering service
Per-call timeout 30-60 s Streaming measures time to first byte separately

Minimal implementation

import time, threading

class CircuitBreaker:
    def __init__(self, fail_threshold=5, cooldown=30, half_open_max=1):
        self.fail_threshold = fail_threshold
        self.cooldown = cooldown
        self.half_open_max = half_open_max
        self.failures = 0
        self.state = "closed"
        self.opened_at = 0.0
        self.half_open_calls = 0
        self._lock = threading.Lock()

    def allow(self):
        with self._lock:
            if self.state == "closed":
                return True
            if self.state == "open":
                if time.monotonic() - self.opened_at >= self.cooldown:
                    self.state = "half_open"
                    self.half_open_calls = 0
                else:
                    return False
            if self.half_open_calls >= self.half_open_max:
                return False
            self.half_open_calls += 1
            return True

    def record(self, ok):
        with self._lock:
            if ok:
                self.failures = 0
                self.state = "closed"
                self.half_open_calls = 0
                return
            self.failures += 1
            if self.state == "half_open" or self.failures >= self.fail_threshold:
                self.state = "open"
                self.opened_at = time.monotonic()

Which errors count

Counting a 400 as an outage lets one malformed request black out the whole path.

Error Counts Why
Connect/read timeout Yes Upstream is unreachable
429 Yes Quota is gone; retrying makes it worse
5xx Yes Server-side failure
400 No Caller's fault
401 / 403 No Retrying cannot help
Content-policy refusal No Business outcome, not failure

Retry and breaker divide the work

Retry handles transient failures: at most 2-3 attempts, exponential backoff with jitter, idempotent calls only. The breaker handles sustained outage. Order: check breaker, then retry, then record the result. Retry without a breaker is the 3am story; a breaker without retry fails on a single blip.

Isolate by dimension

One global breaker is an anti-pattern. Keep instances keyed by provider:model, optionally per tenant. An OpenAI outage should not disable a local Ollama fallback, and one customer exhausting quota must not affect others.

After the breaker trips: fallback chain

  1. Alternate provider or a smaller model
  2. Cached or rule-based answer, clearly labelled
  3. Explicit "busy, retry later" with a queue

Log every fallback. Silent degradation is worse than an error, because users assume the answer is normal.

Three metrics

circuit_state (0/1/2) per provider, rejected_total (requests saved), and open_duration (how long it stays open, which calibrates the cooldown). Alert once on transition to open, not on every rejection.

FAQ

What threshold? Depends on volume. Low-traffic services can use 5 consecutive failures; high-traffic ones should use "failure rate above 50% with at least 20 requests in the window".

Fixed cooldown? Prefer Retry-After, otherwise fixed with doubling up to five minutes, reset on the first success.

Shared state across processes? Local Redis with INCR plus expiry for multi-host setups; accept the extra network hop.

Will it trip on normal variance? A failure-rate window is steadier than a consecutive count, and a single probe makes a false trip cheap.

Related Articles
2026-08-06
Awesome MCP Servers (91,854 Stars) 2026: The Definitive Curated List of 1,000+ Model Context Protocol Servers
2026-07-17
AI Agent Stream Processing 2026
2026-08-02
No-Code AI Agent Builder 2026: Dify vs Langflow vs n8n - Build Agents Without Writing Code
2026-07-16
AI Agent Monitoring Platforms Compared 2026: LangFuse vs Datadog vs Helicone
2026-07-16
Smolagents Tutorial Beginners 2026
2026-07-22
AI Agent Prompt Engineering 2026

Written by our editorial team; tools listed here are tested or verified against public sources. Links point to official sites or GitHub repos for reference only — no paid placements.

💬 Comments (0)

No comments yet. Be the first!

Login to comment