Fallback and retry
AI providers occasionally become unavailable, apply rate limits, or return errors during high-traffic periods. Without a fallback, the gateway returns an error to the caller. With a fallback chain, the gateway silently retries against another provider and the caller receives a response.
Fallbacks are defined per routing rule and are transparent to the caller — the response format is the same regardless of which provider in the chain ultimately handled the request.
How the fallback chain works
A request follows this sequence:
- Primary provider —
retry_countis the number of retries after the first attempt, so the primary is attempted up toretry_count+ 1 times on server errors (HTTP 5xx) and rate-limit responses (HTTP 429, retried with back-off honouringRetry-After). The defaultretry_countof 2 therefore gives 3 attempts (1 initial attempt plus 2 retries). A streamed attempt that gets no answer headers within the first-byte wait is retried too, but only when it was the last candidate in the chain; see First-byte timeouts. - Fallback providers — each fallback is attempted once, in order.
retry_countapplies only to the primary provider. Fallbacks are defined in the routing rule that matched the request. - If all providers are exhausted, the terminal status reflects the last failure in the chain. A server or connection error ends in
502 all_providers_failed, but a final429surfaces429 rate_limited(forwarding the provider'sRetry-After), and a read timeout504. The size of the request body never changes the outcome: a provider outage on a large prompt is still502 all_providers_failed, and only a provider that itself answers413has that answer passed through. A deterministic policy refusal on the final attempt (data residency, provider allowlist, sub-processor objection, a deprecated/unpriced/disabled model, the role model-mask, or a provider auth-config error) surfaces its own status rather than a masking502. A keyed provider (or your own endpoint) answering the same "no healthy deployments" phrase gets the same retry/fallback treatment; its final502detail is the generic "provider HTTP 4xx upstream unavailable". See Terminal status by last failure.
flowchart LR
Start([Request]) --> P1
subgraph Primary ["Primary provider"]
P1[Attempt 1] -- "5xx / 429" --> P2[Attempt 2]
P2 -- "5xx / 429" --> P3[Attempt 3]
end
P1 -- "4xx (except 429)" --> Bail(["Return 4xx immediately<br/>no retry or fallback<br/>(exception: 4xx whose body reports an upstream outage)"])
P3 -- "5xx / 429" --> F1[Fallback 1]
F1 -- "5xx / 429" --> F2[Fallback 2]
F2 -- "5xx (last failure)" --> E([502 all_providers_failed])
F2 -- "429 (last failure)" --> R([429 rate_limited])
Client errors
A client error response from a provider (HTTP 4xx — for example, bad request, unauthorised, not found) is treated as a definitive failure. The gateway does not fall back to another model and, in general, does not retry. The error is returned to the caller immediately.
Exception — a 5xx that reports a request defect. The inverse also exists. The Myra-hosted model proxy (and the model pods behind it) sometimes rejects a request-content problem with a 5xx: HTTP 500 whose error message names Invalid user message at index N, or HTTP 501 Unknown part type: <x>. No other model, and no retry, can fix that, so the gateway recognises exactly those two shapes (bare or wrapped in the proxy's litellm.<X>Error envelope) and does not retry the same leg and does not count it as circuit-breaker evidence. It still walks the fallback chain once (a different provider may accept the content). If the last leg also ended this way, the caller gets the typed 400 invalid_request error (a normal JSON envelope, or a typed error frame on an open stream) instead of a misleading 502 all_providers_failed. Its message is the proxy's own reason (relayed only when it itself names one of those phrases; any other text is never echoed) with the litellm.<X>Error wrapper removed and cut to 256 bytes; if the body carries no readable reason, a fixed generic sentence is used. The recorded provider status in the request log stays the real 5xx. A bare text body that names one of the two phrases is request-side too (it gets the generic sentence above, since only a JSON error message is relayed). An empty body, a body without either phrase (including other 5xx text), or the phrase only beyond the first 16 KiB are not request-side and keep the normal 5xx treatment (retry, breaker, 502). On a server-side tool loop, a call after a tool result that ends this way is not re-dialled and ends as invalid_request as well (and is recorded in the model-error triage queue as a bad_request row with the real 5xx status, never as all_providers_failed); the web-search Mistral Agents leg answers the same typed 400 invalid_request, not a 502; a failure that arrives mid-stream, after output has begun, keeps its streaming error handling.
Exception — a 4xx that reports an upstream outage. Some model proxies answer a server-side fault with a 4xx status. The Myra-hosted model proxy does this when it has benched every deployment of a model (HTTP 400, "There are no healthy deployments for this model"). The gateway recognises that exact phrase in the error body and treats the response like a 5xx: it retries, then walks the fallback chain, and if every leg fails returns all_providers_failed (502) with the "temporarily unavailable" message rather than the proxy's raw text. Any other 400 body, an empty or unreadable body, and a body that only mentions the phrase beyond its first 16 KiB stay ordinary 4xx and are returned immediately. A 429 is unchanged. This outage 4xx also skips the self-recovery resends below, and it is not circuit-breaker evidence: the proxy's own cooldown is the fleet-level breaker.
A narrow set of transparent, gateway-side self-recoveries are the exception to "no retry": when the gateway can see that its own request body caused the 4xx, it fixes the body and re-sends the same model once — stripping a deprecated parameter, dropping a forced tool_choice the backend cannot honour, removing gateway-injected tools the backend refuses, or stripping an unsupported reasoning parameter. These never change the model, never fire more than once per turn, and never fire after streaming has begun; if the single resend also fails, the original 4xx is surfaced.
HTTP 429 (rate limited) is the exception and is not treated as a definitive failure: the gateway retries it against the primary with back-off (honouring the provider's Retry-After header) and, once the primary's attempts are exhausted, falls through to the fallback chain just like a 5xx.
💡 Note: This prevents pointless retries: if your request is malformed or your API key is invalid, retrying against another provider will not help. A 429 is different — it is transient, so it is retried and does fall through the chain.
retry_count
retry_count controls the number of retries against the primary provider after the first attempt (not the total number of attempts). The primary is therefore attempted retry_count + 1 times. Only the primary provider uses retry_count; each fallback is tried exactly once. Set it in the gateway config:
curl -X PATCH https://your-gateway-host/admin/v1/gateways/{id} \
-H "Cookie: aig_admin=<SESSION>" \
-H "Content-Type: application/json" \
-d '{"config": {"retry_count": 3}}'
retry_count |
Primary attempts | Retries |
|---|---|---|
1 |
2 | 1 |
2 |
3 | 2 |
3 |
4 | 3 |
Fallback configuration in routing rules
Fallbacks are defined in the actions object of a routing rule:
{
"priority": 10,
"conditions": [
{"field": "model", "op": "prefix", "value": "gpt-"}
],
"actions": {
"provider": "openai",
"model": "gpt-4o",
"fallbacks": [
{"provider": "anthropic", "model": "claude-sonnet-4-6"},
{"provider": "gemini", "model": "gemini-2.0-flash"}
]
},
"enabled": true
}
Each entry in fallbacks is attempted once, in array order.
💡 Note: The per-rule
timeout_msaction bounds every leg of this rule — the primary and each fallback leg alike. See thetimeout_msaction in the routing rules API reference.
Configuring fallback providers
Before you begin, ensure the following conditions are met:
- ☑ You have admin access.
- ☑ A gateway with at least one routing rule exists.
The fallbacks section of the routing rule editor.
Proceed as follows to add fallback providers to a routing rule:
- Open Organisation › AI setup › Gateways.
- The gateway list opens.
- Click on the gateway you want to configure.
- The gateway page opens.
- Open the Models & routing tab and locate the Routing Rules card.
- The rule list opens.
- Click on the routing rule you want to edit.
- The rule editor opens.
- Scroll to the Fallbacks section.
- The fallbacks list is visible.
- Click on the Add button.
- A new fallback row appears.
- Select the fallback provider from the Provider drop-down list.
- The provider is set.
- Select the fallback model from the model drop-down list next to the provider.
- The model is set.
- Repeat steps 6–8 for each additional fallback provider, in the order the gateway should try them.
- Each fallback is added to the list.
- Click on the Save Rule button.
-> The routing rule is updated with the configured fallback chain.
To create the same configuration via the API:
curl -X POST https://your-gateway-host/admin/v1/gateways/{id}/rules \
-H "Cookie: aig_admin=<SESSION>" \
-H "Content-Type: application/json" \
-d '{
"priority": 10,
"conditions": [{"field": "model", "op": "prefix", "value": "gpt-"}],
"actions": {
"provider": "openai",
"model": "gpt-4o",
"fallbacks": [
{"provider": "anthropic", "model": "claude-sonnet-4-6"},
{"provider": "gemini", "model": "gemini-2.0-flash"}
]
},
"enabled": true
}'
BYOK key swap on provider change
When a fallback triggers a provider change, the gateway automatically selects the BYOK (bring your own key) key for the new provider. The x-aig-byok-alias header applies to the primary provider and to a fallback leg on the same provider; a fallback leg on a different provider always uses that provider's default-alias key.
A BYOK key must be stored for each key-requiring provider in the fallback chain. Keyless providers (the Myra EU fleet) need no stored key — a fallback leg to them dispatches without one. If no key is found for a key-requiring fallback provider, that fallback leg is silently skipped (the gateway logs a warning) and the chain continues to the next fallback. No 424 is raised for a fallback leg — the 424 provider_key_missing error is emitted only for the primary (originally requested) provider, before the fallback loop begins.
A fallback leg uses the same key rules as the primary request:
- Self-serve workspaces are served by Myra's shared key for Anthropic on every leg; a key stored on the gateway is never read. A fallback to a model outside your plan's model list is skipped. A fallback to a different provider than the one requested is allowed when the model is in your plan (for example a fallback from another provider to Anthropic on Myra's shared key); it is subject to the same spend and wallet checks as the main request, and a keyless Myra-hosted model is allowed when your plan and the EU-Gov gate permit it.
- A Myra-provided model can be a fallback leg on any provider, including a provider other than the primary's, when your gateway has no key of its own for it. It follows the same rules as a normal request: the model must be enabled for the gateway (or be in your plan on a self-serve workspace), Myra's spend check and the wallet check run for that leg, and the cost is charged to the workspace wallet. Your own key for the provider is still preferred. How a refused leg is reported is described below.
- When the model's built-in search is switched off on the first attempt (an inherently searching model is swapped to its non-searching sibling), the sibling's key is resolved under the same rule: it is a different model, so the primary's key is never reused for it, and a sibling that rule refuses is skipped like any other leg.
- A leg that is refused because the model is not enabled, not in your plan, has no billable price, or is a sibling refused by the key rule is skipped like a missing key: it is not announced to the client while the chain continues (the gateway logs a warning); only when it is the last leg does the final
502 all_providers_failedmessage name its cause (no_key_for_fallback:<provider>). Spend and wallet refusals are the exception (an empty, frozen or disputed wallet, a spend limit, or a spend check that could not be verified): they are recorded as wallet refusals, the same as when the refusal happens at the call. When an earlier leg really failed, the client gets that earlier failure (for example the primary's429 rate_limited); only when every leg was refused by the spend or wallet check does the wallet or spend code answer (for example429 quota_exceeded,402 wallet_insufficientor503 spend_unverified), not a502.
⚠️ Caution: A missing key does not halt the fallback chain — a key-requiring fallback with no stored key is skipped and the gateway moves on to the next fallback. Store BYOK keys for every provider in your fallback chains: when every leg is skipped or fails, the request ends in
502 all_providers_failed, not a424.
502 all_providers_failed
When every provider in the chain (primary plus all fallbacks) has been tried and none succeeded, the gateway returns:
HTTP status code: 502.
💡 Note: The
messagefield carries the last upstream error encountered while exhausting the chain, falling back toAll configured providers failedwhen no more specific detail is available.
Terminal status by last failure
502 all_providers_failed is the outcome only when the chain's last attempt was a server or connection error. When the final attempt failed for a more specific reason, the gateway surfaces that reason's own status instead of masking it as a 502:
| Last failure | HTTP status | Code |
|---|---|---|
| Server / connection error (default) | 502 |
all_providers_failed |
| Provider rate limit | 429 |
rate_limited (forwards Retry-After) |
| Read timeout | 504 |
request_timeout |
Provider answered 413 |
413 |
the provider's answer, passed through (not retried) |
| Data-residency block | 403 |
(residency refusal) |
| Provider not on the gateway allowlist | 403 |
(allowlist refusal) |
| Sub-processor objection | 403 |
(objection refusal) |
| Model disabled on the gateway | 403 |
model_disabled_on_gateway |
| Model blocked by the role model-mask | 403 |
(role refusal) |
| Deprecated, unpriced, or capability-mismatched model | 400 |
model_not_found / capability refusal |
| Provider auth misconfiguration | 500 |
configuration_error |
The deterministic policy refusals (residency, allowlist, objection, disabled/deprecated/unpriced model, role mask, auth-config) outrank the outage heuristics: a policy-blocked final attempt is reported as the policy refusal, never as a provider outage.
First-byte timeouts
A streamed provider call that sends no response headers within the first-byte wait (20 s by default, or the matching rule's timeout_ms) is treated as a stall. What happens next depends on the chain:
- A fallback follows: the gateway moves to the fallback at once. The stalled provider is not dialled again, because a different model is the faster way to an answer. If that fallback cannot be used right now (open circuit breaker, no key, role mask), the request ends without a re-dial.
- The primary is the last candidate (no fallback is configured): the gateway dials it again, up to
retry_countmore times (a Myra-hosted model gets at least one re-dial even withretry_count0), with the usual back-off, provided the wait plus another full first-byte wait still fits the request's remaining time limit. If it does not fit, the request ends at once with504 request_timeout. - The fallback itself stalls (it is the last candidate): it is not dialled again, so the request ends with
504 request_timeoutafter the primary and the fallback were each tried once. The exception is a Myra-hosted fallback, which gets one re-dial if it fits the same time limits. - Bytes already arrived (the answer stalls mid-stream, or after the headers): never retried. Part of the answer may already have reached you.
- A long first-byte wait (a rule
timeout_msof roughly 75 s or more) leaves no room for a second wait inside the request's time limit, so that stall ends at once with504 request_timeout.
A send that stalls until the same deadline as the first-byte wait (for example when the rule's timeout_ms sets both) cannot be told apart from a stalled wait and is retried under the same limits. With no fallback, the worst case is therefore retry_count + 1 first-byte waits (at least 2 for a Myra-hosted model) plus back-off, and never more than 150 s before the first byte or the request's overall limit, for example 3 waits of the rule's timeout_ms with the default retry_count of 2. When every attempt stalls the outcome is unchanged: 504 request_timeout. The request log counts each dial in upstream_attempts.
Logged fields
For every request that uses a fallback, the gateway logs the final provider used:
| Log field | Description |
|---|---|
fallback_provider |
Name of the provider that ultimately served the request, if different from the primary. |
fallback_model |
Model name used by the fallback provider. |
These fields are visible in the request log table and in the admin UI log viewer.