🚀 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

Routing Logic for Mixed Model Fleets

Routing logic for mixed model fleets balances cost against latency by directing requests to the most efficient available model. With models in the catalog, manual selection fails at scale. Automatic lowest-cost routing handles this by evaluating real-time prices and availability. This guide covers implementing dynamic model selection, fallback strategies, and OpenAI-compatible API routing to optimize performance without hardcoding vendor dependencies.

Why Mixed Model Fleets Need Routing

Single-model architectures create rigid dependencies that fail under variable load or cost constraints. When an application binds to one specific model, it inherits that model’s latency spikes, availability limits, and fixed pricing structure. This approach works for static workloads but breaks when demand fluctuates or when marginal cost becomes a primary optimization target. A mixed model fleet resolves these bottlenecks by treating inference as a pool of interchangeable resources. Instead of pinning to a single provider or architecture, you distribute requests across 723 available models, including 0 zero-cost options for low-priority tasks. This diversity allows the system to adapt to real-time conditions without manual intervention. The core benefit is resilience through redundancy. If a primary model experiences high latency or temporary unavailability, the routing layer shifts traffic to alternative models that meet the same functional requirements. This prevents downstream failures and maintains consistent response times for end users. Cost optimization becomes granular rather than binary. Different models excel at different tasks; a lightweight model may handle simple classification tasks at a fraction of the cost of a large language model, while delivering acceptable accuracy. By routing based on task complexity, you avoid over-provisioning compute for simple operations. To see the full range of available models, review the model catalog. Understanding the specific capabilities and limitations of each model in your fleet is the first step in designing effective routing logic. Without this visibility, routing decisions remain guesswork rather than engineered solutions.

How Automatic Lowest-Cost Routing Works

Automatic lowest-cost routing evaluates every available model against your specific request payload before dispatching. The system does not rely on static price lists or cached averages. Instead, it queries live pricing data for each compatible model in the fleet at the moment of inference. This ensures that the selection reflects current market conditions, including spot instance availability and provider-specific discounts. The routing engine calculates the total expected cost by combining input and output token rates. For standard chat completions, the median cost structure involves an input rate of 0.2794 and an output rate of 0.918. The engine multiplies these rates by the estimated token counts. It then compares the resulting totals across all eligible models. The model with the strictly lowest projected cost receives the request. This process happens in milliseconds, adding negligible overhead to your application’s latency. You do not need to maintain separate client logic for different providers or model versions. The single API endpoint handles the complexity of fleet management. If the cheapest model becomes unavailable or exceeds latency thresholds, the router immediately selects the next best option without failing the request. To leverage this, send your request to the standard endpoint. The system handles the rest.
POST /v1/chat/completions
{
  "model": "auto",
  "messages": [{"role": "user", "content": "Analyze this data"}]
}
Setting the model parameter to `auto` triggers the routing logic. You can also specify constraints, such as maximum latency or required capabilities, to filter the candidate pool. The router respects these boundaries while still optimizing for cost. This approach is particularly effective for workloads with variable token lengths, where the 3.3 significantly impacts the final price. By offloading the selection process to the platform, you reduce operational overhead and ensure consistent pricing optimization across your entire deployment. See the [API documentation](/docs) for detailed parameter options.

Implementing Model Fallback Strategies

Primary models often hit rate limits or experience temporary unavailability during peak traffic. A fallback strategy ensures your application remains responsive by automatically switching to a secondary model when the primary endpoint fails or returns a `429 Too Many Requests` status. This approach prevents user-facing errors without requiring manual intervention or complex load balancer configurations. Configure fallbacks by defining a priority list of compatible models in your request headers or configuration file. The system evaluates each model in order until one returns a successful `200 OK` response. This linear evaluation keeps logic simple and predictable. You can mix models with different parameter sizes or providers to balance cost and availability. For example, if a high-performance model is unavailable, route the request to a smaller, faster model that meets minimum quality thresholds. This tradeoff maintains service continuity while avoiding expensive retries. { "model": "primary-model-v1", "fallbacks": [ "secondary-model-v2", "tertiary-model-v3" ] } Implement retry logic with exponential backoff to handle transient network errors. Set a maximum retry count to prevent infinite loops. Log failed attempts to monitor which models are underperforming or frequently rate-limited. Use these logs to adjust your fallback order or capacity planning. FastInfra’s API supports this pattern natively. Define your preferred model and fallbacks in the request payload. The platform handles the routing and retries automatically. This reduces client-side code complexity and improves reliability. Review your fallback configuration regularly. Model availability and pricing change over time. Adjust your list to reflect current performance and cost data. For detailed configuration options, see the API documentation.

