🚀 One API for every frontier model on FastInfra

Browse models

Transparent per-token pricing → compare providers on FastInfra

View pricing

OpenAI-compatible chat completions → start in minutes

Read the docs

⚡ Server Auction → Enterprise bare metal from $78.15/mo (173 in stock)

Browse deals

Implement Multi Model Routing for Cost Savings

Multi model routing for cost savings requires shifting from static model selection to dynamic logic that balances price, latency, and capability. By implementing a router that evaluates against specific task requirements, you avoid paying premium rates for simple queries. This guide details the api implementation patterns needed to build a system that automatically selects the cheapest viable model while maintaining quality standards.

Define Model Selection Logic

Categorize inference requests by computational complexity before routing them. Simple tasks like summarization, classification or entity extraction require minimal context window and reasoning depth. Complex tasks like code generation, multi-step logic, or nuanced creative writing demand higher capability models. Mapping tasks to the correct tier prevents paying for unused compute capacity. Define three distinct complexity tiers for your application logic:
  • Low Complexity: Short prompts, deterministic outputs, and low latency requirements. Route these to smaller, faster models to minimize token costs.
  • Medium Complexity: Moderate context windows, multi-turn conversations, or standard reasoning tasks. Use balanced models that offer a trade-off between speed and accuracy.
  • High Complexity: Large context windows, advanced reasoning, or specialized domain knowledge. Reserve these requests for the most capable models available.
Implement a classification layer that evaluates incoming requests against these criteria. Check prompt length, required output format, and historical performance data. This layer sits between your application code and the inference API.
def classify_request(prompt, metadata):
    if len(prompt) < 500 and metadata.get('task') == 'classify':
        return 'low'
    elif metadata.get('task') == 'code_gen':
        return 'high'
    else:
        return 'medium'
Once classified, map each tier to specific model IDs. FastInfra supports 723 models, allowing granular selection. Avoid hardcoding model names in your business logic. Instead, maintain a configuration map that links complexity tiers to current model slugs. This approach simplifies updates when new models are released or pricing changes. Review the available models at /models to identify candidates for each tier. Select models that meet your latency and accuracy requirements while minimizing cost. Ensure your routing logic handles cases where a specific model is unavailable or exceeds rate limits by falling back to the next tier.

Set Performance Thresholds

Define latency and quality boundaries before deploying a router. Without explicit thresholds, the system defaults to the cheapest available model, which may degrade user experience with slow responses or inaccurate outputs. You must establish maximum acceptable latency in milliseconds and minimum quality scores for each use case. Use these steps to configure your thresholds:
  • Measure baseline latency for your primary model under normal load.
  • Set a hard timeout limit, typically 2x the baseline, to trigger a fallback.
  • Define a quality floor using automated evaluation metrics like BLEU or custom accuracy tests.
  • Configure the router to switch to a faster, smaller model when latency exceeds the limit.
  • Route back to the high-quality model when system load decreases.
The router evaluates each request against these rules. If the primary model response time breaches the threshold, the request reroutes to a secondary model optimized for speed. This ensures consistent performance during traffic spikes.

{
  "primary_model": "high-quality-l7",
  "max_latency_ms": 1500,
  "fallback_model": "fast-inference-3b",
  "quality_threshold": 0.85
}
This configuration sends requests to the high-quality model first. If the response takes longer than 1500ms, the system switches to the faster 3B parameter model. The quality threshold ensures the fallback model still meets minimum accuracy standards. Monitor these thresholds regularly. Traffic patterns change, and model performance varies with load. Adjust limits based on real-world data from your API logs. FastInfra provides detailed metrics for every request, including latency and cost. Use the documentation to access these logs and refine your routing logic. Properly set thresholds balance cost savings with user satisfaction, preventing expensive over-provisioning while maintaining acceptable response times.

Implement Fallback Strategies

