Electrical circuit breakers representing protection for failing AI agent tools
← Back to Blog
December 2026·AI Engineering·12 min read

Circuit breakers for AI agent tools: when to stop calling a failing dependency

Learn how circuit breakers stop AI agents from repeatedly calling unhealthy tools, control recovery probes and expose honest degraded outcomes.

Circuit breakers for AI agent tools stop a workflow from calling a dependency that is already showing a sustained pattern of failure. Instead of allowing every agent run to discover the same outage through another timeout, the breaker remembers recent outcomes, opens when a defined threshold is crossed and fails subsequent calls immediately.

That sounds like a standard distributed-systems pattern, but agents make the boundary harder to design. A conventional service usually calls a dependency at a known place. An agent can choose tools dynamically, retry with different arguments, re-plan around an error and create parallel branches. A broken search API can therefore turn one user request into ten doomed calls before the orchestrator admits that the dependency is unavailable.

I treat the breaker as part of the tool contract, not as a generic exception wrapper. It needs to know which operation failed, whether the failure says anything about dependency health, what the agent may do instead and how one controlled probe can verify recovery without releasing a herd of waiting runs.

What a circuit breaker does for an AI agent

A circuit breaker sits between a caller and a dependency. While the dependency appears healthy, the breaker allows calls through and observes their outcomes. When failures exceed its policy, it opens. Calls are then rejected locally until a recovery interval has passed. A limited probe is eventually allowed; successful probes close the circuit, while a failed probe opens it again.

The objective is not to repair the dependency. It is to stop spending capacity, latency and money on calls that are unlikely to succeed. Microsoft distinguishes the pattern from retrying: retries assume another attempt may succeed, while a circuit breaker prevents an operation that is currently likely to fail. The two controls belong together, but they make decisions at different timescales.

For an agent platform, the protected resource is larger than one HTTP connection. Opening a breaker can preserve:

  • model tokens that would otherwise be spent re-planning around the same outage;
  • worker slots occupied by long tool timeouts;
  • the failing provider's recovery capacity;
  • the user's deadline and the workflow's remaining retry budget;
  • downstream systems that would receive duplicate or partial actions.

A timeout on one call is evidence. An open circuit is a shared operational conclusion: calls matching this dependency and operation should not start right now.

Why tool-using agents amplify dependency failures

Agents convert failures into new decisions. That flexibility is valuable when an alternative exists, but dangerous when the model cannot tell that several tool names lead to the same unhealthy backend.

Imagine a research agent whose search request times out. It tries again with a shorter query, switches from search_web to search_news, asks a sub-agent to research the topic and then retries the original call after re-planning. If all four paths use the same provider account, one dependency incident has become a small retry storm.

Parallel runs multiply the effect. Fifty agents can each remain inside their local retry limit while the platform sends hundreds of calls to a provider that is already rejecting traffic. This is why a per-run counter is not a circuit breaker. A breaker aggregates health evidence across callers and gives them one shared decision.

The pattern complements a retry budget, which limits repeated attempts within a workflow. It also differs from load shedding, which refuses work because the platform lacks capacity. A breaker refuses one dependency path because recent evidence says that path is unhealthy.

Closed, open and half-open states

StateCall behaviorTransition
ClosedAllow calls and record qualifying outcomesOpen when the failure policy is met
OpenReject locally without touching the dependencyBecome eligible for a probe after the recovery delay
Half-openAllow only controlled probe trafficClose after enough successes; reopen on failure

Keep this state explicit. Hiding it behind a timestamp such as blocked_until makes it harder to distinguish a normally closed breaker from a recovery probe in progress. Explicit state also makes transitions auditable and testable.

The breaker state is operational state, not the agent run's business state. A run can transition to completed_degraded while the tool circuit remains open. Another run may wait for human review. Keep those state machines separate and connect them through a typed tool outcome.

Choose the right breaker identity

A single global breaker for every tool is too broad. One failing CRM integration should not disable search, email and document storage. A breaker per full URL is often too narrow: dynamic paths and query parameters fragment evidence until no key sees enough failures to open.

I define breaker identity from the smallest stable failure domain operators can act on:

provider:account:region:operation

search_vendor:primary:eu:search
crm_vendor:tenant_42:global:create_contact
llm_vendor:project_a:eu:model_family

Operation matters because read and write endpoints can fail differently. Account or tenant scope matters when a revoked credential affects one integration while the vendor remains healthy. Region matters only if traffic and health are actually isolated by region.

Do not let the model create this key from free text. The tool adapter should derive it from trusted configuration. Two aliases that reach the same backend should share a health domain when their failures are correlated.

Count health failures, not every bad outcome