Balancing Latency vs Cost Tradeoffs

Latency and cost are competing constraints in production inference. Routing logic must prioritize one over the other based on the specific user interaction pattern. Real-time chat interfaces require sub-second responses, making latency the primary metric. Batch processing tasks, such as summarizing large documents overnight, can prioritize cost efficiency because user wait time is irrelevant. FastInfra’s automatic lowest-cost routing evaluates available models against your defined latency thresholds. If a cheaper model exceeds the time limit, the system routes the request to a faster, more expensive alternative. This prevents timeout errors while maintaining budget control. You define the maximum acceptable delay, and the API handles the selection. Use this table to map workload types to routing priorities:
Workload Type vs Routing Priority
Workload Type Primary Metric Secondary Metric Recommended Strategy
Real-time Chat Latency Cost Fastest available model
Document Summary Cost Latency Cheapest available model
Code Generation Quality Latency High-capability model fallback
Batch Data Processing Cost Throughput Spot instance routing
Implement explicit latency caps in your API calls. The following example sets a maximum time-to-first-token threshold. If the selected model cannot meet this requirement, the request fails fast or triggers a fallback, rather than hanging.

{
  "model": "auto",
  "max_tokens": 1000,
  "latency_budget_ms": 200
}
Adjust the `latency_budget_ms` parameter based on user tolerance. For internal tools, higher budgets allow routing to cheaper models like those priced at 0.0108. For customer-facing applications, lower budgets ensure responsiveness. Review your routing performance metrics in the dashboard to refine these thresholds. See API documentation for detailed parameter options.

OpenAI-Compatible API Routing Patterns

A single OpenAI-compatible endpoint abstracts the complexity of 723 underlying models. Your application sends standard JSON payloads, and the platform handles model selection, tokenization, and response formatting. This design eliminates vendor lock-in and reduces the engineering overhead required to support multiple inference providers. The primary benefit is runtime flexibility. You can switch from a high-latency, low-cost model to a faster, more expensive one by changing a single configuration variable. The API contract remains identical. Request bodies, streaming formats, and error codes follow the OpenAI specification, ensuring that existing client libraries work without modification. To implement this pattern, initialize your client with the FastInfra base URL and API key. Specify the model identifier in the request body. The routing layer interprets this identifier and directs the request to the optimal backend.
import openai

client = openai.OpenAI(
    api_key="YOUR_FASTINFRA_KEY",
    base_url="https://api.fastinfra.com/v1"
)

response = client.chat.completions.create(
    model="gpt-3.5-turbo-equivalent",
    messages=[{"role": "user", "content": "Analyze this data."}]
)
Routing decisions can be static or dynamic. Static routing assigns a specific model to a specific endpoint in your configuration. Dynamic routing allows the platform to select the best available model based on real-time metrics like cost, latency, or availability. When using automatic lowest-cost routing, the system evaluates 0.2794 and 0.918 across compatible models. It selects the option that meets your latency requirements while minimizing expenditure. You can override this behavior by pinning to a specific model ID if strict consistency is required for your use case. This approach simplifies testing and deployment. You can evaluate new models in production by routing a small percentage of traffic to them, then scale up based on performance metrics. For detailed configuration options, see the API documentation.

Dynamic Model Selection for Workloads

