Introduction
Modern .NET applications increasingly use more than one AI model. A production application might use a smaller model for simple classification, a more capable model for complex reasoning, and another provider as a fallback when the primary service is unavailable.
That creates a routing problem.
Instead of sending every request to one model, the application needs to decide which IChatClient should handle each request. The decision may depend on task complexity, latency, cost, availability, or application policy.
Microsoft.Extensions.AI provides the IChatClient abstraction for interacting with AI services and supports composable client pipelines through ChatClientBuilder. This makes it possible to build routing, caching, telemetry, rate limiting, and other middleware around a common interface.
Routing sounds straightforward, but production routing is not simply:
If request is simple -> Model A
Otherwise -> Model B
A useful router must also consider what happens when a model becomes slow, unavailable, rate-limited, or unexpectedly expensive.
This article shows how to design and benchmark a practical AI routing layer in .NET.
Why AI Model Routing Matters
Different models can have different characteristics.
For example, an application may have:
| Workload | Preferred model characteristic |
|---|---|
| Classification | Low latency |
| Simple extraction | Low cost |
| General chat | Balanced |
| Complex reasoning | Higher capability |
| Large-context analysis | Large context support |
| Fallback | High availability |
Using the most capable model for every request can unnecessarily increase cost and latency.
Using the cheapest model for every request can reduce response quality.
Routing attempts to find a better balance.
A simplified architecture looks like this:
+----------------+
Request ----------->| AI Router |
+-------+--------+
|
+-------------+-------------+
| | |
v v v
Model A Model B Model C
Fast Balanced Advanced
The router becomes an application-level policy engine.
Understanding IChatClient
IChatClient provides a common abstraction for chat-capable AI services. It supports regular and streaming responses and accepts ChatOptions for per-request configuration.
A basic application can work against the abstraction rather than a provider-specific implementation:
using Microsoft.Extensions.AI;
public sealed class AiService(IChatClient chatClient)
{
public async Task<string> AskAsync(
string prompt,
CancellationToken cancellationToken = default)
{
var response = await chatClient.GetResponseAsync(
prompt,
cancellationToken: cancellationToken);
return response.Text;
}
}
The benefit is separation of application logic from the underlying model provider.
The same abstraction can also be wrapped with additional functionality such as distributed caching, telemetry, rate limiting, and custom delegating clients.
That composability is particularly useful for routing.
A Simple Routing Strategy
Start with an explicit routing policy.
For example:
public enum AiTaskType
{
Simple,
General,
Complex
}
Then map each workload to an AI client:
using Microsoft.Extensions.AI;
public sealed class AiRouter(
IChatClient fastClient,
IChatClient generalClient,
IChatClient advancedClient)
{
public IChatClient SelectClient(AiTaskType taskType)
{
return taskType switch
{
AiTaskType.Simple => fastClient,
AiTaskType.General => generalClient,
AiTaskType.Complex => advancedClient,
_ => generalClient
};
}
}
This is static routing.
It is easy to understand and easy to test, but it does not react to runtime conditions.
If the advanced model becomes unavailable, the router still selects it.
Production systems usually need a second layer: availability-aware routing.
Adding Failover
Suppose the primary model fails.
The router can attempt a fallback client:
using Microsoft.Extensions.AI;
public sealed class FallbackChatService(
IChatClient primary,
IChatClient fallback)
{
public async Task<ChatResponse> GetResponseAsync(
IEnumerable<ChatMessage> messages,
CancellationToken cancellationToken = default)
{
try
{
return await primary.GetResponseAsync(
messages,
cancellationToken: cancellationToken);
}
catch (HttpRequestException)
{
return await fallback.GetResponseAsync(
messages,
cancellationToken: cancellationToken);
}
}
}
This demonstrates the basic idea, but production code should not blindly treat every exception as a failover condition.
A validation error should not necessarily cause the request to be sent to another provider.
A useful policy distinguishes failures:
Provider unavailable -> Failover
Rate limited -> Retry/failover
Timeout -> Failover
Invalid request -> Return error
Authentication failure -> Alert/fail safely
Content-policy response -> Apply application policy
The classification should be specific to the providers and infrastructure used by the application.
Latency-Based Routing
Availability is only one dimension.
A model can be technically available while responding too slowly for the application's SLA.
Suppose two models are available:
Model A
Latency: 250 ms
Model B
Latency: 1,500 ms
If the task is simple and both produce acceptable results, Model A may be preferable.
A simple latency-aware policy can maintain rolling measurements:
public sealed record ModelHealth(
string Name,
double AverageLatencyMs,
double FailureRate);
The router can then rank eligible models.
public static ModelHealth SelectFastest(
IEnumerable<ModelHealth> models)
{
return models
.Where(m => m.FailureRate < 0.05)
.OrderBy(m => m.AverageLatencyMs)
.First();
}
The 5% value here is an application policy example, not a universal production threshold.
Thresholds should come from the application's requirements and observed workload.
Cost-Aware Routing
Cost is another routing dimension.
A practical router can assign each request a complexity class:
Simple
-> Low-cost model
Moderate
-> Standard model
Complex
-> Advanced model
For example:
public sealed record RoutingDecision(
string Model,
string Reason);
public static RoutingDecision Route(AiTaskType task)
{
return task switch
{
AiTaskType.Simple =>
new("fast-model", "Simple workload"),
AiTaskType.General =>
new("general-model", "Standard workload"),
AiTaskType.Complex =>
new("advanced-model", "Complex workload"),
_ =>
new("general-model", "Default route")
};
}
The important design principle is to make routing decisions observable.
If the router selects an expensive model, you should be able to determine why.
A Better Routing Pipeline
Routing should not be the only middleware in the AI client pipeline.
Microsoft.Extensions.AI supports composable client functionality. Microsoft documents examples involving distributed caching, function invocation, OpenTelemetry, logging, rate limiting, and custom delegating clients.
A conceptual pipeline can look like:
Application
|
v
Routing
|
v
Rate Limiting
|
v
Telemetry
|
v
Caching
|
v
Provider Client
The exact ordering depends on the desired semantics.
For example, if caching occurs before the provider call, a cache hit may avoid the downstream model request entirely.
Microsoft's documentation shows UseDistributedCache() and UseOpenTelemetry() being composed around an IChatClient.
Benchmarking the Router
A routing implementation should be measured rather than judged by intuition.
At minimum, measure:
Join the conversation! Your thoughts help the community grow.