A tool call can fail without proving that the dependency is unhealthy. Invalid arguments, denied permissions and a missing record usually say something about the request, not the service. Counting all non-success responses opens circuits for caller mistakes and hides bugs behind an infrastructure mechanism.

OutcomeCount toward breaker?Reason
Connection failure or timeoutUsually yesThe dependency did not complete the call
HTTP 500, 502, 503 or 504Usually yesServer or gateway health signal
HTTP 429Policy-dependentMay require a separate quota or rate-limit breaker
HTTP 400 or validation errorNoThe request should be corrected, not repeated
HTTP 401 or 403Usually noOpen a credential incident, not a vendor-health circuit
Valid empty resultNoA business outcome is not a transport failure
Schema or semantic contract violationOften yes, separatelyThe service responded but the adapter cannot safely use it

Writes require special care. A timeout may hide a successful side effect. The breaker can prevent further calls, but it cannot decide whether repeating the write is safe. Route that outcome into reconciliation for ambiguous tool results and use an idempotency key before any retry.

Record slow successes as latency evidence, but do not automatically count every slow response as failure. A separate slow-call threshold can open the breaker when tail latency makes results useless, provided the service objective defines what “too slow” means.

Use windows and thresholds that match the tool

“Open after five failures” is not a complete policy. Five failures among five calls indicate something different from five failures among ten thousand calls. The window also matters: five failures within thirty seconds are stronger evidence than five spread across a day.

A practical policy combines:

  • minimum volume before a failure rate can open the circuit;
  • rolling time or request window for recent evidence;
  • failure-rate threshold rather than only a lifetime count;
  • consecutive-failure fast path for a dependency that fails completely;
  • open duration informed by provider guidance and observed recovery;
  • success requirement for leaving half-open state.

Low-volume tools need a different policy from high-volume search. With only two calls an hour, a percentage has little meaning; consecutive failures and a short open period may be clearer. For busy dependencies, a rolling rate prevents a small number of normal errors from opening the circuit.

Do not copy thresholds from another system and call the job finished. Start with the tool's latency objective, normal error rate, provider quota and cost of a false opening. Then validate the policy under controlled fault injection.

Control recovery probes

The half-open state is where naive implementations create a second incident. If every worker notices that open_until has passed and sends a probe, the recovering dependency receives a burst precisely when it has the least spare capacity.

Elect one probe owner with an atomic compare-and-set or distributed lock. Other callers continue to receive circuit_open until the probe finishes or its lease expires. For a high-volume service, permit a very small bounded number of probes rather than reopening normal traffic at once.

A probe should use a representative, safe operation. A shallow health endpoint can return 200 while the database path needed by the agent still fails. On the other hand, probing with a non-idempotent write can create a real side effect. Prefer a documented readiness operation or a read that exercises the same critical path.

Recovery can be gradual. Close into limited concurrency, watch fresh outcomes and restore the normal limit over several windows. AWS's circuit-breaker guidance for Lambda emphasizes electing controlled half-open probes so every execution environment does not hammer the backend at once.

Return an outcome the agent cannot misread

An open breaker should not look like a generic tool exception. If the model sees “request failed,” it may call the same tool again with different wording. Return a structured outcome that the orchestrator handles before the model chooses another action:

{
  "status": "unavailable",
  "reason": "circuit_open",
  "dependency": "search_vendor:primary:eu:search",
  "retryable_by_agent": false,
  "next_probe_after": "2026-12-01T07:01:30Z",
  "allowed_fallbacks": ["cached_search", "ask_user_to_retry_later"]
}

retryable_by_agent: false is essential. The platform owns circuit recovery; the model does not. Do not expose an exact probe time if that would encourage thousands of clients to retry simultaneously. An internal orchestrator can use it while the user-facing response gives a broader, jittered expectation.

Fallbacks must be honest. Cached data should include its age. A smaller model should be allowed only when it still meets the task's quality and safety contract. If a missing tool makes the requested outcome impossible, stop and say so rather than presenting a partial answer as complete. This is a concrete form of designing for partial failure in AI automation.

Implement a shared breaker in Laravel

In a Laravel application, local process memory is insufficient when queue workers and web instances share a dependency. The state needs a shared store with atomic updates. Redis is a common fit; a database can work at lower volume when its own availability is not coupled to the protected dependency.

final class ToolCircuit
{
    public function __construct(private CircuitStore $store) {}

