Introduction
In our previous lesson, we built a robust retry mechanism with exponential backoff and jitter. This pattern is essential for handling transient failures—temporary blips in network or service availability. However, what happens when a dependency, like an LLM API or a critical tool, experiences a more prolonged outage? Continuously retrying against a dead service is not only futile but also actively harmful. It consumes resources (threads, connections, CPU) in your own application and can contribute to a "thundering herd" problem, preventing the downstream service from recovering. This leads to cascading failures, where a single component's failure brings down the entire system.
To address this, we turn to another classic pattern from distributed systems: the Circuit Breaker. This lesson will guide you through integrating circuit breakers for your agent's external service dependencies to prevent such cascading failures. Given your background in distributed systems, the core state machine will be familiar. Our focus will be on adapting this pattern to the unique failure modes of AI systems and implementing it from first principles for a production-grade agent architecture.
1. The Circuit Breaker Pattern: A State Machine for Resilience
At its heart, the circuit breaker is a stateful proxy that wraps calls to a remote service. It monitors for failures and, if they exceed a certain threshold, it "trips" or "opens," causing subsequent calls to fail immediately without even attempting to contact the unavailable service. This "fail-fast" behavior is the key to preventing cascading failures.
The pattern is defined by three primary states:
- CLOSED: The default state. All requests are allowed to pass through to the downstream service. The circuit breaker monitors for failures. If the failure count exceeds a configured threshold within a specific time window, the circuit transitions to the OPEN state.
- OPEN: The circuit is "tripped." For a configured
recovery_timeoutperiod, all requests to the service are immediately rejected with an error without making a network call. This protects your application from wasting resources on calls that are destined to fail and gives the downstream service time to recover. When the timeout expires, the circuit transitions to HALF-OPEN. - HALF-OPEN: The circuit allows a limited number of "probe" requests to pass through to the downstream service. If these probes succeed, it's a sign the service has recovered, and the circuit transitions back to CLOSED. If they fail, the circuit trips again, returning to the OPEN state and resetting the recovery timer.

The following short video provides a clear, conceptual overview of this state machine in a microservices context.
Introduction to circuit breaker in microservices (for beginners)
This video, "Introduction to circuit breaker in microservices (for beginners)" by sudoCODE, offers a concise explanation of the pattern's three states and the logic behind them.
Please watch from before we move on. This segment clearly defines the Closed, Open, and Half-Open states and visualizes the state machine transitions. Then, from system has recovered, observe the pseudocode, which maps the logic for failure/success counters to each state.
2. Designing a Circuit Breaker for AI Agent Dependencies
While the core pattern is universal, implementing it for AI agents requires attention to specific details, particularly in a distributed environment where multiple agent workers might be running concurrently.
A naive in-memory implementation, where each worker process tracks state independently, is insufficient. One worker might trip its local circuit breaker while another, unaware of the broader issue, continues to hammer the failing API. To ensure all parts of your system have a consistent view of a dependency's health, a shared state backend is required. Redis is an ideal choice for this, providing fast, centralized storage for the circuit breaker's state.
The following article provides a superb, first-principles guide to designing and implementing a Redis-backed circuit breaker specifically for an LLM API. It will serve as our primary blueprint.
Claude API Circuit Breaker | Enterprise Pattern Guide
This SitePoint article details a production-grade circuit breaker implementation. It directly addresses the challenges we face.
First, read the sections The Cascade Failure Problem and Pattern Fundamentals to solidify the "why" and the core states in the context of LLM APIs. Next, focus on the design choices in the section Designing the Circuit Breaker. Pay close attention to: The architecture diagram showing how breakers isolate each provider. The argument for Redis-backed state over local in-memory state. The proposed Redis key schema (circuit:{provider_name}:...). The critical logic for defining failure conditions—distinguishing retryable provider errors (5xx, 429, timeouts) from non-retryable client errors (400, 401).
The article makes a crucial point: you must carefully define what constitutes a "failure." Tripping the circuit on a client-side error, like an invalid API key (401), would be a mistake, as it would needlessly block traffic and failover to other providers who would receive the same bad request. The circuit should only react to signals indicating the provider is unhealthy.
3. A Production-Grade Implementation Blueprint
With our design principles established, let's examine the implementation details. One of the most critical aspects of a distributed circuit breaker is ensuring state transitions are atomic. Imagine two workers simultaneously detecting a failure when the count is one below the threshold. Both might read the count, increment it, and attempt to trip the circuit, leading to a race condition.
The SitePoint article presents an elegant solution using a Redis Lua script to handle the failure recording and state transition atomically. This is a robust pattern that leverages Redis's server-side scripting capabilities to ensure correctness under concurrency.
Claude API Circuit Breaker | Enterprise Pattern Guide
We will now dive into the Python code and the underlying Redis mechanics from the same article.
First, carefully study the Python code in the section that begins with the CircuitBreaker class definition. Read through the entire class, focusing on: The __init__ method, which registers the RECORD_FAILURE_SCRIPT. The _get_state method's logic for detecting an expired OPEN state (via TTL) and transitioning to HALF_OPEN. The _record_failure method, which executes the atomic Lua script. The call method, which orchestrates the entire logic: checking the state, handling HALF_OPEN probes with a SETNX-based lock, and calling the underlying function. After reviewing the code, read the section Distributed State Management with Redis to get a deeper explanation of how the Lua script and key TTLs work together to manage the state machine atomically and reliably.
This implementation provides a complete, reusable, and production-ready CircuitBreaker class. It encapsulates all the necessary logic: state management, atomic updates, and the core call-wrapping functionality.
4. Advanced Considerations: Beyond Simple Failures
The pattern we've just designed is excellent for handling binary, availability-based failures (i.e., the service is up or down). However, agentic systems introduce more nuanced failure modes that a sophisticated circuit breaker can also address.

