---
title: Fail over to a backup model when a backend fails
summary: Put a deliberately tiny deployment and a healthy backup behind one alias, watch throttling errors reach clients, then add a failure rule that retries on the backup and keeps the throttled backend out for 30 seconds, so every request succeeds.
category: models
level: Intermediate
duration: 30
tracks: [portal, cli, iac, terraform]
order: 3.6
status: new
illustration: diagrams/model-failover.svg
tags: [model alias, failover, retry, failure rules, CEL, HTTP 429, rate limit, temporary exclusion, maxRetryAttempts, high availability, resilience]
objectives:
  - Explain how failure rules, same-backend retries, temporary exclusion, and the retry limit decide where a failed request goes next
  - See throttling errors reach clients when an alias has priorities but no failure rules
  - Fail over to a backup model on HTTP 429 with a CEL failure rule, and prove it with the x-ms-served-model header
  - Keep a throttled backend out of the alias for 30 seconds, and watch it come back
prereqs:
  - 02-first-model-call
---

# Fail over to a backup model when a backend fails

Your chat app calls the `chat-failover` alias, which prefers a `gpt-5-mini` deployment. When that deployment runs
out of capacity, it returns `HTTP 429`, and so do your users' requests. In this lab you make the problem easy to see
with a deliberately tiny primary deployment, then add one failure rule to the alias: a `429` from a backend moves
the request to a healthy backup, `gpt-6.1-sol`, and keeps the throttled backend out of the alias for 30 seconds.
The app keeps sending `"model": "chat-failover"` and never retries on its own.

## Before you begin

<!-- setup: tools sign-in extension clone -->

> [!TIP]
> On the **Bicep + azd** and **Terraform** tracks, `azd up` or `terraform apply` creates its own gateway, both
> deployments, the alias, and a key, so you can skip this section. You need only the one-time setup above.

- Complete [Publish a Foundry model and make your first call](../02-first-model-call/README.md). You need the
  gateway, the `app-first-call` runtime key, and the Foundry account. Lab 02 also gave the gateway the **Foundry
  User** role on your Foundry account, which covers the two new deployments in this lab.
- Recommended: [Route an alias across models by priority and weight](../22-model-routing/README.md) explains
  priority and weight. This lab builds on them.
- Permission to change the gateway, for example **Contributor** on its resource group, and to create deployments
  in the Foundry account.
- Run the scripts from the lab's folder, `~/aigateway/labs/29-model-failover`. The Bash scripts and snippets
  need `curl` and `jq`, which Cloud Shell has.

Set these variables once. Every track and the **Verify** section reuse them.

```bash title="Bash"
# Name your gateway, the Foundry account from lab 02, the two backend models, and the alias that clients call
export RG="<resource-group>"
export GATEWAY="<gateway>"
export FOUNDRY_RG="<foundry-resource-group>"     # resource group of the Foundry account from lab 02
export FOUNDRY_ACCOUNT="<foundry-account-name>"
export PROVIDER="foundry-models"                 # the gateway provider of your Foundry account
export PRIMARY="gpt-5-mini-tiny"                 # the preferred deployment, deliberately tiny
export PRIMARY_VERSION="2025-08-07"
export BACKUP="gpt-6.1-sol"                      # the healthy backup deployment
export BACKUP_VERSION="2026-09-29"
export ALIAS="chat-failover"                     # the name that clients send in "model"
echo "📝 Alias $ALIAS will prefer $PRIMARY and fall back to $BACKUP on gateway $GATEWAY in $RG"

# Read the resource IDs of the gateway and the Foundry account, and the gateway's runtime URL
export GATEWAY_ID="$(az aigateway show -g "$RG" -n "$GATEWAY" --query id -o tsv)"
export FOUNDRY_ID="$(az cognitiveservices account show -g "$FOUNDRY_RG" -n "$FOUNDRY_ACCOUNT" --query id -o tsv)"
export AI_GATEWAY_URL="https://$(az aigateway show -g "$RG" -n "$GATEWAY" --query properties.frontend.defaultHostname -o tsv)"
echo "🆔 Gateway: $GATEWAY_ID"
echo "🌐 Runtime URL: $AI_GATEWAY_URL"

# Build the management URL of the gateway's default workspace, and the API version, for the az rest calls
export WS="https://management.azure.com$GATEWAY_ID/workspaces/default"
export API="api-version=2026-11-01"

# Read the app-first-call key from the gateway, so that it never shows on screen or lands in a file
export AI_GATEWAY_API_KEY="$(az aigateway api-key list-secrets -g "$RG" --gateway-name "$GATEWAY" -n app-first-call \
  --query primaryKey -o tsv)"
echo "🔑 Key: in AI_GATEWAY_API_KEY (${#AI_GATEWAY_API_KEY} characters, not shown)"

# Keep a jq filter that prints the alias's backend models, its retry limit, and its failure rules
export ROUTES='.properties
  | (.backendModels[] | "\(.resourceId | split("/") | last)  priority \(.priority)  weight \(.weight)"),
    "Maximum retries per request: \(.maxRetryAttempts // 0)",
    (if ((.failures // []) | length) == 0 then "Failure rules: none"
     else (.failures | to_entries[] | "Rule \(.key + 1): when \(.value.when)  retries \(.value.retryAttempts // 0)"
       + "  exclude for \(.value.excludeFor // "this request only")") end)'
```

```powershell title="PowerShell"
# Name your gateway, the Foundry account from lab 02, the two backend models, and the alias that clients call
$RG              = "<resource-group>"
$GATEWAY         = "<gateway>"
$FOUNDRY_RG      = "<foundry-resource-group>"    # resource group of the Foundry account from lab 02
$FOUNDRY_ACCOUNT = "<foundry-account-name>"
$PROVIDER        = "foundry-models"              # the gateway provider of your Foundry account
$PRIMARY         = "gpt-5-mini-tiny"             # the preferred deployment, deliberately tiny
$PRIMARY_VERSION = "2025-08-07"
$BACKUP          = "gpt-6.1-sol"                 # the healthy backup deployment
$BACKUP_VERSION  = "2026-09-29"
$ALIAS           = "chat-failover"               # the name that clients send in "model"
Write-Host "📝 Alias $ALIAS will prefer $PRIMARY and fall back to $BACKUP on gateway $GATEWAY in $RG"

# Read the resource IDs of the gateway and the Foundry account, and the gateway's runtime URL
$GATEWAY_ID = az aigateway show -g $RG -n $GATEWAY --query id -o tsv
$FOUNDRY_ID = az cognitiveservices account show -g $FOUNDRY_RG -n $FOUNDRY_ACCOUNT --query id -o tsv
$env:AI_GATEWAY_URL = "https://$(az aigateway show -g $RG -n $GATEWAY --query properties.frontend.defaultHostname -o tsv)"
Write-Host "🆔 Gateway: $GATEWAY_ID"
Write-Host "🌐 Runtime URL: $env:AI_GATEWAY_URL"

# Build the management URL of the gateway's default workspace, and the API version, for the az rest calls
$WS  = "https://management.azure.com$GATEWAY_ID/workspaces/default"
$API = "api-version=2026-11-01"

# Read the app-first-call key from the gateway, so that it never shows on screen or lands in a file
$env:AI_GATEWAY_API_KEY = az aigateway api-key list-secrets -g $RG --gateway-name $GATEWAY -n app-first-call `
  --query primaryKey -o tsv
Write-Host "🔑 Key: in AI_GATEWAY_API_KEY ($($env:AI_GATEWAY_API_KEY.Length) characters, not shown)"

