# APIM with Azure Front Door for Global AI Distribution

**Last updated:** 2026-02
**Status:** GA
**Category:** API Management & AI Gateway

---

## Introduksjon

Nar organisasjoner ruller ut AI-tjenester globalt eller trenger ekstra beskyttelse og ytelsesoptimalisering, er kombinasjonen av Azure Front Door og Azure API Management en kraftig arkitektur. Azure Front Door gir global HTTP(S)-lastbalansering, DDoS-beskyttelse, Web Application Firewall (WAF), edge caching og TLS-offloading -- alt foran APIM som haandterer AI-spesifikk policy-haaandheving, token-ratebegrensning og backend-lastbalansering.

For norsk offentlig sektor er denne kombinasjonen relevant i flere scenarier: organisasjoner med innbyggertjenester som ma handtere trafikktopper (f.eks. skattemelding-perioden, eksamenssvar), tjenester som eksponeres mot internasjonale brukere, eller organisasjoner som krever ekstra lag med DDoS-beskyttelse. Azure Front Door sine globale PoP-er (Points of Presence) gir lavere latency for brukere narmere edge-lokasjoner.

Arkitekturen Front Door + APIM + AI Backend gir et tre-lags forsvar: Front Door handterer DDoS og WAF pa nettverksniva, APIM haandterer API-spesifikk sikkerhet og trafikkstyring, og Azure AI-tjenestene handterer modellspesifikk tilgangskontroll. Denne referansen dekker konfigurasjon, sikring og optimalisering av denne arkitekturen.

---

## Global lastdistribusjon

### Arkitekturoversikt

```
Brukere (globalt)
    |
    v
Azure Front Door (Global L7 Load Balancer)
    |-- PoP Oslo (naermest norske brukere)
    |-- PoP London
    |-- PoP New York
    |
    v
APIM Instance(r)
    |-- West Europe (primaer)
    |-- North Europe (sekundaer)
    |
    v
AI Backends
    |-- Azure OpenAI (West Europe)
    |-- Azure OpenAI (Sweden Central)
    |-- Microsoft Foundry (North Europe)
```

### Oppsett av Front Door-profil

Konfigurer Front Door med APIM som origin:

| Innstilling | Verdi |
|------------|-------|
| **Origin type** | API Management |
| **Origin hostname** | `{apim-name}.azure-api.net` |
| **Caching** | Enable caching (for GET-requests) |
| **Query string behavior** | Use Query String |
| **Health probe path** | `/status-0123456789abcdef` |
| **Health probe protocol** | HTTPS |
| **Health probe method** | GET |
| **Probe interval** | 30 sekunder |

### Bicep: Front Door med APIM Origin

```bicep
resource frontDoorProfile 'Microsoft.Cdn/profiles@2024-02-01' = {
  name: frontDoorName
  location: 'global'
  sku: {
    name: 'Premium_AzureFrontDoor'  // Premium for Private Link + WAF
  }
}

resource frontDoorEndpoint 'Microsoft.Cdn/profiles/afdEndpoints@2024-02-01' = {
  parent: frontDoorProfile
  name: 'ai-gateway-endpoint'
  location: 'global'
  properties: {
    enabledState: 'Enabled'
  }
}

resource originGroup 'Microsoft.Cdn/profiles/originGroups@2024-02-01' = {
  parent: frontDoorProfile
  name: 'apim-origin-group'
  properties: {
    loadBalancingSettings: {
      sampleSize: 4
      successfulSamplesRequired: 3
      additionalLatencyInMilliseconds: 50
    }
    healthProbeSettings: {
      probePath: '/status-0123456789abcdef'
      probeRequestType: 'GET'
      probeProtocol: 'Https'
      probeIntervalInSeconds: 30
    }
    sessionAffinityState: 'Disabled'
  }
}

resource originWestEurope 'Microsoft.Cdn/profiles/originGroups/origins@2024-02-01' = {
  parent: originGroup
  name: 'apim-west-europe'
  properties: {
    hostName: '${apimNameWestEurope}.azure-api.net'
    httpPort: 80
    httpsPort: 443
    originHostHeader: '${apimNameWestEurope}.azure-api.net'
    priority: 1
    weight: 1000
    enabledState: 'Enabled'
    enforceCertificateNameCheck: true
  }
}

resource originNorthEurope 'Microsoft.Cdn/profiles/originGroups/origins@2024-02-01' = {
  parent: originGroup
  name: 'apim-north-europe'
  properties: {
    hostName: '${apimNameNorthEurope}.azure-api.net'
    httpPort: 80
    httpsPort: 443
    originHostHeader: '${apimNameNorthEurope}.azure-api.net'
    priority: 2  // Failover
    weight: 1000
    enabledState: 'Enabled'
    enforceCertificateNameCheck: true
  }
}

resource route 'Microsoft.Cdn/profiles/afdEndpoints/routes@2024-02-01' = {
  parent: frontDoorEndpoint
  name: 'ai-gateway-route'
  properties: {
    originGroup: {
      id: originGroup.id
    }
    supportedProtocols: [ 'Https' ]
    patternsToMatch: [ '/ai/*' ]
    forwardingProtocol: 'HttpsOnly'
    httpsRedirect: 'Enabled'
    linkToDefaultDomain: 'Enabled'
  }
}
```

