Skip to main content

Routing, load balancing and fallbacks

The router is the part of the gateway that decides which provider actually answers a request. You give several deployments the same public name, for example claude-sonnet-5-5 on Anthropic and on Bedrock, and clients keep sending that one name. For every request the router keeps the healthy deployments the caller may use, picks one with the routing strategy, retries a failed call on another deployment, rests a deployment that keeps failing, and moves the request to another model when the whole group is down. Everything on this page is part of the free gateway.

A real-world scenario​

A customer support app sends every request to claude-sonnet-5-5. The team puts two deployments behind that name, the Anthropic API with a 400 request per minute limit and Bedrock in us-east-1 with 800, and tells the router to shuffle traffic by those limits. On a busy afternoon Anthropic starts answering with rate limit errors. The router retries each failed call on Bedrock, cools the Anthropic deployment down for thirty seconds once three calls fail within thirty seconds, and when both providers have a bad hour the request goes to gpt-6.1-sol as a fallback. The app never changes a line, and the response headers tell the team which deployment answered and whether a fallback was used.

Step by step​

In the Admin UI​

  1. Open /ui/models-and-endpoints as a proxy admin and pick the Add Model tab. Add the first deployment with the public name in the model name field, then add the second provider's deployment with the same public name. Two entries with one name form a model group. Set rpm or weight under Advanced Settings when you want weighted shuffling.
  2. Open /ui/router-settings. On the Loadbalancing tab pick a profile, Balanced, Low latency, Cost saver or High availability, or set Routing Strategy yourself and fill in Number of Retries, Allowed Fails and Cooldown Time under Reliability & Retries. Click Save Changes.
  3. Pick the Fallbacks tab, click Add Fallbacks, choose the Primary Model and the Fallback Chain, and click Save All Configurations.
  4. Click Test fallback on the new row. It sends a real test message and a toast names the model that answered, so you can see the fallback working before traffic needs it.

With curl​

The same setup in config.yaml.

model_list:
- model_name: claude-sonnet-5-5
spanway_params:
model: anthropic/claude-sonnet-5-5
api_key: os.environ/ANTHROPIC_API_KEY
rpm: 400
- model_name: claude-sonnet-5-5
spanway_params:
model: bedrock/us.anthropic.claude-sonnet-5-5
aws_region_name: us-east-1
rpm: 800
- model_name: gpt-6.1-sol
spanway_params:
model: openai/gpt-6.1-sol
api_key: os.environ/OPENAI_API_KEY

router_settings:
routing_strategy: simple-shuffle
num_retries: 2
allowed_fails: 2
cooldown_time: 30
fallbacks:
- claude-sonnet-5-5: ["gpt-6.1-sol"]

Send a request and read the routing headers.

curl -i -X POST http://localhost:4000/v1/chat/completions \
-H "Authorization: Bearer $SPANWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{"model": "claude-sonnet-5-5", "messages": [{"role": "user", "content": "Where is my order 4411?"}]}'

A client can also name fallbacks for one call by adding "fallbacks": ["gpt-6.1-sol"] to the body, and scripts can change a model's fallbacks with the fallback management API.

Expected result​

The response is a normal chat completion. Its headers say what the router did.

x-spanway-model-id: 3f9c0e2a
x-spanway-model-group: claude-sonnet-5-5
x-spanway-attempted-retries: 0
x-spanway-attempted-fallbacks: 0
x-spanway-attempts: 1
x-spanway-routing-reason: strategy=simple-shuffle

When Anthropic rate limits the first attempt, x-spanway-attempted-retries becomes 1, x-spanway-model-id names the Bedrock deployment and the reason header adds the cause, for example strategy=simple-shuffle; retry_cause=RateLimitError. When the whole group fails, x-spanway-attempted-fallbacks becomes 1 and x-spanway-model-group reads gpt-6.1-sol. The spend log row records the deployment that answered and the model it was priced at, and a 429 No deployments available for selected model names the deployments in cooldown.

Reference​

Routing strategies​

router_settings.routing_strategy picks one deployment from the healthy members of a model group.

routing_strategyHow a deployment is chosen
simple-shuffleRandom choice, weighted by weight, rpm or tpm when set. The default and the fastest.
least-busyThe deployment with the fewest requests in flight.
usage-based-routingThe deployment with the most remaining TPM and RPM headroom in the current minute, tracked per instance.
usage-based-routing-v2The same headroom check with counters shared through Redis, so every instance sees the same usage.
latency-based-routingThe deployment with the lowest recent latency.
cost-based-routingThe cheapest deployment according to the price map.
lar1The deployment type an agent's declared confidence calls for, see LAR-1 routing.

Two more mechanisms run as filters in front of whichever strategy is chosen. Tag routing keeps only deployments whose tags match the request, and provider budgets drop deployments over budget. Budgets are not a strategy of their own. They turn on when provider_budget_config is set, whatever routing_strategy says. Strategies that track usage share their counters through Redis when several instances run, see Redis requirements.

Routing groups​

A routing group gives a few model groups their own strategy while every other model keeps the top-level routing_strategy. This helps when, for example, two chat models should share traffic in a fixed order while embeddings keep the default shuffle. You can edit groups on Settings, Router Settings, Routing Groups or in config.yaml.