Fallback logic prevents single-model failures from breaking user-facing applications. When a primary model times out or returns an error, the router must attempt a request against a secondary model with similar capabilities but different infrastructure dependencies. This approach maintains service continuity while allowing you to prioritize cost or latency based on real-time availability. Define a priority list of candidate models before implementing the code. Rank them by performance requirements and cost efficiency. Use the FastInfra API to query available models and filter for those supporting the required context window and output format. Implement the fallback sequence using a loop that iterates through your candidate list. Wrap each API call in a try-catch block to handle network errors, timeouts, or model-specific exceptions. If the primary model fails, immediately attempt the next model in the queue without alerting the end user.
const models = ['model-a', 'model-b', 'model-c'];
for (const model of models) {
  try {
    const response = await fetch('/v1/chat/completions', {
      method: 'POST',
      body: JSON.stringify({ model, messages })
    });
    if (!response.ok) throw new Error('API Error');
    return await response.json();
  } catch (error) {
    console.warn(`Failed with ${model}, trying next...`);
  }
}
throw new Error('All fallback models failed');
Set strict timeouts for each attempt to prevent cascading delays. A single slow model should not block the entire request chain. Review your model options at /models to identify compatible alternatives for your specific use case. Log every fallback event to track failure rates per model. High failure rates on a specific model indicate infrastructure issues or capacity constraints. Use this data to adjust your routing logic or switch to reserved capacity for critical workloads.

Build the Router API

A router API acts as a transparent proxy between your application and the inference backend. It intercepts OpenAI-compatible requests, evaluates the payload against your routing rules, and forwards the call to the selected model endpoint. This architecture keeps your application code unchanged while moving cost and latency logic to the infrastructure layer. Structure the proxy to handle three distinct phases. First, parse the incoming JSON body to extract the `model` field and input token count. Second, consult your routing table to map the request to a specific provider or model variant. Third, forward the request and stream the response back to the client. Use a lightweight framework like Express or FastAPI to build the handler. The following Python example demonstrates the core forwarding logic. It assumes a `select_model` function exists to determine the target endpoint. @app.post("/v1/chat/completions") async def proxy_request(request: Request): body = await request.json() target_model = select_model(body) response = await httpx.post( f"https://api.fastinfra.net/v1/chat/completions", json={**body, "model": target_model}, headers={"Authorization": f"Bearer {API_KEY}"} ) return StreamingResponse(response.aiter_bytes(), media_type="application/json") Store your routing configuration in a separate file or database. Map input characteristics, such as token length or required capability, to specific models. This separation allows you to update pricing logic without redeploying the proxy. Implement strict error handling for upstream failures. If the selected model times out or returns a 500 error, the router must catch the exception and trigger a fallback. Log the failure reason and the latency observed before switching to the next candidate. Validate the output format before returning it to the client. Ensure that the response structure matches the OpenAI schema your application expects. This consistency prevents breaking changes in your frontend when the underlying model changes. Deploy the router close to your application to minimize network hops. Use environment variables to manage API keys and model endpoints. This setup supports dynamic updates to your 723 without requiring code changes.

Compare Model Pricing Tiers

Model pricing varies significantly impacts inference costs. Routing logic must account for this variance to reduce spend. FastInfra provides a wide range of models with different price points. The platform supports 723 models in its catalog. This diversity allows developers to match tasks to the most economical option. Small language models handle simple tasks at a fraction of the cost of large models. Complex reasoning requires larger models with higher prices. The median input price for chat models is 0.2794. The median output price is 0.918. These averages mask the extremes available in the catalog. The cheapest chat input price is 0.0108. Using this model for basic classification or routing tasks saves money. Reserve expensive models for tasks requiring high accuracy or complex reasoning.
The 10 cheapest paid chat models on FastInfra by combined input and output price (USD per 1M tokens)
ModelInput $/1MOutput $/1MRoutes
Solar Mini 4.5
upstage/solar-mini-4-5
$0.0108$0.04321
Mistral Nemo
mistralai/mistral-nemo
$0.0313$0.03241
L3 Lunaris 8B
sao10k/l3-lunaris-8b
$0.04$0.051
Ling 3.0 Flash
inclusionai/ling-3.0-flash
$0.0227$0.0681
Llama 3.2 3B Instruct
meta-llama/llama-3.2-3b-instruct
$0.0648$0.06482
Mistral Small 24B Instruct 2501
mistralai/mistral-small-24b-instruct-2501
$0.054$0.08642
Command R7B 12.2024
cohere/command-r7b-12-2024
$0.0375$0.151
Nova Micro V1
amazon/nova-micro-v1
$0.0378$0.15121
Schematron V2 Turbo
inference-net/schematron-v2-turbo
$0.0324$0.1621
Trinity Mini
arcee-ai/trinity-mini
$0.0486$0.1621
Compare models before deploying. Check the /models page for detailed specifications. Look at context window size, speed, and price per token. Balance performance needs against budget constraints. Implementing multi-model routing requires understanding these tiers. Route simple queries to low-cost models. Route complex queries to high-performance models. This strategy maximizes efficiency. See the /pricing page for detailed cost breakdowns.