# Define a function that prints the alias's backend models, its retry limit, and its failure rules
function Show-Routes($alias) {
  $p = $alias.properties
  $p.backendModels | ForEach-Object { '{0}  priority {1}  weight {2}' -f ($_.resourceId -split '/')[-1], $_.priority, $_.weight }
  "Maximum retries per request: $([int]$p.maxRetryAttempts)"
  if (-not $p.failures) { 'Failure rules: none' }
  $n = 0
  foreach ($f in $p.failures) {
    $n++
    $exclude = if ($f.excludeFor) { $f.excludeFor } else { 'this request only' }
    'Rule {0}: when {1}  retries {2}  exclude for {3}' -f $n, $f.when, [int]$f.retryAttempts, $exclude
  }
}
```

The CLI and Bicep tracks of lab 02 name the provider `foundry-models`. A portal import names it after your
Foundry account. To check, list the backend models. The **Provider** column shows the provider of each one.

```bash title="Bash"
# List the backend models on the gateway, with the provider that holds each one
echo "✨ Backend models on $GATEWAY:"
az aigateway model list -g "$RG" --gateway-name "$GATEWAY" -o table
```

```powershell title="PowerShell"
# List the backend models on the gateway, with the provider that holds each one
Write-Host "✨ Backend models on ${GATEWAY}:"
az aigateway model list -g $RG --gateway-name $GATEWAY -o table
```

Deploy the two models in your Foundry account. The primary gets capacity `1`, the smallest there is, so that it
returns `HTTP 429` after a couple of requests; a production deployment would be much larger. If you kept
`gpt-6.1-sol` from lab 22 or 27, skip the second command. Model inference is billed per use.

```bash title="Bash"
# Deploy the primary: gpt-5-mini with 1,000 tokens and 1 request per minute of Global Standard capacity
az cognitiveservices account deployment create -g "$FOUNDRY_RG" -n "$FOUNDRY_ACCOUNT" \
  --deployment-name "$PRIMARY" --model-name gpt-5-mini --model-version "$PRIMARY_VERSION" \
  --model-format OpenAI --sku-name GlobalStandard --sku-capacity 1 \
  --query "{name:name, capacity:sku.capacity, state:properties.provisioningState}" &&
  echo "✨ Model deployment $PRIMARY is ready in $FOUNDRY_ACCOUNT"

# Deploy the backup: gpt-6.1-sol with 10,000 tokens and 10 requests per minute
az cognitiveservices account deployment create -g "$FOUNDRY_RG" -n "$FOUNDRY_ACCOUNT" \
  --deployment-name "$BACKUP" --model-name "$BACKUP" --model-version "$BACKUP_VERSION" \
  --model-format OpenAI --sku-name GlobalStandard --sku-capacity 10 \
  --query "{name:name, capacity:sku.capacity, state:properties.provisioningState}" &&
  echo "✨ Model deployment $BACKUP is ready in $FOUNDRY_ACCOUNT"
```

```powershell title="PowerShell"
# Deploy the primary: gpt-5-mini with 1,000 tokens and 1 request per minute of Global Standard capacity
az cognitiveservices account deployment create -g $FOUNDRY_RG -n $FOUNDRY_ACCOUNT `
  --deployment-name $PRIMARY --model-name gpt-5-mini --model-version $PRIMARY_VERSION `
  --model-format OpenAI --sku-name GlobalStandard --sku-capacity 1 `
  --query "{name:name, capacity:sku.capacity, state:properties.provisioningState}"
if ($?) { Write-Host "✨ Model deployment $PRIMARY is ready in $FOUNDRY_ACCOUNT" }

# Deploy the backup: gpt-6.1-sol with 10,000 tokens and 10 requests per minute
az cognitiveservices account deployment create -g $FOUNDRY_RG -n $FOUNDRY_ACCOUNT `
  --deployment-name $BACKUP --model-name $BACKUP --model-version $BACKUP_VERSION `
  --model-format OpenAI --sku-name GlobalStandard --sku-capacity 10 `
  --query "{name:name, capacity:sku.capacity, state:properties.provisioningState}"
if ($?) { Write-Host "✨ Model deployment $BACKUP is ready in $FOUNDRY_ACCOUNT" }
```

## How it works

An alias without failure rules sends each request to one backend model, picked by priority and weight, and returns
whatever that backend answers, errors included. Failure rules tell the gateway what to do when a backend fails:

| Setting | Alias field | Portal | What it does |
|---|---|---|---|
| **Rule condition** | `failures[].when` | **Failure handling** › **Add rule** › **Rule condition** | A CEL expression over the backend's `response`. Rules run in order, and only the first matching rule applies. A failure that matches no rule goes to the client. |
| **Same backend retries** | `failures[].retryAttempts` | **Same backend retries** | Extra attempts on the failed backend before switching. The default, `0`, switches at once. |
| **Temporary exclusion** | `failures[].excludeFor` | **Temporarily exclude the backend after retries** › **Exclusion duration (seconds)** | Keeps the failed backend out of later requests to the alias for a while, up to one day. Without it, the backend is skipped only for the current request. |
| **Maximum retries per request** | `maxRetryAttempts` | **Request retry limit** › **Maximum retries per request** | Caps the extra sends of one request across all backend models, from `0` to `25`. `3` allows four sends in total. The portal suggests `3`. The API default, `0`, leaves a matching rule nowhere to send the request: in our tests, the client then got an empty `HTTP 503` instead of the backend's `429`. |

When a rule matches and its same-backend retries are used up, the gateway skips the failed backend for the rest of
the request and runs the alias's [routing](https://ai.gateway.azure.com/docs/models/routing-order) again over the
remaining backend models: another model in the same priority group first, then the next priority group. So
priorities pick the order of the backups, and the rules decide when to move to them.

![The chat app sends model chat-failover. The gateway tries gpt-5-mini-tiny at priority 0, which returns 429. Rule 1 matches, excludes the primary for 30 seconds, and the request goes to gpt-6.1-sol at priority 1, which returns 200](../assets/diagrams/model-failover.svg "A 429 from the primary matches the rule, so the gateway retries the request on the backup and keeps the primary out for 30 seconds.")

Conditions are [CEL](https://ai.gateway.azure.com/docs/cel-expressions#cel-features) expressions. `response` is `null` when the backend sent no
HTTP response at all, such as a timeout or a refused connection, so check `response != null` before you read
`response.status_code`. Over the API, in Bicep, and in Terraform, wrap each expression in `@cel(…)`; the portal adds
the wrapper.

Not every failure can be recovered:

- **Output already sent.** The gateway retries or switches only before any output reaches the client, and only when
  it can replay the request safely. A stream that fails after its first tokens isn't retried.
- **Stored conversations.** A Responses API request with `previous_response_id` stays on the backend that stored the
  earlier response, and doesn't switch.
- **Policies.** Alias policies run once per request. A same-backend retry doesn't run that model's policies again; a
  switch runs the new model's policies before calling it.

## Create the alias

Register both deployments in the gateway, then create the `chat-failover` alias with `gpt-5-mini-tiny` at priority
`0` and `gpt-6.1-sol` at priority `1`, without failure rules for now.

<!-- track: portal | Portal -->

### Import the two models

1. Open the [AI Gateway portal](https://ai.gateway.azure.com) and select your gateway in the top bar.
2. Select **Models** › **Add** › **Models from Microsoft Foundry**.
3. In **Resource groups**, select the resource group of your Foundry account. Keep **Managed identity** as the
   **Authentication method**, and clear **Create an alias for each model**.

   ![The Models from Microsoft Foundry panel, with one resource group selected, Managed identity, and Create an alias for each model cleared](../assets/screens/failover-01-import.webp "Clear Create an alias for each model: you create one alias for both models in the next step.")

4. In **Models**, make sure only your Foundry account is selected. Its row reads `This model provider already exists
   in your gateway. 2 new models are available.` Select **Add models**. The banner reads `Models imported. 2 model(s)
   were created. No aliases were created.` Select **Close**.

> **Checkpoint**
> **Models** › **Backend models** lists `gpt-5-mini-tiny` and `gpt-6.1-sol`, next to `gpt-5-mini` from lab 02.
> The portal names the new backend model `gpt-6-1-sol` and shows its display name, `gpt-6.1-sol`.

### Create the alias

1. Select **Models** › **Add** › **Alias for existing models**.
2. On **Basics**, set **Alias name** to `chat-failover` and **Description** to `Prefers the tiny deployment`.
   Select **Next**.
3. On **Auto model selection (preview)**, leave the option cleared, and select **Next**.
4. On **Select models**, select `gpt-5-mini-tiny` and `gpt-6.1-sol`. Select **Next**.

   ![The Select models step of Create alias, with gpt-5-mini-tiny and gpt-6.1-sol selected](../assets/screens/failover-02-select-models.webp "Both backend models come from the same Foundry provider and support the same API formats.")

5. On **Session affinity**, clear **Enable session affinity**. Select **Next**.

   ![The Session affinity step with Enable session affinity cleared](../assets/screens/failover-03-session-affinity.webp "Without session affinity, priority alone decides which backend model comes first.")

6. On **Priorities and weights**, set **Priority** to `0` for `gpt-5-mini-tiny` and `1` for `gpt-6.1-sol`. Keep
   both weights at `1`. Select **Next**.

   ![The Priorities and weights step, with priority 0 for gpt-5-mini-tiny and priority 1 for gpt-6.1-sol](../assets/screens/failover-04-priorities.webp "Each model is alone in its priority group, so each has a 100% share within its priority.")

7. On **Failure handling**, keep the defaults, without rules, and select **Next**. You add a rule after you've seen
   the errors.
8. On **Review**, select **Create**.

> **Checkpoint**
> The `chat-failover` alias opens. Its overview shows **Session affinity** **Disabled** and **Routing order**
> **Priorities only**, and its **Backend models** tab shows `gpt-5-mini-tiny` at priority `0` and `gpt-6.1-sol` at
> priority `1`.

<!-- track: cli | Azure CLI -->

### Register the two models

A backend model registers one deployment under the provider. `modelName` must be the deployment's name: the
gateway calls the deployment that it names. If you kept `gpt-6.1-sol` in the gateway from lab 22 or 27, skip the
second command.

```bash title="Bash"
# Register the primary deployment as a backend model under the provider
az aigateway model create -g "$RG" --gateway-name "$GATEWAY" --provider-name "$PROVIDER" -n "$PRIMARY" \
  --display-name "$PRIMARY" --api-format OpenAIChatCompletions \
  --supported-endpoints /openai/v1/chat/completions /openai/v1/responses \
  --deployment-config "{resourceId:$FOUNDRY_ID/deployments/$PRIMARY,modelName:$PRIMARY,modelVersion:$PRIMARY_VERSION}" \
  --query "{name:name, deployment:properties.deployment.modelName}" &&
  echo "✨ Model $PRIMARY is published through $PROVIDER"