router_settings:
routing_strategy: simple-shuffle
routing_groups:
- group_name: chat-primary
models: ["claude-sonnet-5-5", "gpt-6.1-sol"]
routing_strategy: priority
model_priorities: {"claude-sonnet-5-5": 1, "gpt-6.1-sol": 2}

The priority strategy is only valid inside a routing group. A call to the group sends traffic to the model with the lowest priority number that has a healthy deployment, and moves to the next number when it fails. Models with the same number share traffic. A direct call to one member model keeps that model's own policy.

A save with a broken group is refused with 400 and one of these messages.

MessageFix
routing_groups: group_name must be non-empty.Give every group a name.
routing_groups: 'default' is reserved for the implicit fallback group.Pick another name.
routing_groups: group names must be unique, duplicate group_name '...'Rename one of the groups.
Priority routing groups require nonempty, distinct modelsList each model once.
model_priorities must contain exactly the group's modelsGive every listed model a priority, and no others.
model_priorities requires routing_strategy='priority'Remove model_priorities or switch the group to priority.
Priority routing groups use model_priorities, not routing_strategy_argsRemove routing_strategy_args from the priority group.

Pre-routing with auto routers​

An auto router is a model_list entry whose model starts with auto_router/. It chooses a model group from the content of the request before the strategy above picks a deployment within that group.

ModelWhat it does
auto_router/<name> with auto_router_configSemantic auto router, matches the prompt against example utterances with embeddings, see auto routing.
auto_router/complexity_routerScores the prompt locally and maps the score to tiers, see auto routing.
auto_router/quality_routerMaps complexity to an admin defined quality tier and picks the deployment that declares it, see quality router.
auto_router/adaptive_routerClassifies the request type and learns from conversation signals which model to prefer, see adaptive router.

Every auto router records its decision in the spend logs and reports usage and savings on the cost optimisation page.

Retries and cooldowns​

A failed call is retried on the same model group up to num_retries times, picking a deployment again each time. retry_policy sets retry counts per error type (BadRequestErrorRetries, AuthenticationErrorRetries, TimeoutErrorRetries, RateLimitErrorRetries, ContentPolicyViolationErrorRetries and others), and model_group_retry_policy overrides it per group. A failing deployment is put in cooldown for cooldown_time seconds (default 5) and skipped by the router. With allowed_fails at its default of 3, the gateway's error rate rule decides when, and any other value, such as the 2 in these examples, pauses the deployment once its failures inside one cooldown_time window go over the number, see cooldowns. allowed_fails_policy sets the threshold per error type, and disable_cooldowns: true turns cooldowns off.

router_settings:
num_retries: 2
allowed_fails: 2
cooldown_time: 30
retry_policy:
RateLimitErrorRetries: 3
AuthenticationErrorRetries: 0

Fallbacks​

When every retry on a model group fails, fallbacks send the request to other groups in order. Three lists cover different failure types.

router_settings:
fallbacks:
- claude-sonnet-5-5: ["gpt-6.1-sol"]
context_window_fallbacks:
- claude-haiku-5-5: ["claude-sonnet-5-5"]
content_policy_fallbacks:
- claude-sonnet-5-5: ["gemini-3.8-flash"]
default_fallbacks: ["gpt-6.1-sol"]

fallbacks applies to general errors, context_window_fallbacks to prompts that are too long for the model, and content_policy_fallbacks to provider content filter refusals. default_fallbacks applies to every group without its own entry. With general_settings.enforce_fallback_model_access: true, a fallback is only attempted when the calling key may use the fallback model.

Caching across model groups​

The response cache key includes the model group, so the same prompt sent to two different public names is cached twice. caching_groups declares groups that should share cache entries, which is useful when two names point at the same underlying model.

router_settings:
caching_groups: [["claude-sonnet-5-5", "claude-sonnet-5-5-bedrock"]]

See caching for turning the cache on.

Timeouts​

timeout sets the overall request timeout in seconds, and stream_timeout on a deployment sets the timeout for the first streamed chunk. Clients can override timeouts per request with the x-spanway-timeout header. Reliability collects all the settings that keep traffic flowing during provider outages.

Errors​

What you seeWhyFix
400 Invalid model name passed in model=...No deployment carries that public name.Check the name on Models + Endpoints or in model_list.
429 with No deployments available for selected modelEvery deployment of the group is in cooldown or over its rpm and tpm limits.Raise the limits, add a deployment, or shorten cooldown_time. The response names the cooldown deployments.
The primary model's error comes back although a fallback is setThe calling key may not use the fallback model and enforce_fallback_model_access is on, so the gateway skipped that fallback.Add the fallback model to the key or team, or turn the setting off.
The same provider keeps answeringsimple-shuffle is weighted by rpm, tpm or weight, so a deployment with a much larger limit wins most of the time.Even out the weights, or pick least-busy.
A deployment never recoversallowed_fails is low and cooldown_time is long, or the deployment keeps failing its background health check.Open Models + Endpoints, Health Status, fix the credential or endpoint, and tune the two settings.
router settings updated successfully but the gateway behaves as beforeThe setting is owned by config.yaml, which the gateway refuses to overwrite from the database.Change it in the config file and restart, or remove it from the file so the Admin UI owns it.