    public function call(string $key, Closure $operation): ToolResult
    {
        $permit = $this->store->acquirePermit($key, now());

        if ($permit === null) {
            return ToolResult::unavailable(
                reason: 'circuit_open',
                retryableByAgent: false,
            );
        }

        try {
            $result = $operation();
            $this->store->recordSuccess($permit, now());

            return $result;
        } catch (ToolHealthFailure $error) {
            $this->store->recordFailure($permit, $error->category, now());

            return ToolResult::unavailable(
                reason: 'dependency_failure',
                retryableByAgent: false,
            );
        } finally {
            $this->store->releaseProbeLease($permit);
        }
    }
}

acquirePermit should atomically read state, rotate the rolling window and elect at most one half-open probe. recordFailure should transition state only for classified health failures. Include a lease expiry so a worker crash cannot leave the circuit permanently half-open.

Keep retries inside the protected call policy. One logical tool invocation may make two short transport attempts, but the breaker should observe both the attempt-level pressure and the final invocation outcome. Never place an unbounded retry loop outside the breaker, because open decisions would then be bypassed.

Define what happens when the breaker store is unavailable. Failing open preserves tool availability but can intensify an outage. Failing closed protects the dependency but may unnecessarily disable it. The correct choice depends on side effects and risk; writes with financial or external consequences deserve a more conservative fallback than a read-only public search.

Make breaker decisions observable

A breaker can make errors disappear from dependency dashboards because calls are no longer sent. That is expected, but it means circuit state must be visible as a first-class signal.

Track at least:

  • state transitions with breaker key, policy version and reason;
  • allowed, failed and short-circuited calls by tool operation;
  • time spent open and number of half-open probes;
  • probe successes, failures and lease expiries;
  • agent outcomes caused by an open circuit: degraded, deferred, escalated or failed;
  • estimated latency, tokens and provider calls avoided;
  • false openings and manual overrides.

Alert on transitions and sustained user impact, not every short-circuited call. Once open, thousands of local rejections can describe one incident. Correlate circuit events with the workflow events used for AI-agent observability so an operator can trace a user-visible degradation back to the dependency decision.

A manual override should be authenticated, time-limited and audited. “Force closed forever” converts the breaker into decoration. Prefer a controlled probe or a temporary policy adjustment with an automatic expiry.

Test failure and recovery as a state machine

Unit tests for one timeout are not enough. Treat the breaker as a concurrent state machine and verify transitions under realistic traffic.

  1. Inject qualifying and non-qualifying failures and verify only the intended outcomes affect health.
  2. Cross the threshold and confirm later calls never reach the dependency.
  3. Advance time to half-open and race many workers; only the configured probe count should pass.
  4. Crash the probe owner and confirm the lease eventually permits another probe.
  5. Return a failed probe and verify the circuit reopens without releasing queued callers.
  6. Return the required successful probes and restore traffic gradually.
  7. Partition the breaker store and verify the chosen fail-open or fail-closed behavior.
  8. Simulate an ambiguous write timeout and confirm reconciliation starts without an automatic duplicate.

Also test agent behavior. The model must not route around the breaker through an alias, recursively delegate the same failing task or claim that a fallback result is equivalent. The infrastructure state machine and the model policy need separate assertions.

Production checklist

  • Derive stable breaker keys from trusted provider, account, region and operation data.
  • Separate dependency-health failures from validation, permission and business outcomes.
  • Use minimum volume, a rolling window and a documented threshold policy.
  • Store state where all relevant workers share it and update transitions atomically.
  • Elect bounded half-open probes with expiring leases.
  • Return circuit_open as a typed, non-retryable agent outcome.
  • Define honest cached, degraded, deferred and escalation paths in advance.
  • Never use a breaker as a substitute for idempotency or ambiguous-write reconciliation.
  • Observe state transitions and user outcomes, not only provider error rates.
  • Fault-test opening, recovery, concurrency and breaker-store failure.

A good circuit breaker turns repeated uncertainty into one explicit operational decision. It stops every agent from rediscovering the same outage, gives the dependency room to recover and forces the product to state what happens when a tool is unavailable. The pattern is simple; the useful engineering is in choosing the right failure domain, evidence and fallback contract.

If your agents keep retrying failing tools, hiding partial results or creating cascades during provider incidents, I can help review the workflow boundaries and recovery policy. See my AI engineering consulting work or contact me.

Sources

Sources and methodology: sources checked December 1, 2026. The breaker identity model, typed agent outcome and Laravel implementation are original synthesis based on production-oriented PHP, distributed systems and AI-agent engineering. Thresholds must be validated against each dependency's normal error rate, quota and recovery behavior. This article was prepared with AI assistance and reviewed for technical accuracy and practical usefulness. Cover: electrical panel photograph from Pixabay.

Igor Gawrys
Igor Gawrys
AI Engineer & IT Consultant · Katowice, Poland