# Register the backup deployment the same way
az aigateway model create -g "$RG" --gateway-name "$GATEWAY" --provider-name "$PROVIDER" -n "$BACKUP" \
  --display-name "$BACKUP" --api-format OpenAIChatCompletions \
  --supported-endpoints /openai/v1/chat/completions /openai/v1/responses \
  --deployment-config "{resourceId:$FOUNDRY_ID/deployments/$BACKUP,modelName:$BACKUP,modelVersion:$BACKUP_VERSION}" \
  --query "{name:name, deployment:properties.deployment.modelName}" &&
  echo "✨ Model $BACKUP is published through $PROVIDER"
```

```powershell title="PowerShell"
# Register the primary deployment as a backend model under the provider
az aigateway model create -g $RG --gateway-name $GATEWAY --provider-name $PROVIDER -n $PRIMARY `
  --display-name $PRIMARY --api-format OpenAIChatCompletions `
  --supported-endpoints /openai/v1/chat/completions /openai/v1/responses `
  --deployment-config "{resourceId:$FOUNDRY_ID/deployments/$PRIMARY,modelName:$PRIMARY,modelVersion:$PRIMARY_VERSION}" `
  --query "{name:name, deployment:properties.deployment.modelName}"
if ($?) { Write-Host "✨ Model $PRIMARY is published through $PROVIDER" }

# Register the backup deployment the same way
az aigateway model create -g $RG --gateway-name $GATEWAY --provider-name $PROVIDER -n $BACKUP `
  --display-name $BACKUP --api-format OpenAIChatCompletions `
  --supported-endpoints /openai/v1/chat/completions /openai/v1/responses `
  --deployment-config "{resourceId:$FOUNDRY_ID/deployments/$BACKUP,modelName:$BACKUP,modelVersion:$BACKUP_VERSION}" `
  --query "{name:name, deployment:properties.deployment.modelName}"
if ($?) { Write-Host "✨ Model $BACKUP is published through $PROVIDER" }
```

### Create the alias

Each `--backend-model` adds an entry to the alias's `backendModels` list, with a `resource-id`, a `priority`, and
a `weight`.

```bash title="Bash"
# Build the resource ID prefix of the provider's backend models, which each --backend-model entry uses
export MODELS="$GATEWAY_ID/workspaces/default/modelProviders/$PROVIDER/models"

# Create or update the alias with the primary at priority 0 and the backup at priority 1, then print it
az aigateway model-alias set -g "$RG" --gateway-name "$GATEWAY" -n "$ALIAS" \
  --description "Prefers the tiny deployment" \
  --backend-model resource-id="$MODELS/$PRIMARY" priority=0 weight=1 \
  --backend-model resource-id="$MODELS/$BACKUP" priority=1 weight=1 \
  --only-show-errors -o none &&
  echo "🔖 Alias $ALIAS routes to:" &&
  az aigateway model-alias show -g "$RG" --gateway-name "$GATEWAY" -n "$ALIAS" | jq -r "$ROUTES"
```

```powershell title="PowerShell"
# Build the resource ID prefix of the provider's backend models, which each --backend-model entry uses
$MODELS = "$GATEWAY_ID/workspaces/default/modelProviders/$PROVIDER/models"

# Create or update the alias with the primary at priority 0 and the backup at priority 1, then print it
az aigateway model-alias set -g $RG --gateway-name $GATEWAY -n $ALIAS `
  --description "Prefers the tiny deployment" `
  --backend-model resource-id="$MODELS/$PRIMARY" priority=0 weight=1 `
  --backend-model resource-id="$MODELS/$BACKUP" priority=1 weight=1 `
  --only-show-errors -o none
if ($?) {
  Write-Host "🔖 Alias $ALIAS routes to:"
  Show-Routes (az aigateway model-alias show -g $RG --gateway-name $GATEWAY -n $ALIAS | ConvertFrom-Json)
}
```

> **Checkpoint**
> The output shows `gpt-5-mini-tiny  priority 0  weight 1`, `gpt-6.1-sol  priority 1  weight 1`,
> `Maximum retries per request: 0`, and `Failure rules: none`.

<!-- track: iac | Bicep + azd -->

**What you need:** only the one-time setup from **Before you begin**. This track doesn't use your gateway from lab 02:
`azd up` creates a new one, so it works on its own.

### Review the templates

`infra/main.bicep` creates the resource group `rg-<environment name>` and calls the quick start's
[resources.bicep](../quickstart/infra/resources.bicep) for the gateway, the Foundry account with `gpt-5-mini`, its
default alias, and the `app-first-call` key. Then it adds the two deployments and publishes the `chat-failover`
alias:

<!-- include: infra/main.bicep -->

`infra/deployments.bicep` deploys the tiny primary, with capacity `1`, and the backup, one after the other:

<!-- include: infra/deployments.bicep -->

`infra/failover-alias.bicep` registers both deployments and writes the alias. `FAILOVER` picks one of two shapes:
`off` gives the alias priorities only, and `on` adds `maxRetryAttempts` and the failure rule for `429`. You can
also deploy this file on its own to the gateway from lab 02, once both deployments exist.

<!-- include: infra/failover-alias.bicep -->

### Deploy with azd up

Move into the lab's folder, create an azd environment named `aigw-lab29` in your current subscription, then
provision everything. It takes about five minutes.

```bash title="Bash"
# Move into the lab's folder, which holds the azd project
cd ~/aigateway/labs/29-model-failover &&
  echo "📂 Lab folder: $(pwd)"