Consider these scenarios:
- Performance Degradation: An API isn't down, but its p99 latency has spiked from 2 seconds to 30 seconds. This can still cause cascading timeouts. A circuit breaker could be configured to trip based on latency thresholds, not just error codes.
- Quality Degradation (Semantic Failure): An LLM provider is online and fast, but it starts consistently returning malformed JSON, hallucinated facts, or responses that fail validation checks. These are not HTTP errors, but they are failures from the agent's perspective. A more advanced circuit breaker can incorporate these quality signals into its failure count.
- Cost Spikes: A runaway agent loop could cause massive, unexpected costs. A circuit breaker could be integrated with a cost-tracking module to trip if an API's cost-per-minute exceeds a budget.
These advanced concepts are discussed in the following article, which looks at the circuit breaker pattern specifically through the lens of AI agent reliability.
This article by Brandon Lincoln Hendricks explores the unique application of circuit breakers in AI systems.
Please read the sections Implementing Circuit Breakers for LLM Calls and Fallback Strategies and Graceful Degradation. As you read, note the metrics beyond simple error rates that an AI-specific circuit breaker might track, such as response time, token consumption, and semantic validation.
This idea of a "degraded" state and semantic failure monitoring moves us beyond simple availability management and into true system resilience. When a circuit opens due to a hard failure or trips to a "degraded" state due to poor performance, the natural next question is: what should the agent do instead? This brings us to the topic of our next lesson.
Conclusion
In this lesson, you've gone from the foundational principles of the circuit breaker pattern to a full-fledged, production-grade design for agentic systems. You now understand how to move beyond simple retries to protect your system from cascading failures caused by sustained dependency outages.
Key Takeaways:
- Circuit Breakers Prevent Cascading Failures: By "failing fast" when a dependency is down, they conserve resources and maintain system stability.
- The Three States: The pattern operates on a simple but powerful state machine: CLOSED (normal), OPEN (failing fast), and HALF-OPEN (probing for recovery).
- Distributed State is Crucial: For multi-worker agent systems, state must be managed centrally (e.g., in Redis) to ensure a consistent view of dependency health.
- Atomicity is Non-Negotiable: State transitions, especially failure counting, must be atomic to prevent race conditions. Redis Lua scripts are an excellent tool for this.
- AI-Specific Failures: Production-grade agent circuit breakers should consider not just HTTP errors but also latency degradation, semantic failures, and cost anomalies.
Preview of the Next Lesson:
An open circuit breaker successfully prevents a call to a failing service. But what happens next? Instead of simply returning an error, a truly resilient agent should have a backup plan. In our next lesson, we will implement fallback tool selection as a graceful degradation strategy. You'll learn how to design logic that, in the event of a primary tool's failure (as detected by our circuit breaker), automatically routes the task to a secondary tool or a different LLM provider, allowing the agent to complete its mission with reduced, but still functional, capability.