---

## DDoS-beskyttelse

### Front Door innebygd DDoS-beskyttelse

Azure Front Door gir plattform-niva DDoS-beskyttelse automatisk:

| Beskyttelsestype | Dekning |
|-----------------|---------|
| L3/L4 DDoS | Automatisk for alle Front Door-profiler |
| L7 DDoS | Via WAF-policyer |
| Volumetriske angrep | Absorberes av Front Doors globale nettverk |
| Protocol-angrep | Filtreres pa edge |
| Application-layer | WAF rate limiting + bot protection |

### Kombinert beskyttelse

For kritiske AI-tjenester, kombiner Front Door med Azure DDoS Protection:

```bicep
resource ddosProtectionPlan 'Microsoft.Network/ddosProtectionPlans@2023-11-01' = {
  name: 'ai-gateway-ddos-plan'
  location: location
  properties: {}
}
```

---

## Web Application Firewall

### WAF-policy for AI Gateway

```bicep
resource wafPolicy 'Microsoft.Network/FrontDoorWebApplicationFirewallPolicies@2024-02-01' = {
  name: 'aiGatewayWafPolicy'
  location: 'global'
  sku: {
    name: 'Premium_AzureFrontDoor'
  }
  properties: {
    policySettings: {
      enabledState: 'Enabled'
      mode: 'Prevention'
      requestBodyCheck: 'Enabled'
      requestBodyInspectLimitInKB: 128
    }
    managedRules: {
      managedRuleSets: [
        {
          ruleSetType: 'Microsoft_DefaultRuleSet'
          ruleSetVersion: '2.1'
          ruleGroupOverrides: []
        }
        {
          ruleSetType: 'Microsoft_BotManagerRuleSet'
          ruleSetVersion: '1.1'
        }
      ]
    }
    customRules: {
      rules: [
        {
          name: 'RateLimitAiRequests'
          priority: 100
          enabledState: 'Enabled'
          ruleType: 'RateLimitRule'
          rateLimitDurationInMinutes: 1
          rateLimitThreshold: 100
          matchConditions: [
            {
              matchVariable: 'RequestUri'
              operator: 'Contains'
              matchValue: [ '/ai/' ]
            }
          ]
          action: 'Block'
        }
        {
          name: 'BlockSuspiciousPayloads'
          priority: 200
          enabledState: 'Enabled'
          ruleType: 'MatchRule'
          matchConditions: [
            {
              matchVariable: 'RequestBody'
              operator: 'Contains'
              matchValue: [
                'ignore previous instructions'
                'ignore all instructions'
                'disregard your system prompt'
              ]
              transforms: [ 'Lowercase' ]
            }
          ]
          action: 'Block'
        }
        {
          name: 'GeoBlockNonAllowed'
          priority: 300
          enabledState: 'Enabled'
          ruleType: 'MatchRule'
          matchConditions: [
            {
              matchVariable: 'RemoteAddr'
              operator: 'GeoMatch'
              negateCondition: true
              matchValue: [ 'NO', 'SE', 'DK', 'FI' ]  // Nordiske land
            }
          ]
          action: 'Log'  // Start med Log, bytt til Block etter validering
        }
      ]
    }
  }
}
```

### WAF-regler tilpasset AI-trafikk

| Regel | Type | Handling | Formal |
|-------|------|---------|--------|
| Rate limit per IP | RateLimit | Block | Maks 100 req/min per IP |
| Prompt injection patterns | Match | Block | Blokkerer kjente injeksjonsmonstre |
| Geo-filtering | Match | Log/Block | Begrens til tillatte land |
| Bot protection | Managed | Block | Identifiserer og blokkerer botter |
| OWASP Core Rules | Managed | Block | Standard webapplikasjonsbeskyttelse |
| Payload size limit | Match | Block | Maks request body-storrelse |

---

## Edge Caching

### Caching-strategi for AI med Front Door

For AI-API-er er caching begrenset til GET-requests og statisk innhold. POST-baserte chat completion-kall caches ikke av Front Door, men det finnes bruksomrader:

| Innholdstype | Cachebar? | Strategi |
|-------------|-----------|----------|
| Chat completions (POST) | Nei | Bruk APIM semantisk caching |
| Model listing (GET) | Ja | Front Door edge cache |
| API documentation | Ja | Front Door edge cache |
| Health endpoints | Nei | Bypass cache |
| Static assets (dev portal) | Ja | Front Door edge cache |

### Caching for Developer Portal