Leverage Free Tier Models

Zero-cost models serve as a critical roles in development workflows and low-stakes production tasks. They eliminate baseline spend for schema validation, prompt engineering, and initial integration testing. FastInfra provides access to 0 models at no charge, allowing teams to iterate without triggering metered billing events.

Use free tier endpoints for tasks where latency tolerance is high and accuracy requirements are minimal. Common use cases include:

  • Validating JSON schema structure before switching to paid models.
  • Testing API connectivity and authentication headers.
  • Running unit tests for application logic that depends on LLM outputs.
  • Prototyping prompt templates for complex reasoning tasks.

Integrate free models into your routing logic as the default fallback. This ensures that non-critical requests never incur costs. When a request fails cost or performance checks, route it to a free model rather than dropping the request entirely. This maintains system responsiveness while preserving budget.

Configure your client to specify the model ID explicitly. Free models often have shorter context windows and lower throughput limits. Verify these constraints in the model catalog before deployment. A typical API call to a free model looks like this:

curl https://api.fastinfra.com/v1/chat/completions \
  -H "Authorization: Bearer $API_KEY" \
  -d '{
    "model": "free-tier-model-id",
    "messages": [{"role": "user", "content": "Test prompt"}]
  }'

Monitor the error rate and latency of free tier requests separately from paid traffic. Free models may experience higher contention during peak hours. If latency exceeds your application’s SLA, automatically escalate the request to a low-cost paid model. This hybrid approach balances cost efficiency with reliability. Review your usage patterns in the dashboard to identify opportunities for further optimization.

Monitor Routing Efficiency

Track routing efficiency by measuring the cost per successful response and the frequency of fallback triggers. These metrics reveal whether your selection logic optimizes spend without degrading user experience. High fallback rates indicate overly aggressive thresholds or unstable model availability, while rising costs per response suggest the router is defaulting to expensive options unnecessarily. Use a structured logging approach to capture request metadata. Record the selected model, latency, status code, and token counts for every inference call. Aggregate this data to calculate real-time performance indicators.
  1. Calculate cost per successful response by dividing total token spend by the number of 200 OK responses.
  2. Measure fallback frequency as the percentage of requests redirected from the primary model to a backup.
  3. Track average latency by model tier to ensure cost savings do not introduce unacceptable delays.
Implement a simple aggregation script to process these logs. The following example shows how to structure the data for analysis:
{
  "request_id": "req_123",
  "primary_model": "fast-model-v1",
  "fallback_model": "cost-efficient-v2",
  "latency_ms": 120,
  "status": "success",
  "input_tokens": 50,
  "output_tokens": 150,
  "cost_usd": 0.00045
}
Review these metrics daily to adjust your routing thresholds. If fallback frequency exceeds 5%, relax your performance constraints or expand the pool of eligible models. FastInfra supports automatic routing across 723 models, allowing you to test different combinations without manual infrastructure changes. Access detailed usage statistics in the dashboard after logging in at /login?tab=register. Compare your actual spend against the pricing tiers to identify outliers. Consistent monitoring ensures that multi-model routing delivers genuine cost savings rather than hidden inefficiencies.

Related FastInfra resources

Frequently asked questions

Does multi-model routing increase latency?

Routing adds minimal overhead, typically milliseconds. The latency gain from using faster, smaller models for simple tasks usually offsets the routing delay, resulting in net faster responses for most workloads.

How do I handle streaming with multiple models?

Ensure your router passes the stream flag correctly to the upstream provider. Most OpenAI-compatible APIs support streaming natively, allowing the router to pipe tokens directly to the client without buffering the entire response.

What happens if the cheapest model fails?

Your fallback strategy should catch the error and retry the request on the next tier in your priority list. This ensures reliability while still attempting to use the most cost-effective option available at that moment.

Can I route based on token count?

Yes. You can configure logic to switch to models with larger context windows or better pricing for long-context tasks when the input size exceeds a specific threshold, optimizing for both cost and capability.

Is authentication complex with multiple providers?

Using a unified API key simplifies this. FastInfra provides a single key that manages access to hundreds of models, abstracting away the need to manage separate credentials for each underlying provider.

Last reviewed November 19, 2026 by FastInfra. Prices and counts on this page are refreshed from the live catalog on every load.