Dynamic model selection shifts routing decisions from static configuration to runtime logic. Instead of pinning an application to a single model, your code evaluates the incoming request context and selects the optimal endpoint. This approach reduces costs for simple queries while preserving quality for complex tasks. Common workloads fall into distinct categories with different resource requirements: * **Code generation:** Requires high logical consistency and large context windows. * **Chat completions:** Prioritizes low latency and conversational flow. * **Summarization:** Needs efficient processing of large input tokens. * **Classification:** Benefits from small, fast models with minimal overhead. Implementing this pattern requires inspecting the prompt before sending it to the API. You can check for code syntax, question complexity, or explicit user intent. Once classified, your application switches the `model` parameter in the request payload. import requests def route_request(prompt, user_intent): if user_intent == "code": model_id = "fast-infra/code-llama-70b" elif user_intent == "chat": model_id = "fast-infra/mistral-7b-instruct" else: model_id = "fast-infra/default-chat" response = requests.post( "https://api.fastinfra.net/v1/chat/completions", headers={"Authorization": f"Bearer {API_KEY}"}, json={ "model": model_id, "messages": [{"role": "user", "content": prompt}] } ) return response.json() This logic runs client-side or within a lightweight edge function. It ensures that expensive large language models are reserved for tasks that genuinely require their capabilities. Simple classification or keyword matching often suffices for basic routing. For more complex needs, you can use a small embedding model to score semantic similarity against known task patterns. Routing dynamically allows you to leverage the full range of available models. You can access 723 options, including 0 free tiers for testing. By aligning model choice with workload type, you optimize both performance and spend. See the /docs for detailed API parameters and /models for a complete list of available endpoints.

Infrastructure Options for Custom Routing

Automatic routing handles most inference traffic, but custom logic requires dedicated compute. You might need self-hosted routing if your fallback rules depend on proprietary business metrics, real-time user context, or complex state machines that external APIs cannot evaluate. FastInfra provides three infrastructure tiers for this logic. CPU Cloud servers are sufficient for lightweight HTTP proxies that inspect headers and redirect requests. They run continuously without GPU overhead.
curl -X POST https://api.fastinfra.com/v1/chat/completions \
  -H "Authorization: Bearer $API_KEY" \
  -d '{"model": "auto", "messages": [{"role": "user", "content": "test"}]}'
For heavier preprocessing, such as token counting or embedding similarity checks before routing, use per-minute GPU Cloud pods. These scale to zero when idle, so you only pay for the seconds your routing script runs. A single RTX 4090 pod costs 1.20 per hour, making it viable for bursty custom logic. If your routing engine requires persistent state, large local caches, or 24/7 uptime with predictable pricing, dedicated bare-metal servers offer isolation and consistent performance. This avoids the cold-start latency of serverless containers. Spot GPU pods provide a discount for interruptible workloads. Use them for batch routing decisions or offline model selection experiments where interruptions do not impact live users. Choose the infrastructure that matches your routing complexity:
  • Lightweight proxies: CPU Cloud servers starting at 8.90 per month.
  • Bursty preprocessing: Per-minute GPU pods for on-demand compute.
  • Stateful engines: Dedicated bare-metal for persistent memory and low latency.
  • Cost-sensitive batch jobs: Spot GPU pods for discounted, interruptible capacity.
Review the API documentation for standard routing parameters before building custom infrastructure. Most teams find that automatic lowest-cost routing combined with simple model fallbacks covers 90% of use cases.

Related FastInfra resources

Frequently asked questions

Does automatic routing increase latency?

Automatic routing adds minimal overhead, typically milliseconds. The latency gain from selecting a faster, available model often offsets this cost, especially when avoiding queue times on overloaded flagship models.

Can I set maximum price limits?

Yes. You can configure routing rules to cap the maximum price per token. The system will only route to models that meet this budget constraint, ensuring cost control while maintaining functionality.

How do fallbacks handle streaming?

Fallbacks trigger before the first token is generated if the primary model fails. Once the backup model is selected, streaming continues normally, providing a seamless experience to the end user.

Is dynamic selection available for embeddings?

Yes. Dynamic model selection applies to embedding models as well. You can route based on dimension requirements or cost, ensuring efficient vector generation for retrieval tasks.

Do I need to change my code to use mixed fleets?

No. Because the API is OpenAI-compatible, you only need to update the model ID in your request header or payload. The routing logic handles the rest transparently.

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