An application rarely uses the same AI model for every task. A customer support application might need a fast, low-cost model for simple questions and a more capable model for complex requests. A document processing system might use one model for summarization and another for extracting structured information.
Connecting each application directly to multiple AI providers can make this difficult to manage. Developers need to maintain different endpoints, credentials, request formats, and model configurations. When a model changes, the application may also need code changes and another deployment.
Azure AI Gateway provides another approach. It allows administrators to register multiple backend models and publish them through model aliases. An application sends requests to an alias, while the gateway determines which registered model should handle each request.
This separation is useful because the application can continue using the same model name even when the backend configuration changes. The gateway can also distribute requests across multiple models using priorities and weights.
In this article, we will explore how model routing works in Azure AI Gateway, configure an alias with multiple backend models, and call that alias from a C# application. We will also look at weighted traffic distribution, gradual model migration, and the considerations developers should understand before using routing in production.
Understanding Model Aliases and Backend Models
Before configuring routing, it helps to understand three concepts used by Azure AI Gateway: model providers, backend models, and model aliases.
A model provider represents the service that hosts the model. It contains the endpoint and authentication configuration needed by the gateway to communicate with that service. This could be Microsoft Foundry, Azure OpenAI, another supported provider, or a compatible custom endpoint.
A backend model represents a model or deployment registered with the gateway. Registering a backend model does not deploy a new AI model. It makes an existing deployment available through the gateway.
A model alias is the name that applications use when making requests. It can point to one or more registered backend models.
For example, imagine an organization has two chat models:
support-model-small, which is suitable for simple customer questions.
support-model-large, which handles more complicated requests.
Instead of exposing both deployment names directly to the application, the platform team can create an alias called support-chat.
The application sends this name in its request:
{
"model": "support-chat",
"messages": [
{
"role": "user",
"content": "How can I reset my account password?"
}
]
}
The gateway resolves support-chat and selects an eligible backend model according to its routing configuration.
The application does not need to know which backend received the request. It only needs to understand the API contract supported by the alias.
This is the main benefit of aliases: they separate application code from backend model selection.
Registering Multiple Models in Azure AI Gateway
Start by making sure the models you want to use are available as backend models in the gateway.
For example, an organization may already have two deployments in Microsoft Foundry. Import both deployments into Azure AI Gateway and configure the gateway's authentication to access them.
When importing Foundry models, managed identity is a useful option where supported. It allows the gateway to authenticate to the Foundry resource without placing the backend credential in the client application.
After importing the models, open the gateway's model management area and verify that both backend models are registered.
The next step is to create an alias and associate the two models with it.
For this example, use the following logical configuration:
Setting | Model A | Model B |
|---|
Backend model | support-model-small
| support-model-large
|
Alias | support-chat
| support-chat
|
Priority | 0 | 0 |
Weight | 80 | 20 |
Both models have the same priority, so the gateway can distribute eligible requests between them according to their relative weights.
The weights do not represent percentages that must add up to 100. They are relative values. In this example, weights of 80 and 20 represent an intended traffic distribution of approximately 80% and 20% across the two backends over a sufficiently large number of eligible requests.
The actual distribution can vary, particularly with small request volumes or when session affinity is enabled.
There is another important requirement: all backend models behind the same alias must support at least one common API interface. For example, if the application calls the OpenAI Chat Completions endpoint, both backends must support that interface. An Anthropic Messages model cannot simply be mixed with an OpenAI Chat Completions model in the same alias when they do not share a supported interface.
Understanding Priorities and Weights
Azure AI Gateway provides two important routing settings: priority and weight. They solve different problems.
Priority determines the preferred routing tier. A lower priority number is preferred over a higher number. For example, a backend with priority 0 is preferred over one with priority 1.
Weight distributes traffic between eligible backend models within the same priority tier.
Consider this configuration:
Backend model | Priority | Weight |
|---|
Model A | 0 | 80 |
Model B | 0 | 20 |
Model C | 1 | 100 |
Model A and Model B belong to the same priority tier. The gateway can distribute requests between them according to their relative weights.
Model C has a higher priority number, so it belongs to a lower-preference tier. It is not simply included in the same 80/20 distribution.
This distinction matters when designing routing rules. If the goal is to split traffic between two models, assign them the same priority. If one model should be preferred over another, use different priorities.
Priority should not automatically be treated as guaranteed failover. Routing preference and retry behavior are separate concerns. Do not assume that the gateway will always retry another backend whenever the preferred model returns an error. Test the behavior for the gateway configuration and request type you deploy, and implement client-side error handling where required.
Configuring an 80/20 Traffic Split
A weighted split is useful when introducing a new model without immediately moving all application traffic to it.
Suppose an organization currently uses Model A. The team wants to evaluate Model B before making it the primary model.
Instead of changing the application, the platform team can place both models behind the same alias and configure their weights.
The following Azure CLI example illustrates the alias configuration using the Azure AI Gateway CLI:
az aigateway model-alias set \
--resource-group "$RG" \
--gateway-name "$GATEWAY" \
--name "support-chat" \
--description "Weighted routing for support chat" \
--backend-model resource-id="$MODEL_A_ID" priority=0 weight=80 \
--backend-model resource-id="$MODEL_B_ID" priority=0 weight=20
The resource IDs must refer to backend models already registered with the gateway. The gateway name, resource group, and model IDs should come from your Azure environment.
The command configures both models at priority 0. Their weights determine how requests are distributed between them.
After updating the alias, send requests through the gateway and inspect the responses and request traces to determine which backend served each request.
Do not conclude that routing is broken simply because a small test produces a different distribution from the configured ratio. Weighted routing is intended to distribute traffic over requests, not guarantee an exact split over every small batch.
Also review session affinity. If requests carry a session identifier and session affinity is enabled, related requests may continue going to the same backend. This is useful when a conversation should remain associated with one model, but it can make a small test appear to ignore the configured weight distribution.
Calling the Shared Alias From C#
One of the useful parts of model aliases is that the application does not need to change when the gateway's backend routing configuration changes.
A C# application can continue sending requests to the same OpenAI-compatible chat completions endpoint.
Create a simple console application:
dotnet new console -n GatewayModelRouting
cd GatewayModelRouting
Configure the gateway endpoint, runtime API key, and alias through environment variables:
$env:AI_GATEWAY_URL = "https://your-gateway-host/default/models/openai/v1/chat/completions"
$env:AI_GATEWAY_API_KEY = "your-runtime-api-key"
$env:AI_GATEWAY_MODEL = "support-chat"
Use the actual endpoint and runtime key generated for your gateway. The key authenticates the application to the gateway; it is not the credential used by the gateway to access the backend models.
Now create a small client:
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
public sealed class GatewayChatClient
{
private readonly HttpClient _httpClient;
private readonly string _modelAlias;
public GatewayChatClient(
HttpClient httpClient,
string endpoint,
string apiKey,
string modelAlias)
{
_httpClient = httpClient;
_httpClient.BaseAddress = new Uri(endpoint);
_modelAlias = modelAlias;
_httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", apiKey);
}
public async Task<string> SendAsync(
string prompt,
CancellationToken cancellationToken = default)
{
var request = new
{
model = _modelAlias,
messages = new[]
{
new
{
role = "user",
content = prompt
}
}
};
using var response = await _httpClient.PostAsJsonAsync(
"",
request,
cancellationToken);
response.EnsureSuccessStatusCode();
using var document = await JsonDocument.ParseAsync(
await response.Content.ReadAsStreamAsync(
cancellationToken),
cancellationToken: cancellationToken);
return document.RootElement
.GetProperty("choices")[0]
.GetProperty("message")
.GetProperty("content")
.GetString() ?? string.Empty;
}
}
The client accepts a model alias instead of a backend deployment name. This is intentional. The C# application should not need to know whether the request is handled by Model A or Model B.
The request format is the standard OpenAI Chat Completions structure. It works when the alias advertises and supports that interface.
Now use the client from Program.cs:
string endpoint =
Environment.GetEnvironmentVariable("AI_GATEWAY_URL")
?? throw new InvalidOperationException(
"Gateway endpoint is missing.");
string apiKey =
Environment.GetEnvironmentVariable("AI_GATEWAY_API_KEY")
?? throw new InvalidOperationException(
"Gateway API key is missing.");
string modelAlias =
Environment.GetEnvironmentVariable("AI_GATEWAY_MODEL")
?? throw new InvalidOperationException(
"Model alias is missing.");
using var httpClient = new HttpClient
{
Timeout = TimeSpan.FromSeconds(90)
};
var client = new GatewayChatClient(
httpClient,
endpoint,
apiKey,
modelAlias);
Console.Write("Enter your question: ");
string prompt = Console.ReadLine() ?? string.Empty;
if (string.IsNullOrWhiteSpace(prompt))
{
Console.WriteLine("Enter a question.");
return;
}
try
{
string answer = await client.SendAsync(prompt);
Console.WriteLine();
Console.WriteLine("Response:");
Console.WriteLine(answer);
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Gateway request failed: {ex.Message}");
}
catch (TaskCanceledException)
{
Console.WriteLine("The request timed out or was cancelled.");
}
Run the application several times with different prompts. The application continues using support-chat, even though the gateway may select different backend models.
For a production application, register the client with dependency injection using IHttpClientFactory, use secure configuration for credentials, and add structured logging and appropriate retry handling.
Identifying Which Model Served a Request
When multiple models are behind one alias, developers need to know which backend actually handled a request.
This information is important during testing, model evaluation, and production troubleshooting.
The gateway response can identify the backend model that served the request. For example, the response's model field may contain the backend model name and version rather than the alias sent by the client. Foundry-backed models can also provide an x-ms-served-model response header.
The application can capture these details for diagnostics:
string? servedModel = null;
if (response.Headers.TryGetValues(
"x-ms-served-model",
out var values))
{
servedModel = values.FirstOrDefault();
}
The exact headers available depend on the backend and gateway configuration. Do not assume that every provider returns the same metadata.
For more complete visibility, use gateway request traces and monitoring. These help platform teams understand which alias was called, which backend served the request, and how much latency and token usage were associated with it.
Avoid logging complete prompts and responses by default. They may contain customer information or other sensitive content. Capture only the diagnostic details required for monitoring and troubleshooting, and apply the organization's data-retention rules.
Using Weighted Routing for Model Migration
Weighted routing is especially useful when an organization wants to replace an existing model gradually.
Imagine an application that currently sends all requests to Model A. The team has tested Model B in a development environment and wants to introduce it to production users.
A direct replacement moves every request to Model B immediately. If the new model has unexpected latency, different output behavior, or compatibility problems, the application may be affected across all users.
A gradual migration provides more control.
The team can start with a small share of traffic going to Model B while the majority continues using Model A. After reviewing the results, the team can increase the weight assigned to Model B.
For example:
Migration stage | Model A weight | Model B weight |
|---|
Initial test | 95 | 5 |
Wider evaluation | 80 | 20 |
Extended rollout | 50 | 50 |
Final migration | 0 | 100 |
These values are example configurations, not automatic rollout stages. The platform team should decide when to change the weights based on actual evaluation results.
During the rollout, compare response quality, latency, error rates, token consumption, and application-specific outcomes. A model that produces technically valid responses may still behave differently enough to affect the application's business logic.
Also consider session affinity. If the application maintains multi-turn conversations, sending each message to a different model can affect consistency. A session identifier can help keep related requests associated with the same backend when session affinity is configured.
Using Different Aliases for Different Workloads
Not every routing decision needs to happen behind one alias.
An application may have different requirements for different tasks. For example, a customer support system may use one model for quick responses and another for detailed analysis.
The platform team can create separate aliases:
Alias | Intended workload |
|---|
support-fast
| Short, routine customer questions |
support-analysis
| Complex support investigations |
document-summary
| Document summarization |
code-review
| Code analysis and review |
Each alias can have its own backend model mapping and policies.
The C# application can select an alias according to the operation it needs to perform. This is different from sending every request through one alias with multiple backends. Separate aliases make the workload distinction explicit and allow administrators to manage each group independently.
There is an important compatibility requirement here as well. A model alias should only group backends that support the same API interface. If the application needs different API formats, such as OpenAI Chat Completions and Anthropic Messages, use separate aliases and the corresponding gateway endpoints rather than expecting the gateway to translate request formats automatically.
Important Considerations for Production Applications
Weighted routing and aliases simplify model management, but they do not remove the need for application-level reliability.
A gateway routing configuration should be tested under realistic conditions. Check what happens when a backend returns a throttling response, an authentication error, or a server failure. Priority is a routing preference; do not assume it automatically provides guaranteed retry or failover behavior.
Client applications should use bounded retries where appropriate, respect retry guidance such as Retry-After when provided, and avoid retrying non-idempotent operations without considering their effects.
Model compatibility also needs attention. Two models may support the same API endpoint but produce different output structures or behavior. If your application expects structured JSON, tool calls, a particular response format, or a specific context length, test those requirements against every backend behind the alias.
Finally, protect runtime API keys and monitor usage. A runtime key can provide broad access to gateway resources according to the configured access model. Use separate credentials for different applications, rotate them when necessary, and never place them in a public repository or an unprotected desktop application.
Conclusion
Azure AI Gateway allows a .NET application to use multiple AI models through a stable model alias. Instead of connecting directly to each provider, the application sends requests to one gateway endpoint, while the gateway manages the backend model selection.
Priorities and weights provide control over how requests are distributed. Weighted routing is useful for A/B testing and gradual model migration, while separate aliases help organize workloads with different requirements.
For C# developers, the application code can remain simple. It sends a request using the alias and processes the response without needing to know which backend model handled the request.
The most important part is to treat routing as an operational capability, not just a configuration setting. Test model compatibility, monitor which backend serves requests, measure response quality and latency, and verify failure behavior before depending on routing in production.
Join the conversation! Your thoughts help the community grow.