# Create an azd environment named aigw-lab29 in your current subscription, so that azd doesn't prompt you
azd env new aigw-lab29 --location eastus2 --subscription "$(az account show --query id --output tsv)" &&
  echo "📝 azd environment aigw-lab29 deploys to eastus2"

# Provision the resource group, the gateway, the Foundry account with three deployments, the alias, and the key
azd up &&
  echo "🚀 Gateway deployed: $(azd env get-value AI_GATEWAY_URL)"
```

```powershell title="PowerShell"
# Move into the lab's folder, which holds the azd project
Set-Location ~/aigateway/labs/29-model-failover
if ($?) { Write-Host "📂 Lab folder: $(Get-Location)" }

# Create an azd environment named aigw-lab29 in your current subscription, so that azd doesn't prompt you
azd env new aigw-lab29 --location eastus2 --subscription (az account show --query id --output tsv)
if ($?) { Write-Host "📝 azd environment aigw-lab29 deploys to eastus2" }

# Provision the resource group, the gateway, the Foundry account with three deployments, the alias, and the key
azd up
if ($?) { Write-Host "🚀 Gateway deployed: $(azd env get-value AI_GATEWAY_URL)" }
```

For another region, pick one where AI Gateway and the `gpt-5-mini` and `gpt-6.1-sol` models are available, as in
[Find the available regions](../SETUP.md#find-the-available-regions). The parameters come from azd environment
values, with the defaults in `infra/main.parameters.json`: `FAILOVER` (`off`), `FAILOVER_EXCLUDE_FOR` (`PT30S`),
`BACKUP_MODEL` (`gpt-6.1-sol`), and `BACKUP_MODEL_VERSION` (`2026-09-29`).

### Read the outputs and the key

Set the variables that the next sections and **Verify** use from azd's environment values, read the key from the
gateway so that it never shows on screen, then print the alias.

```bash title="Bash"
# Read azd's outputs into the variables that the next sections use
export RG="$(azd env get-value AZURE_RESOURCE_GROUP)"
export GATEWAY="$(azd env get-value AI_GATEWAY_NAME)"
export GATEWAY_ID="$(azd env get-value AI_GATEWAY_ID)"
export PROVIDER="$(azd env get-value AI_GATEWAY_PROVIDER)"
export PRIMARY="$(azd env get-value AI_GATEWAY_BACKEND_MODEL)"
export BACKUP="$(azd env get-value AI_GATEWAY_BACKUP_MODEL)"
export ALIAS="$(azd env get-value AI_GATEWAY_MODEL)"
export FOUNDRY_ID="$(azd env get-value FOUNDRY_ACCOUNT_ID)"
export AI_GATEWAY_URL="$(azd env get-value AI_GATEWAY_URL)"
echo "📝 Alias $ALIAS prefers $PRIMARY and falls back to $BACKUP on gateway $GATEWAY in $RG"
echo "🌐 Runtime URL: $AI_GATEWAY_URL"

# Read the app-first-call key from the gateway, so that it never shows on screen or lands in a file
export AI_GATEWAY_API_KEY="$(az aigateway api-key list-secrets --ids "$GATEWAY_ID/apiKeys/app-first-call" \
  --query primaryKey --output tsv)"
echo "🔑 Key: in AI_GATEWAY_API_KEY (${#AI_GATEWAY_API_KEY} characters, not shown)"

