A circuit breaker is useful when an upstream AI API becomes slow or unavailable. It stops sending requests after a failure threshold is reached, preventing your application from wasting time, money, and worker capacity on calls that are unlikely to succeed.
But a circuit breaker is not a retry policy, a fallback generator, or an outage concealer. For an AI-backed product, the safe design depends on which dependency failed, what work has already been completed, and whether returning a degraded result would mislead the customer.
Here is the direct decision framework:
- Count upstream failures such as timeouts, connection failures, provider
5xxresponses, and unavailable responses. - Do not count ordinary client mistakes such as invalid JSON, missing parameters, or authentication errors as evidence that the upstream service is unhealthy.
- Treat rate limiting separately. A
429may require backoff and a shared quota strategy; automatically treating every429as a circuit-breaker failure can make one client’s quota problem worse. - Trip the breaker only after a defined failure signal, then reject new calls quickly rather than allowing every request to wait for the upstream timeout.
- Return a clear, machine-readable error or a deliberately degraded result. Never silently substitute a weaker answer while reporting that the normal workflow succeeded.
What problem a circuit breaker actually solves
A remote call can fail in two materially different ways. It can return an error, or it can hang until a timeout. Without protection, a slow provider can consume connections, threads, async tasks, and request deadlines in your own service. Many callers then wait on the same unhealthy dependency, turning one upstream slowdown into a cascading failure.
The circuit breaker pattern protects the caller by monitoring failures around a protected call. While the circuit is closed, calls pass through. Once the configured failure threshold is reached, the circuit opens and subsequent calls fail immediately without reaching the upstream provider. After a suitable interval, the breaker can allow a limited probe through. If that probe succeeds, the circuit closes again; if it fails, the breaker remains open for another interval.
That gives a small team three useful properties:
- Bounded waiting: New requests fail quickly once the dependency is known to be unhealthy.
- Reduced load: The upstream provider receives fewer calls while it is struggling.
- A visible state change: The breaker can emit a metric or alert when it opens, closes, or rejects a call.
This is particularly valuable for AI APIs because generation requests can be slow and may continue consuming resources after the caller has given up. Your timeout protects your caller’s deadline; the circuit breaker protects the surrounding system from repeatedly paying that deadline.
First classify the failure
The most common circuit-breaker mistake is treating every exception as equivalent. That turns bad customer input into a false signal that the provider is down.
A practical classification is:
| Response or event | Count toward upstream health? | Recommended handling |
|---|---|---|
| Connection failure or timeout | Usually yes | Fail the call and apply the breaker policy |
Provider 5xx |
Usually yes | Fail the call and apply the breaker policy |
Provider 429 |
Separate signal | Honor retry guidance and coordinate quota use; decide separately whether it should contribute to the breaker |
Provider 4xx caused by invalid input |
No | Return a validation error without penalizing provider health |
| Authentication or permission failure | No | Return an actionable configuration error; fix credentials or scopes |
| Your own cancellation due to a deadline | No | Stop the work and report the deadline outcome |
| Malformed response from the provider | Usually yes | Treat as an upstream contract or availability failure |
A status code alone may not tell the whole story. Preserve the provider’s error body where it is safe and useful, because some APIs express model capacity problems or policy rejections inside otherwise structured responses. Classify by the provider’s documented error contract, not by guesswork based only on a number.
The core rule is simple: a client error does not prove that the upstream service is unhealthy. A request that your application formed incorrectly will fail even during a completely healthy outage-free period.
Choose a failure signal before choosing a threshold
“Five failures” is not a complete circuit-breaker policy. You need to decide what counts, over what window, from which scope, and how long the circuit stays open.
For a small team, a useful starting policy has five parts:
1. Select a narrow protected operation
Protect the dependency operation that is actually failing, not your entire application. A breaker around “call the model provider” should probably distinguish the model or endpoint being called. One provider region, model, or endpoint can be unhealthy while others work.
Avoid one global breaker for several unrelated dependencies. It may stop useful work that could still be completed.
2. Use a rolling window or minimum traffic condition
Consecutive failures are simple, but they behave poorly when traffic is very low. One failure could open the circuit even though ten requests would have shown that the dependency remained mostly healthy. A rolling failure ratio needs a minimum request count, while a consecutive-failure counter is easier to reason about.
For an early implementation, choose one of these:
- Consecutive failures: Open after a fixed number of qualifying upstream failures.
- Rolling failure ratio: Open when a qualifying failure ratio exceeds a threshold and enough requests have been observed.
- Hybrid policy: Open quickly on repeated timeouts, but require a larger sample before opening on less decisive errors.
Do not combine every signal into an unexplained score. Explicit thresholds are easier to test, explain, and tune.
3. Keep the scope visible
A breaker can be global to one service instance, shared across instances, or coordinated through an external store. A local breaker is easy to build but gives every instance its own view. A shared breaker can better suppress a fleet-wide flood, but it introduces another dependency and operational state.
For many small applications, a local per-process breaker is sufficient if each instance also has bounded timeouts and concurrency limits. Move toward shared state only when the evidence shows that independent breakers are producing unacceptable load. Do not build distributed breaker infrastructure merely because a circuit breaker sounds enterprise-sized.
4. Bound each call
The breaker cannot protect a request that has no deadline. Set a timeout below the remaining end-to-end budget and make sure cancellation reaches the underlying network operation where possible.
Timeouts should be operation-specific. A fast classification call and a long generation call should not share the same limit. Also avoid setting a timeout so long that workers remain occupied for most of the upstream outage.
5. Add a probe interval
An open circuit should not wait indefinitely for manual intervention. After an interval, permit a small number of trial requests. A successful probe closes the circuit and clears or rolls the failure state. Failed probes keep it open or extend the next interval.
This probe is not an excuse for a retry storm. Limit it to a small concurrency and keep the normal caller-facing rejection behavior in place until the probe succeeds.
Decide what the breaker returns
When the circuit opens, you are making a product decision: what can the customer receive instead of the normal result?
The safe choices depend on the workflow.
Reject the operation explicitly
For an interactive API where the model result is the product, return an error that says the dependency is temporarily unavailable. Include a stable error code, a human-readable message, and whether the caller should retry later.
A response such as 503 upstream_model_unavailable is more useful than a generic 500 internal_error. It supports client retry logic and gives your incident responders a signal they can filter.
Do not automatically retry an open-circuit rejection inside the same request path. That defeats the breaker and can turn a fast failure into another long wait.
Queue the operation
If the work is asynchronous and business-appropriate, place it in a durable queue with a bounded retry policy. Return an accepted status and a job identifier if your product contract permits asynchronous processing.
Queueing preserves work only if the user experience already expects eventual completion. Otherwise, it may hide a delay from customers and create an unbounded backlog. Apply retention limits, attempt limits, and an explicit dead-letter path.
Return a clearly degraded result
Some products can safely provide a fallback: cached content, a smaller model, a reduced feature set, or a result computed without the failed dependency. This is useful only when the fallback is part of the product promise.
Return metadata that identifies the degraded path. Log the difference and expose it in internal metrics. A fallback that silently omits analysis, personalization, or citations changes the quality of the answer while preserving the appearance of success. That is operationally convenient but commercially risky because customers may act on incomplete output.
Preserve partial work
AI workflows often contain independent stages: retrieval, classification, generation, enrichment, and storage. A failure in one stage does not always invalidate earlier stages.
Persist the completed stage outputs, their model or configuration identifiers, and enough context to resume safely. Then decide explicitly whether resuming is permitted. The key is to avoid both extremes:
- Discarding a completed, billable operation after one later failure
- Automatically replaying the entire workflow, including paid or non-idempotent stages
For example, if document retrieval and citation preparation have completed but generation times out, retain those artifacts and retry only generation if the operation is idempotent. If the workflow already sent an email or charged a customer, record that side effect so a retry cannot duplicate it.
Partial-work preservation depends on idempotency keys or another deduplication mechanism. A retry is only safe when repeating it does not create duplicate charges, messages, records, or other customer-visible effects.
Handle rate limits as a separate control loop
Rate limiting and circuit breaking are related but not interchangeable.
A 429 response says the provider will not accept the request under the current quota or policy. A breaker says repeated calls are being suppressed because the dependency has shown a failure signal. If every 429 immediately opens the breaker, you may turn a temporary quota condition into a broad outage for requests that could have succeeded under different scheduling.
Use the provider’s retry guidance where available. Otherwise, apply bounded backoff with jitter and coordinate concurrency so retries do not arrive together. A queue or scheduler can spread work across the allowed request rate more effectively than independent callers retrying simultaneously.
Decide explicitly whether rate-limit responses contribute to breaker failure counts. One defensible policy is to maintain a separate saturation signal: open the breaker only when repeated 429 responses show that the current request pattern cannot fit within the available quota. This lets the breaker reduce pressure without pretending that a quota rejection is the same thing as a server failure.
For your own public API, also expose useful retry timing so clients do not create avoidable pressure. The API Rate Limit Headers guide covers that design separately.
Pair retries with the breaker, not before it
Retries are most useful for transient failures while the breaker is closed. They are generally harmful when the circuit is open because they repeat the load the breaker is designed to suppress.
A safe sequence is:
- Set a strict timeout for the protected call.
- Allow a small number of retries for selected transient outcomes.
- Add exponential backoff with jitter between attempts.
- Count qualifying final failures toward the breaker.
- Once open, fail fast without automatic retries.
- Permit a limited probe after the open interval.
Do not stack several retry layers. If an HTTP client retries automatically, a queue worker retries the job, and your service wrapper retries the client call, one failed upstream request can become many. Assign retry ownership to one layer and document it.
For background AI work, propagate the remaining deadline through every layer so a nested retry cannot outlive the customer’s wait. The deadline budget guide provides a focused approach to that problem.
A minimal implementation shape
The exact library is less important than the state machine and classification rules. A small implementation needs at least these behaviors:
const states = { CLOSED: "closed", OPEN: "open", HALF_OPEN: "half_open" };
class UpstreamCircuitBreaker {
constructor({
failureThreshold = 5,
openDurationMs = 30_000,
clock = () => Date.now(),
} = {}) {
this.failureThreshold = failureThreshold;
this.openDurationMs = openDurationMs;
this.clock = clock;
this.state = states.CLOSED;
this.consecutiveFailures = 0;
this.openedAt = 0;
}
async call(operation) {
if (this.state === states.OPEN) {
if (this.clock() - this.openedAt < this.openDurationMs) {
throw new UpstreamUnavailableError("circuit_open");
}
this.state = states.HALF_OPEN;
}
if (this.state === states.HALF_OPEN && !this.probeInFlight) {
this.probeInFlight = true;
try {
const result = await operation();
this.onSuccess();
return result;
} catch (error) {
if (isUpstreamFailure(error)) this.onFailure();
else this.onSuccess();
throw error;
} finally {
this.probeInFlight = false;
}
}
try {
const result = await operation();
this.onSuccess();
return result;
} catch (error) {
if (isUpstreamFailure(error)) this.onFailure();
else this.onSuccess();
throw error;
}
}
onSuccess() {
this.consecutiveFailures = 0;
this.state = states.CLOSED;
}
onFailure() {
this.consecutiveFailures += 1;
if (this.state === states.HALF_OPEN ||
this.consecutiveFailures >= this.failureThreshold) {
this.state = states.OPEN;
this.openedAt = this.clock();
}
}
}
The example is intentionally compact, not production-ready. A real implementation needs concurrency control for the half-open probe, accurate timeout cancellation, metrics, safe logging, and explicit handling of provider-specific error bodies. It also illustrates an important choice: a non-upstream error does not increment the consecutive-failure count. Whether it should reset the count depends on your policy; resetting is shown here as one defensible interpretation.
Do not hide the provider’s response behind a generic exception before classification. Preserve enough status and error information to distinguish validation failures, quota rejection, timeout, and server failure.
Test the behavior, not just the success path
A breaker is operational infrastructure, so test its transitions and customer-visible consequences.
At minimum, test:
- A qualifying upstream failure increments the breaker signal.
- An invalid request does not penalize upstream health.
- Reaching the threshold opens the circuit.
- Calls are rejected without executing the upstream operation while open.
- The open interval allows only the intended probe behavior.
- A successful probe closes the circuit.
- A failed probe reopens it.
- Rate limits follow their chosen separate policy.
- An open-circuit response identifies the dependency and does not claim that work completed.
- A resumed workflow does not repeat a completed, non-idempotent side effect.
Use a fake upstream operation or controlled fault injection. Do not depend on a real provider being unhealthy during a test run. Your production metrics should then verify that the classifications resemble reality; providers can change response formats, so periodically review unexpected errors that your breaker is ignoring.
Observe the business impact
Track more than whether the circuit is open. Useful signals include:
- Breaker state by dependency and operation
- Qualifying failures and rejected calls
- Upstream timeout rate and latency
429responses and retry volume- Queue depth and age for deferred work
- Partial-work resume counts
- Duplicate-suppression counts
- Customer-visible fallback and explicit-rejection rates
The business question is not merely “did the breaker trip?” It is “did we avoid wasted spend and deliver an honest outcome?” A circuit that opens correctly but causes every customer request to fail may have prevented a cascade while still failing the product. Pair this pattern with the small-team API incident response runbook so operators know what to communicate and when recovery is safe.
A practical rollout sequence
For an indie developer or small team, implement the pattern in this order:
- Measure the dependency. Record upstream status, timeout, latency, and provider error type.
- Bound every call. Add an operation-specific timeout and cancellation.
- Classify failures. Separate upstream faults from client and configuration errors.
- Add retries carefully. Use bounded backoff for selected transient outcomes.
- Add a local breaker. Start with a simple threshold and open interval.
- Define the response. Choose explicit rejection, durable queueing, or a product-approved degraded result.
- Persist partial work. Add idempotency and resume rules for multi-stage workflows.
- Alert on state changes. Notify operators when a breaker opens or remains open.
- Test transitions. Verify rejection, probing, recovery, and side-effect safety.
- Tune from evidence. Change thresholds based on observed latency, capacity, and customer impact.
Do not start with a distributed breaker and a complex dashboard. Start where you can prove that calls are wasting time or money, then add coordination if local controls are insufficient.
Frequently asked questions
Is a circuit breaker the same as a timeout?
No. A timeout limits one call. A circuit breaker observes a sequence of qualifying failures and changes behavior for later calls. A timeout is still required; without it, the breaker may never receive a failure signal from a hung dependency.
Should every 4xx open the circuit?
No. Invalid requests and authentication failures usually indicate a caller or configuration problem, not upstream unavailability. 429 needs separate treatment because it reflects quota or capacity constraints.
Should the circuit retry automatically?
Usually not. Automatic retries while the circuit is open defeat its purpose. Permit a controlled probe after the open interval and handle transient retries only according to a separate, bounded policy.
Is a fallback response always better than an error?
No. A fallback is better only when it is safe, clearly labeled, and consistent with what the customer paid for. Otherwise, an explicit temporary-unavailability error is usually more honest than silently returning degraded work.
When should the breaker be shared across instances?
Consider shared state when independent local breakers still create excessive upstream load or inconsistent recovery behavior. Shared state adds storage, coordination, and failure modes, so it should solve an observed problem rather than a theoretical one.
The bottom line
For AI-backed APIs, the best circuit breaker is not the one with the most elaborate failure score. It is the one that distinguishes upstream faults from client mistakes, fails fast when the dependency is unhealthy, protects workers and spend, and tells the truth about what the customer received.
Start by classifying failures, bounding calls, and choosing an explicit customer outcome. Then add probes, partial-work recovery, and shared coordination only as operational evidence justifies them. A circuit breaker should make an outage less damaging without making it less visible.







