Model Fallback Chains, Gateway Retries and Request Failover
How AI gateways and APIs retry failed requests, chain model fallbacks, and when output locks in so failover stops.
Production AI apps often hit rate limits, timeouts, or provider outages. Most of the material here comes from Cloudflare AI Gateway, Cloudflare Agents, and Perplexity Agent API documentation. Together they describe three layers: retry (same target again), model fallback (next model or provider), and routing (pick or switch based on health, cost, or eligibility).
Model fallback vs request retry: what changes on failure
Section titled “Model fallback vs request retry: what changes on failure”A retry sends the same logical request to the same model or provider again, usually with backoff. A model fallback (or failover) moves to the next entry in an ordered list when the current one errors or times out before usable output.
| Mechanism | What repeats | Typical use |
|---|---|---|
| Request retry | Same provider and model | Transient 5xx, short network blips |
| Model fallback chain | Next model in order | Provider down, quota, regional outage |
| Auto routing | Ranked pool, then fallback candidates | Cost/quality trade-offs at gateway |
Common conclusion: Retries recover from glitches on one endpoint; fallback chains recover when that endpoint cannot serve the request. Documentation from Cloudflare and Perplexity treats these as composable: retries often run before advancing to the next fallback step.
Cloudflare AI Gateway: automatic retries when the upstream provider fails
Section titled “Cloudflare AI Gateway: automatic retries when the upstream provider fails”AI Gateway can retry failed upstream calls without client changes when you enable retries in the dashboard or pass per-request headers.
AI Gateway now supports automatic retries at the gateway level. When an upstream provider returns an error, your gateway retries the request based on the retry policy you configure, without requiring any client-side changes.
— Cloudflare, Automatically retry on upstream provider failures on AI Gateway
You can set retry count (up to 5 attempts), delay (dashboard: 0.1–60 seconds; per-request delay up to 60,000 ms), and backoff (Constant, Linear, or Exponential). Gateway defaults apply to all traffic; request-level cf-aig-* headers override them, as described in the header glossary configuration hierarchy.
cf-aig-max-attempts and timeouts: per-request retry headers
Section titled “cf-aig-max-attempts and timeouts: per-request retry headers”For a provider-specific route, configure retries with:
cf-aig-max-attempts(number, max 5)cf-aig-retry-delay(milliseconds, max 60,000)cf-aig-backoff(constant|linear|exponential)
Use cf-aig-request-timeout (milliseconds) so a slow provider can trigger a retry or fallback. The timeout is measured until the first part of the response arrives; for streaming, the gateway keeps waiting once streaming has started within the limit. See Request handling and Request timeouts and retries with AI Gateway.
On the final retry attempt, the gateway waits until the request completes, regardless of duration.
Model fallback chains on the Universal endpoint and cf-aig-step
Section titled “Model fallback chains on the Universal endpoint and cf-aig-step”The Universal endpoint accepts a JSON array of provider steps. The gateway tries the first object; on failure (or configured timeout), it proceeds to the next.
By default, Cloudflare triggers your fallback if a model request returns an error.
— Cloudflare, Fallbacks
The response header cf-aig-step shows which step succeeded: 0 for the primary, 1 for the first fallback, and so on. See Fallbacks — Response header (cf-aig-step).
Retries on the Universal endpoint run before moving to the next fallback entry. Per-provider config can set maxAttempts, retryDelay, backoff, and requestTimeout (documented on Universal Endpoint).
Dynamic Routing model nodes expose timeout and retries, with optional success and fallback outputs to another element—useful when you want visual routing plus conditional failover.
Auto Router: model pool, scoring, and fallback routing reasons
Section titled “Auto Router: model pool, scoring, and fallback routing reasons”Auto Router builds an eligible model pool (format support, credentials, spend limits, unhealthy providers excluded), classifies the conversation, ranks candidates by quality vs cost, then tries the top model and falls back if needed.
Response headers include cf-aig-routed-model, cf-aig-routing-reason, and cf-aig-routing-decision-id. The cf-aig-routing-reason value fallback_candidate_unavailable means the selected model could not serve the request and another eligible model was used. Other fallback-related reasons include fallback_router_error, fallback_router_timeout, and fallback_unsupported_input. Request headers such as cf-aig-allowed-models and cf-aig-allowed-providers restrict the pool; cf-aig-no-session-affinity: true picks per request instead of pinning a model for the turn.
Perplexity Agent API: models array failover (up to five models)
Section titled “Perplexity Agent API: models array failover (up to five models)”Perplexity documents an explicit client-visible fallback chain via the models parameter.
Model fallback enables specifying multiple models in a models array. The API tries each model in order until one succeeds, providing automatic failover when a model is unavailable.
— Perplexity, Model Fallback
Provide up to 5 models; the models array wins over a single model field when both are set. Billing uses the model that served the request, not every model attempted—see Model Fallback — Pricing. Example usage appears in Agent API Models and Multi-Provider Orchestration.
Perplexity routing and reliability adds platform-side behavior: for catalog models with multiple deployments, traffic shifts by health; failed attempts may retry on another deployment. Client errors such as invalid prompts return 400 without cross-deployment retry; when all deployments fail, 429 with Retry-After may apply, and requests that fail before output are not billed.
Overlap with Cloudflare: Both ordered chains try candidates until one succeeds. Cloudflare exposes step indices via cf-aig-step and routing reasons via Auto Router; Perplexity echoes response.model for the winner.
Cloudflare Workers and Agents: this.retry() and SDK fallback
Section titled “Cloudflare Workers and Agents: this.retry() and SDK fallback”When you own the caller (a Worker or Agent), Cloudflare documents retries and model fallback outside the gateway dashboard.
Agents SDK this.retry() with exponential backoff and jitter
Section titled “Agents SDK this.retry() with exponential backoff and jitter”Retry failed operations with exponential backoff and jitter. The Agents SDK provides built-in retry support for scheduled tasks, queued tasks, and a general-purpose this.retry() method for your own code.
— Cloudflare, Retries
Defaults: maxAttempts 3, baseDelayMs 100, maxDelayMs 3000, using full jitter. Optional shouldRetry stops non-transient errors (for example HTTP 4xx). The same options apply to queue(), schedule(), and scheduleEvery(); invalid options throw at enqueue time. See Agents SDK v0.5.0 — Retry utilities.
AI SDK and Pi AI: fallback before first output
Section titled “AI SDK and Pi AI: fallback before first output”In AI SDK integration, fallback lists models tried in order if the primary fails before any output:
A request that the vendor rejects falls back. So does a stream that fails before its first output part. Once a model has produced output, its answer is final, errors included.
— Cloudflare, AI SDK — Fall back to another model
providerMetadata.cloudflare.model names the model that answered. Failed attempts surface on CloudflareAIError (error.attempts). Within one catalog model, AI Gateway may already retry across providers; dynamic routes can run their own gateway fallback (AI Gateway integration).
Browser Run custom_ai uses the same ordered-list pattern: multiple entries in custom_ai with per-model authorization, tried until one succeeds.
Where to configure retry and fallback (quick reference)
Section titled “Where to configure retry and fallback (quick reference)”| Layer | Who configures | Failover across providers | Output “locks in” |
|---|---|---|---|
AI Gateway dashboard / cf-aig-* |
Operator / any client | Via Universal array or Dynamic Routing | N/A (HTTP semantics) |
| Auto Router | Gateway + headers | Among allowed models | Per routing docs |
Perplexity models |
API client | Yes, up to 5 models | Per Agent API behavior |
Agents this.retry() |
Worker code | No (same operation) | N/A |
AI SDK fallback |
Worker code | Yes (listed models) | After first stream part |
AI Search — AI Gateway models notes configuring request retries and model fallbacks together for resilience. Multi-vendor observability reference summarizes proxy flow: on errors, retry or fallback depends on configuration.
Common mistakes when using fallback and retry
Section titled “Common mistakes when using fallback and retry”- Retrying non-idempotent calls blindly — Callable methods warn that after a connection drop the server may have already executed the call; only retry idempotent operations.
- Expecting fallback after partial stream output — Cloudflare AI SDK and Pi AI stop failover once a model emits output, including error content in the stream.
- Using gateway retries alone for multi-vendor outage — Dashboard retries repeat the same upstream; use Fallbacks or Dynamic Routing for cross-provider failover.
- Ignoring billing order — Perplexity charges the model that served the request; put preferred cheaper or primary models first in the chain (Model Fallback — Pricing).
- Long backoff inside Agent queue retries — Retries — Limitations notes queue retries block subsequent queue items; use
this.retry()inside the callback orschedule()for long delays. - Retrying client errors — Perplexity does not retry deterministic 400s across deployments; fix the request instead of adding more models.
How to check this on your site
Section titled “How to check this on your site”- In the Cloudflare dashboard, open AI → AI Gateway, select your gateway, and confirm Retry Requests matches your policy (Manage gateways — Retry requests).
- Send a test call with
cf-aig-max-attempts,cf-aig-retry-delay, andcf-aig-backoffand confirm behavior in gateway logs (REST API — Per-request configuration). - If you use Universal fallbacks, inspect responses for
cf-aig-stepto see which step served the request (Fallbacks). - If you use Auto Router, check
cf-aig-routed-modelandcf-aig-routing-reasonon responses (Auto Router — Headers). - You can check automatically in Answerwell (our tool): https://answerwell.org/workspace
Report an error or ask a question
Section titled “Report an error or ask a question”If something on this page does not match the linked provider documentation, email yimasynthetic@gmail.com with the page URL and the exact statement you are questioning.