# Keep a jq filter that prints the alias's backend models, its retry limit, and its failure rules, then print them
export ROUTES='.properties
  | (.backendModels[] | "\(.resourceId | split("/") | last)  priority \(.priority)  weight \(.weight)"),
    "Maximum retries per request: \(.maxRetryAttempts // 0)",
    (if ((.failures // []) | length) == 0 then "Failure rules: none"
     else (.failures | to_entries[] | "Rule \(.key + 1): when \(.value.when)  retries \(.value.retryAttempts // 0)"
       + "  exclude for \(.value.excludeFor // "this request only")") end)'
echo "🔖 Alias $ALIAS routes to:"
az aigateway model-alias show -g "$RG" --gateway-name "$GATEWAY" -n "$ALIAS" | jq -r "$ROUTES"
```

```powershell title="PowerShell"
# Read azd's outputs into the variables that the next sections use
$RG                     = azd env get-value AZURE_RESOURCE_GROUP
$GATEWAY                = azd env get-value AI_GATEWAY_NAME
$GATEWAY_ID             = azd env get-value AI_GATEWAY_ID
$PROVIDER               = azd env get-value AI_GATEWAY_PROVIDER
$PRIMARY                = azd env get-value AI_GATEWAY_BACKEND_MODEL
$BACKUP                 = azd env get-value AI_GATEWAY_BACKUP_MODEL
$ALIAS                  = azd env get-value AI_GATEWAY_MODEL
$FOUNDRY_ID             = azd env get-value FOUNDRY_ACCOUNT_ID
$env:AI_GATEWAY_URL     = azd env get-value AI_GATEWAY_URL
Write-Host "📝 Alias $ALIAS prefers $PRIMARY and falls back to $BACKUP on gateway $GATEWAY in $RG"
Write-Host "🌐 Runtime URL: $env:AI_GATEWAY_URL"

# Read the app-first-call key from the gateway, so that it never shows on screen or lands in a file
$env:AI_GATEWAY_API_KEY = az aigateway api-key list-secrets --ids "$GATEWAY_ID/apiKeys/app-first-call" `
  --query primaryKey --output tsv
Write-Host "🔑 Key: in AI_GATEWAY_API_KEY ($($env:AI_GATEWAY_API_KEY.Length) characters, not shown)"

# Define a function that prints the alias's backend models, its retry limit, and its failure rules, then print them
function Show-Routes($alias) {
  $p = $alias.properties
  $p.backendModels | ForEach-Object { '{0}  priority {1}  weight {2}' -f ($_.resourceId -split '/')[-1], $_.priority, $_.weight }
  "Maximum retries per request: $([int]$p.maxRetryAttempts)"
  if (-not $p.failures) { 'Failure rules: none' }
  $n = 0
  foreach ($f in $p.failures) {
    $n++
    $exclude = if ($f.excludeFor) { $f.excludeFor } else { 'this request only' }
    'Rule {0}: when {1}  retries {2}  exclude for {3}' -f $n, $f.when, [int]$f.retryAttempts, $exclude
  }
}
Write-Host "🔖 Alias $ALIAS routes to:"
Show-Routes (az aigateway model-alias show -g $RG --gateway-name $GATEWAY -n $ALIAS | ConvertFrom-Json)
```

> **Checkpoint**
> `azd up` ended with `SUCCESS`, and the last command printed `gpt-5-mini-tiny  priority 0  weight 1`,
> `gpt-6.1-sol  priority 1  weight 1`, `Maximum retries per request: 0`, and `Failure rules: none`.

<!-- track: terraform | Terraform -->

**What you need:** only the one-time setup from **Before you begin**, plus Terraform 1.9 or later, as in
[Deploy a lab with Terraform](../SETUP.md#deploy-a-lab-with-terraform). This track doesn't use your gateway from
lab 02: `terraform apply` creates a new one, so it works on its own.

### Review the configuration

The configuration deploys the same resources as the Bicep templates. `terraform/main.tf` creates the resource group
`rg-<environment_name>` and calls the quick start's [resources module](../quickstart/terraform/resources) for the
gateway, the Foundry account with `gpt-5-mini`, its default alias, and the `app-first-call` key:

<!-- include: terraform/main.tf -->

`terraform/deployments.tf` deploys the tiny primary, with capacity `1`, and the backup, one after the other:

<!-- include: terraform/deployments.tf -->

`terraform/failover-alias.tf` registers both deployments and writes the alias with the `azapi` provider. The
`failover` variable picks one of two shapes: `off` gives the alias priorities only, and `on` adds
`maxRetryAttempts` and the failure rule for `429`. `terraform/variables.tf` declares the settings with the same
defaults as the Bicep template: `failover` (`off`), `exclude_for` (`PT30S`), `backup_model_name` (`gpt-6.1-sol`),
and `backup_model_version` (`2026-09-29`).

<!-- include: terraform/failover-alias.tf -->

### Deploy with terraform apply

Move into the lab's Terraform folder, select your current subscription, then plan and apply the configuration. It
takes a few minutes, most of it while the new gateway activates.

```bash title="Bash"
# Move into the lab's Terraform folder
cd ~/aigateway/labs/29-model-failover/terraform &&
  echo "📂 Terraform folder: $(pwd)"

# Deploy to the Azure CLI's current subscription
export ARM_SUBSCRIPTION_ID="$(az account show --query id --output tsv)" &&
  echo "📍 Subscription: $ARM_SUBSCRIPTION_ID"

# Download the providers, then plan and apply the resource group, the gateway, the Foundry account with three
# deployments, the alias, and the key
terraform init &&
  terraform plan -out tfplan &&
  terraform apply tfplan &&
  echo "🚀 Gateway deployed: $(terraform output -raw ai_gateway_url)"
```

```powershell title="PowerShell"
# Move into the lab's Terraform folder
Set-Location ~/aigateway/labs/29-model-failover/terraform
if ($?) { Write-Host "📂 Terraform folder: $(Get-Location)" }

# Deploy to the Azure CLI's current subscription
$env:ARM_SUBSCRIPTION_ID = az account show --query id --output tsv
if ($?) { Write-Host "📍 Subscription: $env:ARM_SUBSCRIPTION_ID" }

# Download the providers, then plan and apply the resource group, the gateway, the Foundry account with three
# deployments, the alias, and the key
terraform init
if ($?) { terraform plan -out tfplan }
if ($?) { terraform apply tfplan }
if ($?) { Write-Host "🚀 Gateway deployed: $(terraform output -raw ai_gateway_url)" }
```

The configuration deploys to `eastus2`. For another region where AI Gateway and the `gpt-5-mini` and `gpt-6.1-sol`
models are available, as in [Find the available regions](../SETUP.md#find-the-available-regions), run
`export TF_VAR_location=<region>` (PowerShell: `$env:TF_VAR_location = "<region>"`) before `terraform plan`.

### Read the outputs and the key

Set the variables that the next sections and **Verify** use from the Terraform outputs, read the key from the
gateway so that it never shows on screen or lands in the Terraform state, then print the alias. Last, move back to
the lab's folder, where the next sections run the burst script.

```bash title="Bash"
# Read the configuration's outputs into the variables that the next sections use
export RG="$(terraform output -raw azure_resource_group)"
export GATEWAY="$(terraform output -raw ai_gateway_name)"
export GATEWAY_ID="$(terraform output -raw ai_gateway_id)"
export PROVIDER="$(terraform output -raw ai_gateway_provider)"
export PRIMARY="$(terraform output -raw ai_gateway_backend_model)"
export BACKUP="$(terraform output -raw ai_gateway_backup_model)"
export ALIAS="$(terraform output -raw ai_gateway_model)"
export FOUNDRY_ID="$(terraform output -raw foundry_account_id)"
export AI_GATEWAY_URL="$(terraform output -raw ai_gateway_url)"
echo "📝 Alias $ALIAS prefers $PRIMARY and falls back to $BACKUP on gateway $GATEWAY in $RG"
echo "🌐 Runtime URL: $AI_GATEWAY_URL"

# Read the app-first-call key from the gateway, so that it never lands in a file or the Terraform state
export AI_GATEWAY_API_KEY="$(az aigateway api-key list-secrets --ids "$GATEWAY_ID/apiKeys/app-first-call" \
  --query primaryKey --output tsv)"
echo "🔑 Key: in AI_GATEWAY_API_KEY (${#AI_GATEWAY_API_KEY} characters, not shown)"

# Keep a jq filter that prints the alias's backend models, its retry limit, and its failure rules, then print them
export ROUTES='.properties
  | (.backendModels[] | "\(.resourceId | split("/") | last)  priority \(.priority)  weight \(.weight)"),
    "Maximum retries per request: \(.maxRetryAttempts // 0)",
    (if ((.failures // []) | length) == 0 then "Failure rules: none"
     else (.failures | to_entries[] | "Rule \(.key + 1): when \(.value.when)  retries \(.value.retryAttempts // 0)"
       + "  exclude for \(.value.excludeFor // "this request only")") end)'
echo "🔖 Alias $ALIAS routes to:"
az aigateway model-alias show -g "$RG" --gateway-name "$GATEWAY" -n "$ALIAS" | jq -r "$ROUTES"

# Move back to the lab's folder, where the next sections run the burst script
cd .. &&
  echo "📂 Lab folder: $(pwd)"
```

```powershell title="PowerShell"
# Read the configuration's outputs into the variables that the next sections use
$RG                     = terraform output -raw azure_resource_group
$GATEWAY                = terraform output -raw ai_gateway_name
$GATEWAY_ID             = terraform output -raw ai_gateway_id
$PROVIDER               = terraform output -raw ai_gateway_provider
$PRIMARY                = terraform output -raw ai_gateway_backend_model
$BACKUP                 = terraform output -raw ai_gateway_backup_model
$ALIAS                  = terraform output -raw ai_gateway_model
$FOUNDRY_ID             = terraform output -raw foundry_account_id
$env:AI_GATEWAY_URL     = terraform output -raw ai_gateway_url
Write-Host "📝 Alias $ALIAS prefers $PRIMARY and falls back to $BACKUP on gateway $GATEWAY in $RG"
Write-Host "🌐 Runtime URL: $env:AI_GATEWAY_URL"

# Read the app-first-call key from the gateway, so that it never lands in a file or the Terraform state
$env:AI_GATEWAY_API_KEY = az aigateway api-key list-secrets --ids "$GATEWAY_ID/apiKeys/app-first-call" `
  --query primaryKey --output tsv
Write-Host "🔑 Key: in AI_GATEWAY_API_KEY ($($env:AI_GATEWAY_API_KEY.Length) characters, not shown)"

# Define a function that prints the alias's backend models, its retry limit, and its failure rules, then print them
function Show-Routes($alias) {
  $p = $alias.properties
  $p.backendModels | ForEach-Object { '{0}  priority {1}  weight {2}' -f ($_.resourceId -split '/')[-1], $_.priority, $_.weight }
  "Maximum retries per request: $([int]$p.maxRetryAttempts)"
  if (-not $p.failures) { 'Failure rules: none' }
  $n = 0
  foreach ($f in $p.failures) {
    $n++
    $exclude = if ($f.excludeFor) { $f.excludeFor } else { 'this request only' }
    'Rule {0}: when {1}  retries {2}  exclude for {3}' -f $n, $f.when, [int]$f.retryAttempts, $exclude
  }
}
Write-Host "🔖 Alias $ALIAS routes to:"
Show-Routes (az aigateway model-alias show -g $RG --gateway-name $GATEWAY -n $ALIAS | ConvertFrom-Json)

# Move back to the lab's folder, where the next sections run the burst script
Set-Location ..
if ($?) { Write-Host "📂 Lab folder: $(Get-Location)" }
```

> **Checkpoint**
> `terraform apply` ended with `Apply complete! Resources: 14 added, 0 changed, 0 destroyed.`, and the alias printed
> `gpt-5-mini-tiny  priority 0  weight 1`, `gpt-6.1-sol  priority 1  weight 1`, `Maximum retries per request: 0`, and
> `Failure rules: none`.

<!-- /tracks -->

## See the 429s without failover

Send 20 requests to `chat-failover`, one about every second, like a busy chat app. For each request, the script
prints the HTTP status, the `x-ms-served-model` response header, which names the model that answered, and the
`Retry-After` header of errors.

```bash title="Bash"
# Send 20 requests to the alias, with a 1-second pause between them, and count the outcomes
echo "🚦 Sending a burst to $ALIAS without failure rules"
./infra/burst.sh "$ALIAS" 20 1
```

```powershell title="PowerShell"
# Send 20 requests to the alias, with a 1-second pause between them, and count the outcomes
Write-Host "🚦 Sending a burst to $ALIAS without failure rules"
./infra/burst.ps1 -Alias $ALIAS -Count 20 -PauseSeconds 1
```

```text
Sending 20 requests with "model": "chat-failover"
#    Time   Status  Served by                  Retry-After
1    3s     200     gpt-5-mini-2025-08-07      -
2    6s     200     gpt-5-mini-2025-08-07      -
3    8s     429     -                          30
4    10s    429     -                          30
5    12s    429     -                          30
6    16s    200     gpt-6.1-sol-2026-09-29     -
...
12   42s    200     gpt-6.1-sol-2026-09-29     -
13   44s    429     -                          30
14   46s    429     -                          30
15   48s    429     -                          30
16   52s    200     gpt-6.1-sol-2026-09-29     -
...
20   67s    200     gpt-6.1-sol-2026-09-29     -

Outcomes:
  12 200 gpt-6.1-sol-2026-09-29
   6 429
   2 200 gpt-5-mini-2025-08-07
```

The first two requests fit in the primary's capacity. Then the primary answers `429`, and the gateway passes each
`429` to the client, with the primary's `Retry-After: 30`: priority prefers a backend, it doesn't fail over. The
`429` body reads `Your requests to gpt-5-mini for gpt-5-mini-tiny in <region> have exceeded request rate limit`.

In our tests, after three `429`s in a row, the gateway also stopped choosing the primary for about 30 seconds on its
own, so `gpt-6.1-sol` served the next requests, and then the cycle repeated. The product docs don't describe this
protection, and it doesn't save the requests that reach the throttled primary: six of 20 requests failed. A failure
rule saves them.

> **Checkpoint**
> Some requests show `429` with `Retry-After` `30`, and none of them show a served model. Your counts can differ
> slightly.

## Turn on failover

Add one failure rule to the alias: when a backend answers `429`, switch the request to the next backend model at
once, and keep the throttled backend out of the alias for 30 seconds. Cap each request at three extra sends.

<!-- track: portal | Portal -->

### Add a failure rule

1. In **Models** › **Aliases**, open `chat-failover`, and select **Edit**. The alias opens on one page, with a
   section for each step.
2. In **Failure handling**, under **Rules**, select **Add rule**.
3. In **Add failure rule**, replace the **Rule condition** with this expression, without the `@cel()` wrapper:

   ```text
   response != null && response.status_code == 429
   ```

   Keep **Same backend retries** at `0`, keep **Temporarily exclude the backend after retries** selected, and keep
   **Exclusion duration (seconds)** at `30`. Select **Apply**.

   ![The Add failure rule dialog, with the 429 condition, Same backend retries 0, and a 30-second exclusion](../assets/screens/failover-05-add-rule.webp "With 0 same-backend retries, the first 429 switches the request and excludes the backend for 30 seconds.")

4. Under **Request retry limit**, check that **Maximum retries per request** is `3`. The field appears once the
   alias has a rule. Select **Save**.

   ![The Failure handling section of Edit alias, with Maximum retries per request 3 and Rule 1 in the rules table](../assets/screens/failover-06-rules.webp "Rules run in order, and only the first matching rule applies.")

> **Checkpoint**
> The alias overview shows **Failure handling** with **Maximum retries per request** `3`, and **Rule 1** with a
> **Custom condition**, `0 (default)` same-backend retries, and a `30 s` exclusion.
>
> ![The Failure handling section of the alias overview](../assets/screens/failover-07-overview.webp "The overview summarizes the retry limit and each rule.")

<!-- track: cli | Azure CLI -->

### Add a failure rule

The `az aigateway model-alias` commands have no options yet for failure rules or the retry limit, so this step
sends them to the management API with `az rest`, at API version `2026-11-01`. A `PATCH` changes only the fields that
it sends, and keeps the backend models. Send `maxRetryAttempts` with the rules: its default, `0`, allows no send to
the backup. Later `az aigateway model-alias set` and `update` commands keep the rules and the retry limit.

```bash title="Bash"
# Build the change: up to 3 extra sends per request, and one rule that switches on 429 and excludes the backend for 30 s
BODY="$(jq -cn '{properties: {
  maxRetryAttempts: 3,
  failures: [{when: "@cel(response != null && response.status_code == 429)", excludeFor: "PT30S"}]}}')"

# Update the alias, then print it
echo "🔖 Alias $ALIAS routes to:"
az rest --method patch --url "$WS/aliases/$ALIAS?$API" --body "$BODY" | jq -r "$ROUTES"
```

```powershell title="PowerShell"
# Build the change: up to 3 extra sends per request, and one rule that switches on 429 and excludes the backend for 30 s
# Write it to a file, which --body reads with the @ prefix, so that its quotes reach az intact
@{ properties = @{
    maxRetryAttempts = 3
    failures         = @(@{ when = '@cel(response != null && response.status_code == 429)'; excludeFor = 'PT30S' }) } } |
  ConvertTo-Json -Depth 10 -Compress | Set-Content -Path failover.json

# Update the alias, print it, and delete the file
Write-Host "🔖 Alias $ALIAS routes to:"
Show-Routes (az rest --method patch --url "$WS/aliases/${ALIAS}?$API" --body '@failover.json' | ConvertFrom-Json)
Remove-Item failover.json
```

> **Checkpoint**
> The output ends with `Maximum retries per request: 3` and
> `Rule 1: when @cel(response != null && response.status_code == 429)  retries 0  exclude for PT30S`.

<!-- track: iac | Bicep + azd -->

### Provision with failover on

Set `FAILOVER` to `on` and provision again. Only the alias changes: it gets `maxRetryAttempts: 3` and the failure
rule, with `excludeFor` from `FAILOVER_EXCLUDE_FOR`.

```bash title="Bash"
# Turn on the template's failure rule
azd env set FAILOVER on &&
  echo "📝 FAILOVER is on"

# Provision again: only the alias changes
azd provision &&
  echo "🚀 The $ALIAS alias now fails over on 429"
```

```powershell title="PowerShell"
# Turn on the template's failure rule
azd env set FAILOVER on
if ($?) { Write-Host "📝 FAILOVER is on" }

# Provision again: only the alias changes
azd provision
if ($?) { Write-Host "🚀 The $ALIAS alias now fails over on 429" }
```

To go back to priorities only, run `azd env set FAILOVER off` and `azd provision`.

> **Checkpoint**
> `azd provision` ended with `SUCCESS`. **Read the alias** in **Verify** shows `Maximum retries per request: 3` and
> the `429` rule with `exclude for PT30S`.

<!-- track: terraform | Terraform -->

### Apply with failover on

Plan with `failover` set to `on`, then apply the plan. Only the alias changes: it gets `maxRetryAttempts: 3` and the
failure rule, with `excludeFor` from `exclude_for`. You're in the lab's folder, so `-chdir` points Terraform at the
`terraform` folder.

```bash title="Bash"
# Plan the change: turn on the configuration's failure rule
terraform -chdir=terraform plan -var failover=on -out tfplan &&
  echo "📝 The plan updates only the $ALIAS alias"

# Apply the plan
terraform -chdir=terraform apply tfplan &&
  echo "🚀 The $ALIAS alias now fails over on 429"
```

```powershell title="PowerShell"
# Plan the change: turn on the configuration's failure rule
terraform -chdir=terraform plan -var failover=on -out tfplan
if ($?) { Write-Host "📝 The plan updates only the $ALIAS alias" }

# Apply the plan
terraform -chdir=terraform apply tfplan
if ($?) { Write-Host "🚀 The $ALIAS alias now fails over on 429" }
```

To go back to priorities only, plan and apply again without `-var`.

> **Checkpoint**
> The plan ended with `Plan: 0 to add, 1 to change, 0 to destroy.`, for `azapi_resource.alias`. **Read the alias**
> in **Verify** shows `Maximum retries per request: 3` and the `429` rule with `exclude for PT30S`.

<!-- /tracks -->

## Watch the failover

Wait a minute, so that the primary has capacity again, then send the same burst.

```bash title="Bash"
# Send the same burst of 20 requests, now with the failure rule
echo "🚦 Sending a burst to $ALIAS with failover"
./infra/burst.sh "$ALIAS" 20 1
```

```powershell title="PowerShell"
# Send the same burst of 20 requests, now with the failure rule
Write-Host "🚦 Sending a burst to $ALIAS with failover"
./infra/burst.ps1 -Alias $ALIAS -Count 20 -PauseSeconds 1
```

```text
Sending 20 requests with "model": "chat-failover"
#    Time   Status  Served by                  Retry-After
1    2s     200     gpt-5-mini-2025-08-07      -
2    4s     200     gpt-5-mini-2025-08-07      -
3    8s     200     gpt-6.1-sol-2026-09-29     -
4    12s    200     gpt-6.1-sol-2026-09-29     -
...
18   68s    200     gpt-6.1-sol-2026-09-29     -
19   71s    200     gpt-5-mini-2025-08-07      -
20   75s    200     gpt-6.1-sol-2026-09-29     -

Outcomes:
  17 200 gpt-6.1-sol-2026-09-29
   3 200 gpt-5-mini-2025-08-07
```

Every request succeeds. Request 3 reached the primary, got `429`, matched the rule, and the gateway sent it again to
`gpt-6.1-sol` before it answered the client, so the client saw only the `200`. The rule also excluded the primary
for 30 seconds, so the next requests went straight to the backup. Each time the exclusion ends, the gateway tries
the primary again: if it's still throttled, one more `429` excludes it for another 30 seconds; once it has capacity,
it serves requests again, as request 19 shows.

> **Checkpoint**
> All 20 requests show `200`, with no `Retry-After`. Most show `gpt-6.1-sol-2026-09-29`, and the first ones show
> `gpt-5-mini-2025-08-07`.

### See what the primary saw

The client can't tell that a request was retried. The primary's own metrics can: Foundry counts its requests by
status code. Metrics take two or three minutes to appear, so wait, then print the primary's requests per minute,
in UTC, for the last 15 minutes.

```bash title="Bash"
# Print the requests to the primary deployment per minute (UTC) in the last 15 minutes, by HTTP status code
echo "📊 Requests to $PRIMARY per minute, by status code:"
az monitor metrics list --resource "$FOUNDRY_ID" --metric AzureOpenAIRequests \
  --filter "ModelDeploymentName eq '$PRIMARY' and StatusCode eq '*'" \
  --interval PT1M --aggregation Total --offset 15m -o json |
  jq -r '.value[0].timeseries[]
    | (.metadatavalues[] | select(.name.value | ascii_downcase == "statuscode") | .value) as $code
    | .data[] | select((.total // 0) > 0) | "\(.timeStamp[11:16])  status \($code)  \(.total | floor)"' | sort
```

```powershell title="PowerShell"
# Print the requests to the primary deployment per minute (UTC) in the last 15 minutes, by HTTP status code
Write-Host "📊 Requests to $PRIMARY per minute, by status code:"
$metrics = az monitor metrics list --resource $FOUNDRY_ID --metric AzureOpenAIRequests `
  --filter "ModelDeploymentName eq '$PRIMARY' and StatusCode eq '*'" `
  --interval PT1M --aggregation Total --offset 15m -o json | ConvertFrom-Json
$metrics.value[0].timeseries | ForEach-Object {
  $code = ($_.metadatavalues | Where-Object { $_.name.value -eq 'statuscode' }).value
  $_.data | Where-Object { $_.total -gt 0 } | ForEach-Object {
    '{0:HH:mm}  status {1}  {2}' -f ([datetime]$_.timeStamp).ToUniversalTime(), $code, [int]$_.total }
} | Sort-Object
```

```text
📊 Requests to gpt-5-mini-tiny per minute, by status code:
03:15  status 200  2
03:16  status 429  6
03:18  status 200  2
03:18  status 429  2
```

The first burst shows the six `429`s that reached your clients. The second burst shows only two or three: each
`429` kept the primary out for 30 seconds, and the backup served the requests in between. The requests that got
`429` from the primary were retried on the backup, so no client saw them.

> **Checkpoint**
> The primary shows fewer `429`s for the second burst than for the first, even though every client request got
> `200`. If the output is empty or misses the last minutes, wait a minute and run it again.

## Verify

<!-- steps -->

### Read the alias

```bash title="Bash"
# Read the alias, and print its backend models, retry limit, and failure rules
echo "🔖 Alias $ALIAS routes to:"
az aigateway model-alias show -g "$RG" --gateway-name "$GATEWAY" -n "$ALIAS" | jq -r "$ROUTES"
```

```powershell title="PowerShell"
# Read the alias, and print its backend models, retry limit, and failure rules
Write-Host "🔖 Alias $ALIAS routes to:"
Show-Routes (az aigateway model-alias show -g $RG --gateway-name $GATEWAY -n $ALIAS | ConvertFrom-Json)
```

> **Checkpoint**
> ```text
> gpt-5-mini-tiny  priority 0  weight 1
> gpt-6.1-sol  priority 1  weight 1
> Maximum retries per request: 3
> Rule 1: when @cel(response != null && response.status_code == 429)  retries 0  exclude for PT30S
> ```
> On the portal track, the backup shows as `gpt-6-1-sol`, the name that the import gave it.

### Check that the primary comes back

Wait a minute after the last burst, so that the exclusion has ended and the primary has capacity again, then send
six requests.

```bash title="Bash"
# Send 6 requests to the alias, and count the outcomes
echo "🚦 Sending a short burst to $ALIAS"
./infra/burst.sh "$ALIAS" 6 1
```

```powershell title="PowerShell"
# Send 6 requests to the alias, and count the outcomes
Write-Host "🚦 Sending a short burst to $ALIAS"
./infra/burst.ps1 -Alias $ALIAS -Count 6 -PauseSeconds 1
```

> **Checkpoint**
> All six requests show `200`. The first ones show `gpt-5-mini-2025-08-07`: the primary is back in the alias. The
> rest show `gpt-6.1-sol-2026-09-29`, after the primary runs out of capacity again.

<!-- /steps -->

## Go further

- **Add the recommended rules.** The product docs suggest three rules, in this order: `response == null ||
  response.status_code == 408` with `1` same-backend retry and a 60-second exclusion, for timeouts and lost
  connections; `response != null && response.status_code == 429` with a 30-second exclusion, for throttling; and
  `response != null && response.status_code in [500, 502, 503, 504]` with a 30-second exclusion, for server
  errors. Only the first matching rule applies, so a catch-all rule such as `true` goes last.
- **Compare without the exclusion.** In the portal, edit the rule and clear **Temporarily exclude the backend after
  retries**, or send the rule without `excludeFor` with `az rest`. Clients still get only `200`s, but every request
  now tries the throttled primary first. In our tests, the primary got 17 `429`s during a burst of 20 requests,
  instead of 3.
- **Prefer purchased capacity.** Put a provisioned deployment at priority `0` and a pay-as-you-go deployment of the
  same model at priority `1`, with the `429` rule, so that the provisioned capacity serves first and the overflow
  goes to pay as you go.
- **Back up across regions or providers.** Register the same model from a Foundry account in another region, or
  from another provider, at priority `1`, and add the `5xx` rule, so that an outage in one region doesn't reach your
  users.
- **Trace the attempts.** Send the gateway's telemetry to Application Insights, as in
  [Monitor usage, cost, and traces](../13-monitoring/README.md). The product's
  [telemetry reference](https://ai.gateway.azure.com/docs/observability/telemetry-reference#routing-attributes) lists
  the routing attributes that can describe each backend attempt, such as `azure.ai_gateway.routing.attempt`,
  `azure.ai_gateway.routing.backend`, `azure.ai_gateway.routing.failure.type`, and
  `azure.ai_gateway.routing.exclusion.reason`.

## Clean up

Keep the gateway, the runtime key, and `gpt-5-mini` from lab 02. Later labs use them. Remove what you added in
this lab: the alias first, then the two backend models, then the two Foundry deployments.

<!-- track: portal | Portal -->

### Remove the alias and the two models

Open `chat-failover` in **Models** › **Aliases** and select **Delete**. Requests that use the alias fail
immediately; the backend models stay in the gateway. Then delete `gpt-5-mini-tiny` and `gpt-6.1-sol` from
**Models** › **Backend models**. Finally, delete both deployments from your Foundry account, for example with the
last two commands of the CLI track.

<!-- track: cli | Azure CLI -->

### Remove the alias and the two models

```bash title="Bash"
# Delete the alias first, so that nothing points to the two backend models: requests to the alias now fail
az aigateway model-alias delete -g "$RG" --gateway-name "$GATEWAY" -n "$ALIAS" --yes &&
  echo "🚮 Alias $ALIAS is deleted"

# Delete the two backend models from the gateway's provider
az aigateway model delete -g "$RG" --gateway-name "$GATEWAY" --provider-name "$PROVIDER" -n "$PRIMARY" --yes &&
  echo "🚮 Model $PRIMARY is deleted from $PROVIDER"
az aigateway model delete -g "$RG" --gateway-name "$GATEWAY" --provider-name "$PROVIDER" -n "$BACKUP" --yes &&
  echo "🚮 Model $BACKUP is deleted from $PROVIDER"

# Delete the two deployments from the Foundry account, and keep gpt-5-mini for later labs
az cognitiveservices account deployment delete -g "$FOUNDRY_RG" -n "$FOUNDRY_ACCOUNT" --deployment-name "$PRIMARY" &&
  echo "🚮 Model deployment $PRIMARY is deleted from $FOUNDRY_ACCOUNT"
az cognitiveservices account deployment delete -g "$FOUNDRY_RG" -n "$FOUNDRY_ACCOUNT" --deployment-name "$BACKUP" &&
  echo "🚮 Model deployment $BACKUP is deleted from $FOUNDRY_ACCOUNT"
```

```powershell title="PowerShell"
# Delete the alias first, so that nothing points to the two backend models: requests to the alias now fail
az aigateway model-alias delete -g $RG --gateway-name $GATEWAY -n $ALIAS --yes
if ($?) { Write-Host "🚮 Alias $ALIAS is deleted" }

# Delete the two backend models from the gateway's provider
az aigateway model delete -g $RG --gateway-name $GATEWAY --provider-name $PROVIDER -n $PRIMARY --yes
if ($?) { Write-Host "🚮 Model $PRIMARY is deleted from $PROVIDER" }
az aigateway model delete -g $RG --gateway-name $GATEWAY --provider-name $PROVIDER -n $BACKUP --yes
if ($?) { Write-Host "🚮 Model $BACKUP is deleted from $PROVIDER" }

# Delete the two deployments from the Foundry account, and keep gpt-5-mini for later labs
az cognitiveservices account deployment delete -g $FOUNDRY_RG -n $FOUNDRY_ACCOUNT --deployment-name $PRIMARY
if ($?) { Write-Host "🚮 Model deployment $PRIMARY is deleted from $FOUNDRY_ACCOUNT" }
az cognitiveservices account deployment delete -g $FOUNDRY_RG -n $FOUNDRY_ACCOUNT --deployment-name $BACKUP
if ($?) { Write-Host "🚮 Model deployment $BACKUP is deleted from $FOUNDRY_ACCOUNT" }
```

<!-- track: iac | Bicep + azd -->

### Delete everything azd created

In the `aigateway/labs/29-model-failover` folder, delete the resource group with the gateway, the Foundry account
and its three deployments, and the `chat-failover` alias. [`--purge`](../SETUP.md#delete-what-azd-created) also
purges the soft-deleted Foundry account. It takes about ten minutes.

```bash
# Delete everything that azd up created in this lab, purge the soft-deleted Foundry account, and skip the prompt
azd down --purge --force &&
  echo "🚮 Everything that azd up created is deleted"
```

<!-- track: terraform | Terraform -->

### Delete everything Terraform created

In the lab's Terraform folder, delete the resource group with the gateway, the Foundry account and its three
deployments, and the `chat-failover` alias. The [`azurerm` provider](../SETUP.md#delete-what-terraform-created) also
purges the soft-deleted Foundry account. It takes about two minutes.

```bash
# Move into the lab's Terraform folder
cd ~/aigateway/labs/29-model-failover/terraform &&
  echo "📂 Terraform folder: $(pwd)"

# Delete everything that terraform apply created, and purge the soft-deleted Foundry account
terraform destroy -auto-approve &&
  echo "🚮 Everything that terraform apply created is deleted"
```

<!-- /tracks -->

`azd down` and `terraform destroy` don't touch the gateway, key, and `gpt-5-mini` from lab 02, because the
Bicep + azd and Terraform tracks created their own gateways.

## Next steps

- [Route an alias across models by priority and weight](../22-model-routing/README.md)
- [Route alias requests with conditions and session affinity](../27-conditional-routing/README.md)
- [Let the gateway choose the model for each request](../28-auto-model-selection/README.md)
- [Throttle tokens per caller with token limits](../06-token-limits/README.md)
- [Monitor usage, cost, and traces](../13-monitoring/README.md)
- [Model failover](https://ai.gateway.azure.com/docs/models/failover) and
  [Configure model failover](https://ai.gateway.azure.com/docs/models/configure-failover) in the product docs
- [November 12 release: model failover and retry rules](https://ai.gateway.azure.com/docs/releases#release-2026-11-12)