```bicep
resource devPortalRoute 'Microsoft.Cdn/profiles/afdEndpoints/routes@2024-02-01' = {
  parent: frontDoorEndpoint
  name: 'dev-portal-route'
  properties: {
    originGroup: {
      id: devPortalOriginGroup.id
    }
    supportedProtocols: [ 'Https' ]
    patternsToMatch: [ '/developer/*' ]
    forwardingProtocol: 'HttpsOnly'
    cacheConfiguration: {
      queryStringCachingBehavior: 'IgnoreQueryString'
      compressionSettings: {
        isCompressionEnabled: true
        contentTypesToCompress: [
          'text/html'
          'text/css'
          'application/javascript'
          'application/json'
        ]
      }
    }
  }
}
```

---

## Geografisk ruting

### Priority-basert ruting med failover

```
Bruker i Norge
    |
    v
Front Door PoP Oslo
    |
    |-- Priority 1: APIM West Europe (Nederland)
    |-- Priority 2: APIM North Europe (Irland)
    |
    v
APIM West Europe
    |
    |-- Priority 1: Azure OpenAI Sweden Central
    |-- Priority 2: Azure OpenAI West Europe
```

### Restriksjon: Kun Front Door-trafikk til APIM

Sikre at APIM kun aksepterer trafikk fra Front Door:

```xml
<policies>
    <inbound>
        <base />
        <!-- Verify Front Door ID header -->
        <check-header name="X-Azure-FDID"
            failed-check-httpcode="403"
            failed-check-error-message="Access denied. Traffic must route through Azure Front Door."
            ignore-case="false">
            <value>{{FrontDoorId}}</value>
        </check-header>

        <!-- Additionally restrict to Front Door IP ranges -->
        <ip-filter action="allow">
            <address-range from="147.243.0.0" to="147.243.255.255" />
            <!-- AzureFrontDoor.Backend service tag ranges -->
        </ip-filter>
    </inbound>
</policies>
```

### Private Link mellom Front Door og APIM

For maksimal sikkerhet, bruk Front Door Premium med Private Link:

```bicep
resource privateEndpoint 'Microsoft.Cdn/profiles/originGroups/origins@2024-02-01' = {
  parent: originGroup
  name: 'apim-private'
  properties: {
    hostName: '${apimName}.azure-api.net'
    originHostHeader: '${apimName}.azure-api.net'
    priority: 1
    weight: 1000
    enabledState: 'Enabled'
    sharedPrivateLinkResource: {
      privateLink: {
        id: apiManagement.id
      }
      privateLinkLocation: location
      groupId: 'gateway'
      requestMessage: 'Front Door Private Link to APIM'
    }
  }
}
```

---

## Kostnadsestimat for Front Door + APIM

| Komponent | Manedlig kostnad (NOK) |
|-----------|----------------------|
| Front Door Premium (base) | ~4 000 |
| Front Door: 10M requests | ~1 500 |
| Front Door: Data transfer (100 GB) | ~1 000 |
| WAF Policy (Premium) | ~4 500 |
| APIM Standard v2 | ~20 000 |
| **Total** | **~31 000** |

Merk: Front Door Standard er rimeligere (~60% av Premium-pris) men mangler Private Link og WAF Managed Rules.

---

## Referanser

- [Configure Front Door Standard/Premium in front of Azure API Management](https://learn.microsoft.com/en-us/azure/api-management/front-door-api-management) -- trinnvis veiledning
- [What is Azure Front Door?](https://learn.microsoft.com/en-us/azure/frontdoor/front-door-overview) -- oversikt
- [Azure Front Door DDoS protection](https://learn.microsoft.com/en-us/azure/frontdoor/front-door-ddos) -- DDoS-beskyttelse
- [Web Application Firewall on Azure Front Door](https://learn.microsoft.com/en-us/azure/web-application-firewall/afds/afds-overview) -- WAF-oversikt
- [AI gateway in Azure API Management](https://learn.microsoft.com/en-us/azure/api-management/genai-gateway-capabilities) -- AI gateway
- [Restrict caller IPs policy](https://learn.microsoft.com/en-us/azure/api-management/ip-filter-policy) -- IP-filtrering
- [Check header policy](https://learn.microsoft.com/en-us/azure/api-management/check-header-policy) -- header-validering
- [Architecture best practices for Azure Front Door](https://learn.microsoft.com/en-us/azure/well-architected/service-guides/azure-front-door) -- Well-Architected-anbefalinger

## For Cosmo

- **Bruk denne referansen** nar kunden trenger global distribusjon av AI-tjenester, ekstra DDoS-beskyttelse, eller WAF foran AI-gateway-en sin.
- For de fleste norske offentlige virksomheter er Front Door overkill for rene interne AI-tjenester. Anbefal det primaert for innbyggerrettede tjenester med hoy trafikk eller behov for geographic redundancy.
- Front Door Premium er nodvendig for Private Link til APIM og WAF Managed Rules. Standard-tier mangler disse, men er tilstrekkelig for basic lastbalansering og DDoS.
- Husk alltid a konfigurere `X-Azure-FDID`-header-sjekk i APIM for a forhindre at noen omgar Front Door og kaller APIM direkte.
- Kombiner Front Door WAF-regler for prompt injection-monstre pa nettverksniva med APIM Content Safety policy for AI-spesifikk innholdsmoderasjon -- dette gir forsvar i dybden.
