Latency Brownouts in LLM Gateways: Detect, Isolate, and Recover Before Timeouts
HTTP success can hide an unhealthy LLM provider. Design latency-aware admission with route-specific slow-call evidence, streaming-aware metrics, controlled probes, and reliability gates that avoid false failovers.
On this page
A model API can return successful responses while making an application feel unavailable. The HTTP status is fine, the error budget may appear intact, and a breaker that counts only failed requests remains closed. Meanwhile the user has stopped waiting.
That is a latency brownout: a dependency is still responding, but its timing no longer satisfies the application's contract. The difficult part is not choosing a number of seconds and marking every slower response as broken. It is designing a control loop that can distinguish upstream degradation from heavy prompts, local queuing, intentional cancellations, and normal variability.
This article proposes a production-oriented brownout policy for a hypothetical multi-tenant AI support platform. It is an architectural design with illustrative TypeScript and Python code, not a claim about measured provider behavior, an existing outage, or an independently deployed system.
I have previously written about provider failover, retries, and graceful degradation. That article covers recovery after a dependency becomes unhealthy. This one concentrates on a narrower question: what evidence is sufficient to classify a responding model route as too slow to admit more work?
Availability has a timing dimension
Consider two inference calls with the same prompt class. Both return valid structured output. One takes two seconds; the other takes twenty. If the application promised a useful interactive response within eight seconds, only one delivered usable availability.
A service-level indicator based solely on error responses misses that difference. The application's deadline, the provider-facing duration, and the time a streaming user waits for the first meaningful output are related but not interchangeable.
| Signal | What it tells you | What it cannot prove |
|---|---|---|
| Provider-facing completion duration | How long the inference call took end to end | Whether your own queue consumed the user deadline |
| Time to first response chunk | How long until a streaming response began | Whether the final result completed or was correct |
| Output progress / time between chunks | Whether a stream is actively advancing | Whether a token stream carries useful content |
| HTTP / SDK failure rate | How often a call failed at the observed boundary | Whether successful calls were fast enough |
| Full workflow latency | Whether the user-visible operation met its objective | Which dependency caused the delay |
The OpenTelemetry GenAI client-inference conventions define separate measurements for client inference duration and time to first chunk. These conventions describe instrumentation boundaries, not an off-the-shelf health policy. The application must decide what constitutes a problematic delay for its own workload.
A slow call is not automatically an upstream fault. A very long requested output may legitimately take longer to generate. Comparing a tiny classification request to a long report-generation request can create a false brownout.
Compare like with like before counting slow calls
A useful health key is not simply "provider A." I would derive a bounded *route class* from trusted configuration:
- provider and specific model deployment;
- region or account capacity pool where known;
- interactive versus asynchronous workload;
- streaming versus non-streaming interface;
- coarse request-size and requested-output-size bands;
- service tier or provisioned-capacity class if applicable.
The purpose is to keep legitimate latency differences from contaminating the same denominator. An overloaded high-volume route should not necessarily mark every endpoint and every model at the company as unhealthy.
This segmentation has limits. Make the health key too granular and each segment has too little traffic to produce reliable evidence. Include tenant IDs or raw prompt lengths directly in monitoring labels and you create cardinality and privacy problems. Keep sensitive routing keys in a protected decision store and export bounded route categories to telemetry.
I would establish the *slow threshold* from a measured, known-good distribution for each request class, aligned to the user's deadline. The policy might use an explicit duration limit, a baseline-relative degradation check, or both. The point is to avoid pretending that a fixed global number works for classification, streaming generation, and long-form analysis.
An architecture with independent evidence and dispatch
I separate observations from routing decisions. The data plane never lets a single slow response directly change every tenant's model route.
~~~text Authenticated incoming workflow | workload classification | request deadline | +----------v------------+ | Gateway admission | | capability + budget | | current route state | +----------+------------+ | bounded call | +-----------v----------+ | Provider adapter | | time to first chunk | | end-to-end duration | | progress / outcomes | +-----------+----------+ | normalized signals | +------------v------------+ | Brownout evidence store | | route-scoped windows | | minimum sample size | | freshness / exclusions | +------------+------------+ | +----------v-----------+ | Health policy | | healthy / suspect | | restricted / probe | +----------+-----------+ | versioned route state | Gateway admission
Independent limits: queue, concurrency, workflow deadline, and model quality. ~~~
The evidence store is not an LLM prompt. Its policy should be deterministic and inspectable. The gateway should also continue enforcing system-level backpressure and workflow cancellation. A latency breaker cannot substitute for either.
An important distinction: the evidence pipeline may produce suspected degradation while the routing controller decides to reduce admission rather than immediately abandon a provider. That creates room for verification, traffic shaping, and measured recovery.
Count both slow and failed calls, but do not conflate them
Resilience4j's CircuitBreaker documentation distinguishes failure rate from slow-call rate. It supports sliding windows, minimum call counts, a slow-call duration threshold, and a separate threshold for the proportion of calls that are slow. That is a useful reference for the *mechanics* of a health decision.
I would adapt the principle to inference, not copy a library default blindly. In particular:
- Record provider-facing elapsed time for successful completed attempts.
- Record upstream failures separately, including the error class and timeout source.
- Do not count a user clicking Cancel as proof that the provider failed.
- Do not attribute time spent waiting in your own worker queue to provider duration.
- Track excluded and unfinished calls separately, because they reduce confidence in the observed sample.
The last point is easy to miss. A completed-call window has survivorship bias during a brownout: the fastest calls finish and enter the window while the slowest remain in flight. A circuit breaker that evaluates only completions can look healthy immediately before everything times out.
The answer is not to label every in-flight request a failure. Track overdue in-flight work as a separate early-warning signal and bound concurrency while evidence matures.
TypeScript: make the brownout assessment auditable
The following pure function assesses an already-classified set of request observations for one route class. It deliberately returns a recommendation instead of directly opening a global circuit. All thresholds are example policy inputs, not universally appropriate settings.
~~~typescript type Outcome = "success" | "upstream_error" | "excluded";
type Observation = Readonly<{ completedAtMs: number; providerDurationMs: number; outcome: Outcome; }>;
type Policy = Readonly<{ windowMs: number; slowAfterMs: number; minEligible: number; minSuccesses: number; maxSlowShare: number; maxErrorShare: number; }>;
type Assessment = Readonly<{ decision: "unknown" | "healthy" | "suspected_brownout"; reason: string; eligible: number; excluded: number; slowShare: number | null; errorShare: number | null; }>;
export function assessRoute( observations: readonly Observation[], policy: Policy, nowMs: number, ): Assessment { const unknown = (reason: string): Assessment => ({ decision: "unknown", reason, eligible: 0, excluded: 0, slowShare: null, errorShare: null, });
if (!Number.isSafeInteger(nowMs) || !Number.isSafeInteger(policy.windowMs) || !Number.isSafeInteger(policy.slowAfterMs) || !Number.isSafeInteger(policy.minEligible) || !Number.isSafeInteger(policy.minSuccesses) || policy.windowMs <= 0 || policy.slowAfterMs <= 0 || policy.minEligible <= 0 || policy.minSuccesses <= 0 || policy.maxSlowShare <= 0 || policy.maxSlowShare > 1 || policy.maxErrorShare <= 0 || policy.maxErrorShare > 1) { return unknown("invalid_policy"); }
const recent = observations.filter( (o) => Number.isFinite(o.providerDurationMs) && o.providerDurationMs >= 0 && Number.isSafeInteger(o.completedAtMs) && o.completedAtMs <= nowMs && o.completedAtMs > nowMs - policy.windowMs, );
const excluded = recent.filter( (o) => o.outcome === "excluded", ).length;
const eligible = recent.filter( (o) => o.outcome !== "excluded", ); const successes = eligible.filter( (o) => o.outcome === "success", ); const errors = eligible.length - successes.length;
if (eligible.length < policy.minEligible || successes.length < policy.minSuccesses) { return { ...unknown("insufficient_completed_evidence"), eligible: eligible.length, excluded, }; }
const slow = successes.filter( (o) => o.providerDurationMs > policy.slowAfterMs, ).length;
const slowShare = slow / successes.length; const errorShare = errors / eligible.length; const degraded = slowShare >= policy.maxSlowShare || errorShare >= policy.maxErrorShare;
return { decision: degraded ? "suspected_brownout" : "healthy", reason: degraded ? "route_threshold_exceeded" : "within_policy", eligible: eligible.length, excluded, slowShare, errorShare, }; } ~~~
This code is deliberately conservative about what it knows. It does not calculate a p99 from a small sample, estimate queueing, or mark a request that never completed as a success. The recorded outcome must already have been classified by a trusted provider adapter. An invalid or missing observation is absent from the calculation; production monitoring must count invalid observations separately so silent data loss cannot appear healthy.
The slow share uses successful completions as its denominator, while upstream-error share uses all eligible completions. Those numbers answer different questions. The function combines the policy conditions with OR, but the operational controller can choose different responses to slowness and errors.
I would also track the fraction of eligible traffic represented by the sample, especially when tracing is sampled. A low-volume route with six unusually slow requests should not automatically trigger fleet-wide failover.
Detect backlog before completions catch up
A brownout is also a capacity problem. When average provider service time grows, the number of requests concurrently in flight can grow for a fixed arrival rate. This can exhaust your gateway's concurrency pool even before the error rate increases.
An early-warning policy could track overdue fraction among currently in-flight calls, along with provider-facing duration of completed calls. Keep it separate from error rate: being overdue is a timing risk, not proof of failure.
Consider three signals under the same route class:
| Signal | Interpretation | Suggested controller action |
|---|---|---|
| Healthy completed-call window, few overdue | No material latency evidence | Maintain normal admission |
| Many overdue, completed sample insufficient | Degradation plausible but unconfirmed | Tighten concurrency, preserve optional fallback |
| Slow-call threshold exceeded with enough evidence | Sustained timing breach | Restrict route, shift eligible work, probe recovery |
| Rising failures or repeated probe failure | Stronger indication of upstream unavailability | Open circuit under policy and avoid additional load |
These are candidate policies, not results of a benchmark. The key engineering move is to make unknown a first-class state. Without it, missing telemetry and small samples tend to be interpreted as "healthy."
The application should still keep a hard end-to-end workflow deadline. A brownout detector is not a reason to let user requests wait indefinitely for enough statistical confidence.
Streaming requires a different health contract
Streaming changes what responsiveness means. A model might emit its first chunk quickly and then pause for a long period. Another might take longer to begin but produce a complete answer promptly. Neither can be judged accurately from HTTP status alone.
For streaming routes, I would collect:
- time from logical inference start to first provider response chunk;
- the distribution of time between meaningful provider chunks;
- duration from start to completed response;
- whether the stream ended normally, was cancelled, or was interrupted;
- output-token count where reliably available, to compare similarly sized generations.
The OpenTelemetry time-to-first-chunk metric is particularly useful, but should not be mistaken for a complete availability SLI. A first chunk may be protocol metadata rather than useful answer content; an application-specific "first meaningful output" metric may therefore be needed alongside standard telemetry.
Do not count an idle period after the client has cancelled the request as upstream slowness. Also be careful with explicit user think-time or human-approval pauses in an agent workflow: those are application states, not evidence that a model provider is stalled.
If a stream has already emitted user-visible text, failing over midway is not equivalent to switching providers before generation. The replacement might disagree, duplicate output, or violate a previously selected tool plan. I would generally complete or fail the active stream under a clear recovery contract and route *new* eligible work to a healthier provider.
Python: admission should respect the user's remaining deadline
A health signal cannot decide routing without knowing whether a candidate model can satisfy the workflow requirements. A slow but high-quality model may still be appropriate for offline work. A fast fallback may be unusable for an operation requiring a capability or output contract it does not support.
This Python function consumes a trusted snapshot of route state and gives the gateway a bounded recommendation:
~~~python from dataclasses import dataclass from typing import Literal
Health = Literal["healthy", "suspect", "restricted", "unknown"]
@dataclass(frozen=True) class Route: name: str health: Health is_approved: bool supports_required_contract: bool expected_budget_ms: int cost_ceiling_ok: bool
@dataclass(frozen=True) class Decision: route: str | None reason: str
def choose_route( routes: list[Route], remaining_ms: int, reserve_ms: int, ) -> Decision: if remaining_ms <= 0 or reserve_ms < 0: return Decision(None, "deadline_exhausted")
usable_ms = remaining_ms - reserve_ms if usable_ms <= 0: return Decision(None, "insufficient_budget")
# Pre-validated, configured preference order. for route in routes: if not route.is_approved: continue if not route.supports_required_contract: continue if not route.cost_ceiling_ok: continue if route.expected_budget_ms <= 0: continue if route.expected_budget_ms > usable_ms: continue if route.health == "healthy": return Decision(route.name, "normal_route")
# Suspected or unknown is not equivalent to healthy. # Only opt-in workflows may use the explicitly degraded path. return Decision(None, "defer_or_return_degraded_outcome")
routes = [ Route("primary-interactive", "restricted", True, True, 2500, True), Route("fallback-interactive", "healthy", True, True, 3000, True), ] assert choose_route(routes, 5000, 500).route == "fallback-interactive" ~~~
The example is a routing decision, not an SDK client or a full recovery policy. It deliberately does not dispatch to a suspect route by default. A production workflow can have a separate, explicit policy permitting reduced or deferred work when all preferred routes are unhealthy.
The route snapshot must be fresh and tied to a protected health key; the model cannot create its own route status. The decision is not a guarantee that the next call will finish within the expected budget. It is a bounded admission estimate that must still be enforced by timeouts, cancellation, and backpressure.
This separation matters because a cheaper or faster model is not automatically an approved replacement. Use eval-gated model routing to confirm that the fallback actually satisfies the required schema, tool behavior, privacy boundary, and business risk class.
Recovery is a controlled experiment
A brownout detector that opens too aggressively can amplify a transient issue. An open circuit that never probes can leave healthy capacity unused for hours. The recovery policy needs its own boundaries.
I would use versioned route state with a short cooldown, a limited number of half-open probes, and an explicit exit decision based on fresh evidence. The probes should represent the same workload class without exposing consequential side effects. They should be bounded and isolated so recovery traffic does not recreate the overload that caused the original degradation.
The Polly circuit-breaker documentation describes sampling, minimum throughput, and break durations for ordinary fault-driven breakers. A brownout implementation can use a similar state machine, but needs latency-aware evidence and a policy for incomplete probes.
Useful recovery invariants include:
- Only one controller generation may change route state at a time.
- Expired telemetry cannot close a circuit.
- Half-open probes have their own concurrency, deadline, and cost budgets.
- A probe that is cancelled or not observed is unknown, not healthy.
- A recovered route receives traffic gradually rather than absorbing all failover demand at once.
- A new model deployment resets or separately versions its historical health evidence.
The gateway needs a fallback when its own health-policy service is unreachable. That fallback must be conservative and explicit, such as continuing an unexpired approved route binding for a short interval while rejecting activation of new unknown routes. Do not let the model decide whether missing health evidence means everything is fine.
Do not mistake client overload for a provider incident
The most dangerous false positive is opening a provider circuit in response to your own saturated queue. If one tenant's large batch consumes your worker pool, provider-facing requests can remain fast while user-visible latency becomes terrible.
I would capture three clocks separately:
- Queue clock: from request admission to provider dispatch.
- Provider clock: from actual provider request start to termination.
- Workflow clock: from user request to delivered outcome.
The controller should open an upstream route based on provider-facing evidence, not queue delay alone. Queue overload belongs to local admission control. The backpressure article describes that separate boundary.
Similarly, a poorly chosen retry policy can inflate logical operation duration. Instrument both the logical call, including retries, and individual provider attempts when the adapter exposes them. Otherwise a five-second backoff may look like five seconds of model inference. The distinction determines whether you should tune retries, route selection, or the provider circuit.
A failure-injection matrix for brownouts
Before enforcing this policy, I would test a staged fixture rather than tune thresholds from one pretty load test.
| Simulated condition | Evidence expected | Failure to avoid |
|---|---|---|
| All calls succeed but 60% exceed class deadline | Slow-call suspicion after minimum sample | Breaker stays closed because HTTP 200 |
| One very long requested output | Correct workload bucket; no global trip | Long-form generation poisons short-task route |
| Worker queue becomes congested | Local queue alarm, provider route unaffected | Provider blamed for local backlog |
| Several calls never complete | Overdue-in-flight warning and deadline enforcement | Survivorship bias declares route healthy |
| Low traffic with only a few observations | Insufficient-evidence state | Overreact to tiny samples |
| User cancels a stream | Cancellation metric, not upstream error | False provider-failure spike |
| Provider recovers during cooldown | Bounded probes and gradual readmission | Thundering herd on recovery |
| Fallback route violates required schema | Reject fallback; honest degraded outcome | Latency improves while correctness regresses |
That test plan is deliberately broader than a success/failure circuit-breaker unit test. It validates whether *source attribution, sampling, and consequences* line up under realistic timing anomalies.
What I would put on the operations dashboard
A brownout dashboard should answer both "is this route slow?" and "is our response to slowness making things better?"
I would track:
- slow-call proportion and request volume per bounded route class;
- p50, p95, and p99 provider-facing latency, with sample-count context;
- time to first response chunk and inter-chunk stalls for streaming calls;
- local queue wait, in-flight work, deadline misses, and cancellation reasons;
- route-state transitions, cooldowns, probe failures, and unknown-evidence periods;
- diverted traffic, alternate-route latency, quality-regression checks, and cost;
- completed user outcomes and deadline-attainment rate, not only provider HTTP success.
Prompts, retrieved documents, and user data should not be exported as default health metrics. The OpenTelemetry GenAI documentation provides a base for timing telemetry; application metrics should add only the dimensions needed to diagnose a particular workload, with privacy-aware cardinality limits.
The incident response should also make it easy to distinguish an intentional policy action from a provider failure. A high rejection rate while the circuit is open can be the *expected* result of protective admission—not evidence that the provider itself has suddenly begun returning more errors.
Trade-offs: sensitivity, efficiency, and quality
A latency-sensitive breaker can save user time, but it can also make a healthy system less stable if its thresholds are noisy. Tight thresholds increase false trips. Very conservative thresholds allow a brownout to linger. Per-route segmentation improves attribution but reduces statistical power. Additional probes consume budget and capacity when a dependency may already be weak.
For low-volume routes, I would consider passive observation plus explicit request deadlines instead of auto-opening a circuit on a statistically fragile window. For high-impact interactive routes, stricter admission makes sense if there is enough representative traffic and a genuinely compatible fallback.
Even when the system can shift work successfully, model quality and safety must remain release gates. A fast answer with missing required evidence is not successful recovery. A fallback that breaks tool schemas or changes permission semantics is not a valid reliability improvement.
And remember correlated failures: two routes may share infrastructure, quotas, or regional constraints. Route diversity must be assessed using actual deployment dependencies, not just two different display names.
Protect the health signal as a security boundary
A routing controller is also a security-sensitive component. If a tenant can make the shared provider appear unhealthy, the controller may shift other customers to a more expensive or less appropriate model. This is a form of control-plane manipulation, even when the attacker never changes a system prompt.
I would apply three safeguards:
- Authenticate telemetry at the adapter boundary. The model, user prompt, and tool output cannot set their own provider duration, outcome class, or route-health state. Derive timing from monotonic host clocks and separately identify instrumentation gaps.
- Bound the influence of one traffic source. Use trusted service tiers and capacity pools when forming health keys; cap how much traffic from any one tenant can dominate fleet-wide health evidence. Avoid pretending that an arbitrary tenant identifier is a reliable deployment-failure domain.
- Reauthorize every fallback. A brownout never grants permission to send customer content to an unapproved provider, geography, or model tier. Data-residency restrictions, tool permissions, retention terms, and contractual privacy requirements still apply.
The health service should have access controls, versioned decisions, append-only change records, and a deliberate operator override path. An engineer should be able to distinguish an automated brownout restriction from a manual isolation and identify who authorized the latter.
The privacy design belongs in the instrumentation too. Prompt text, provider API keys, full response bodies, and unredacted customer IDs are not needed to compute slow-call proportion. Keep detailed restricted traces separate from low-cardinality health metrics and apply a retention policy that matches the data's sensitivity.
This matters during a live incident: a faster route that violates the user's security boundary is not a valid recovery path. The system should fail or defer visibly rather than silently downgrade its trust guarantees.
The rule I would take into production
Do not ask a circuit breaker only whether the provider returned an error. Ask whether this approved route can still deliver this class of work within its timing contract, based on enough fresh, properly attributed evidence.
That requires two separate designs: a measurement system that can tell upstream slowness from local delay, and a policy system that can change admission without overreacting or causing unsafe fallback behavior.
If the evidence is thin, say it is thin. If the provider is slow, reduce the load intelligently. If the fallback cannot do the job safely, preserve the workflow and return a truthful degraded result. And if the user already received part of a streamed answer, do not pretend that silently replacing the model mid-sentence is a transparent retry.
Availability is not merely that the provider answered. It is that the user received a correct, authorized, timely outcome.
Technical references
KEEP READING
Related engineering notes
A Failover Route Is Not a Recovery Path: Proving Independence in AI Infrastructure
Two LLM providers can share the same failure domain. Build an evidence-backed recovery graph that checks cloud, networking, identity, control-plane and capacity dependencies before admitting fallback routes, then test correlated outages without weakening safety.
Read articleAn Eval Platform Sunset Can Erase Your Release Evidence: Build an Evidence-Escrow Migration Gate
When a hosted LLM evaluation platform retires, switching runners is not enough. Preserve the historical evidence, reconstruct grader semantics, validate scoring parity, and enforce a fail-closed release gate that survives the service shutdown.
Read articleWhen the Package Runs Before Your App: Quarantining AI Framework Releases
The 2026 agent-framework PyPI compromise exposed a blind spot in AI build pipelines: Python startup hooks execute before application imports. Design an artifact-quarantine gate, inspect wheels without installing them, separate credentials, and recover from suspected exposure.
Read article