{
  "nbformat": 4,
  "nbformat_minor": 5,
  "metadata": {
    "kernelspec": {
      "display_name": "bicep",
      "language": "bicep",
      "name": "bicep"
    },
    "language_info": {
      "name": "bicep",
      "version": "1.0.0"
    },
    "blog_metadata": {
      "topic": "Azure Front Door just got more interesting for AI platforms — here’s the edge pattern I’d standardize on",
      "slug": "azure-front-door-just-got-more-interesting-for-ai-platforms-",
      "generated_by": "LinkedIn Post Generator + Azure OpenAI",
      "generated_at": "2026-11-11T21:13:08.792Z"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Azure Front Door just got more interesting for AI platforms — here’s the edge pattern I’d standardize on\n",
        "\n",
        "This notebook turns the blog post into a hands-on validation workflow for an Azure AI edge pattern centered on Azure Front Door. The focus is to classify route types, keep the AI control plane regional, validate a minimal Front Door footprint in Bicep, and test whether edge capabilities actually improve latency, resilience, and abuse protection."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "%pip install requests pandas"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "import os\n",
        "import json\n",
        "import time\n",
        "import textwrap\n",
        "import urllib.request\n",
        "import urllib.error\n",
        "from pathlib import Path\n",
        "\n",
        "import pandas as pd\n",
        "import requests"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Validation goals\n",
        "\n",
        "The architecture decision starts with the request path, not the product menu. For AI platforms, the key route classes to validate are:\n",
        "\n",
        "- `/inference/*` for synchronous model calls\n",
        "- `/stream/*` for streaming or protocol-sensitive paths\n",
        "- `/agents/*` for agent-facing APIs with downstream fan-out\n",
        "\n",
        "The standard proposed here is narrow on purpose:\n",
        "\n",
        "- use Azure Front Door only for public or distributed routes that earn it\n",
        "- separate route classes early at the edge\n",
        "- keep AI control-plane concerns regional\n",
        "- test resilience, protocol behavior, and abuse controls before standardizing"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Architecture sketch\n",
        "\n",
        "This is the reference path described in the tutorial.\n",
        "\n",
        "```mermaid\n",
        "flowchart TD\n",
        "    U[Client / SDK / Browser] --> AFD[Azure Front Door Premium]\n",
        "    AFD --> WAF[WAF Policy]\n",
        "    WAF --> R1[/inference/*]\n",
        "    WAF --> R2[/stream/*]\n",
        "    WAF --> R3[/agents/*]\n",
        "\n",
        "    R1 --> AOAI[Azure OpenAI / Model Gateway]\n",
        "    R2 --> APIM[API Management]\n",
        "    R3 --> ACA[Agent API on Container Apps]\n",
        "\n",
        "    APIM --> AOAI\n",
        "    ACA --> KV[Key Vault]\n",
        "    ACA --> SB[Service Bus]\n",
        "    ACA --> AOAI\n",
        "\n",
        "    AOAI --> MON[Azure Monitor / App Insights]\n",
        "    ACA --> MON\n",
        "    APIM --> MON\n",
        "    AFD --> MON\n",
        "```\n",
        "\n",
        "The important design choice is that route separation happens at the edge, but policy ownership and service behavior remain with the appropriate regional backend."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Required variables and assumptions\n",
        "\n",
        "If you want to run the live validation cells, set these values first:\n",
        "\n",
        "- `SUBSCRIPTION_ID`: Azure subscription ID\n",
        "- `RESOURCE_GROUP_NAME`: Resource group containing edge and AI resources\n",
        "- `API_BASE_URL`: Public API base URL, for example `https://api.contoso.com`\n",
        "\n",
        "Optional values:\n",
        "\n",
        "- `INFERENCE_PATH`: defaults to `/inference/ping`\n",
        "- `STREAM_PATH`: defaults to `/stream/ping`\n",
        "- `AGENTS_PATH`: defaults to `/agents/ping`\n",
        "- `STREAM_EVENTS_PATH`: defaults to `/stream/events`\n",
        "\n",
        "This notebook keeps deployment artifacts local under `./infra`."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "SUBSCRIPTION_ID = os.getenv('SUBSCRIPTION_ID', '<subscription-id>')\n",
        "RESOURCE_GROUP_NAME = os.getenv('RESOURCE_GROUP_NAME', 'rg-ai-edge')\n",
        "API_BASE_URL = os.getenv('API_BASE_URL', 'https://api.contoso.com')\n",
        "INFERENCE_PATH = os.getenv('INFERENCE_PATH', '/inference/ping')\n",
        "STREAM_PATH = os.getenv('STREAM_PATH', '/stream/ping')\n",
        "AGENTS_PATH = os.getenv('AGENTS_PATH', '/agents/ping')\n",
        "STREAM_EVENTS_PATH = os.getenv('STREAM_EVENTS_PATH', '/stream/events')\n",
        "\n",
        "config = {\n",
        "    'SUBSCRIPTION_ID': SUBSCRIPTION_ID,\n",
        "    'RESOURCE_GROUP_NAME': RESOURCE_GROUP_NAME,\n",
        "    'API_BASE_URL': API_BASE_URL,\n",
        "    'INFERENCE_PATH': INFERENCE_PATH,\n",
        "    'STREAM_PATH': STREAM_PATH,\n",
        "    'AGENTS_PATH': AGENTS_PATH,\n",
        "    'STREAM_EVENTS_PATH': STREAM_EVENTS_PATH,\n",
        "}\n",
        "print(json.dumps(config, indent=2))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Route classification worksheet\n",
        "\n",
        "Before deploying anything, classify the routes you actually own. This avoids forcing a global edge onto internal-only or single-region traffic that gains nothing from it."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "route_inventory = pd.DataFrame([\n",
        "    {'route_class': 'inference', 'pattern': '/inference/*', 'public': True, 'distributed_clients': True, 'protocol_sensitive': False, 'recommended_entry': 'Front Door'},\n",
        "    {'route_class': 'stream', 'pattern': '/stream/*', 'public': True, 'distributed_clients': True, 'protocol_sensitive': True, 'recommended_entry': 'Front Door only after validation'},\n",
        "    {'route_class': 'agents', 'pattern': '/agents/*', 'public': True, 'distributed_clients': True, 'protocol_sensitive': False, 'recommended_entry': 'Front Door with governance review'},\n",
        "    {'route_class': 'internal-tools', 'pattern': '/tools/*', 'public': False, 'distributed_clients': False, 'protocol_sensitive': False, 'recommended_entry': 'Regional or private only'},\n",
        "])\n",
        "route_inventory"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Decision table\n",
        "\n",
        "Use this quick table to reason about placement. Front Door is strongest for global public entry, API Management is strongest for API mediation and governance, and regional ingress is strongest when local control matters more than global distribution."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "decision_table = pd.DataFrame([\n",
        "    {'Decision factor': 'Public internet entry', 'Front Door': 'Strong fit', 'API Management': 'Sometimes behind/alongside', 'Regional ingress': 'Usually no', 'Direct regional': 'Limited'},\n",
        "    {'Decision factor': 'Global distribution', 'Front Door': 'Strong fit', 'API Management': 'Not primary', 'Regional ingress': 'No', 'Direct regional': 'No'},\n",
        "    {'Decision factor': 'API policy mediation', 'Front Door': 'Basic at edge', 'API Management': 'Strong fit', 'Regional ingress': 'Limited', 'Direct regional': 'None'},\n",
        "    {'Decision factor': 'Protocol sensitivity', 'Front Door': 'Validate carefully', 'API Management': 'Validate carefully', 'Regional ingress': 'Often better for local control', 'Direct regional': 'Depends'},\n",
        "    {'Decision factor': 'Regional affinity', 'Front Door': 'Indirect', 'API Management': 'Indirect', 'Regional ingress': 'Strong fit', 'Direct regional': 'Strong fit'},\n",
        "    {'Decision factor': 'Operational burden', 'Front Door': 'Moderate', 'API Management': 'Moderate to high', 'Regional ingress': 'Moderate', 'Direct regional': 'Lowest'},\n",
        "])\n",
        "decision_table"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Code example: Front Door profile and endpoint\n",
        "\n",
        "This is the minimum viable Azure Front Door footprint for a standardized AI edge entry point. It creates a Premium profile and a single endpoint, keeping the initial deployment intentionally small."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "from pathlib import Path\n",
        "\n",
        "infra_dir = Path('infra')\n",
        "infra_dir.mkdir(exist_ok=True)\n",
        "\n",
        "bicep_profile_endpoint = \"\"\"param profileName string = 'afd-ai-edge'\n",
        "param endpointName string = 'ai-global'\n",
        "param location string = 'global'\n",
        "param skuName string = 'Premium_AzureFrontDoor'\n",
        "\n",
        "resource profile 'Microsoft.Cdn/profiles@2024-02-01' = {\n",
        "  name: profileName\n",
        "  location: location\n",
        "  sku: {\n",
        "    name: skuName\n",
        "  }\n",
        "}\n",
        "\n",
        "resource endpoint 'Microsoft.Cdn/profiles/afdEndpoints@2024-02-01' = {\n",
        "  name: '${profile.name}/${endpointName}'\n",
        "  location: location\n",
        "  properties: {\n",
        "    enabledState: 'Enabled'\n",
        "  }\n",
        "}\n",
        "\"\"\"\n",
        "\n",
        "profile_file = infra_dir / '01-profile-endpoint.bicep'\n",
        "profile_file.write_text(bicep_profile_endpoint, encoding='utf-8')\n",
        "print(profile_file.read_text(encoding='utf-8'))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Code example: Origin group with health probes\n",
        "\n",
        "Origin groups are where health probing and load balancing become operational decisions instead of defaults. The values below force a conversation about what healthy means for your AI-serving path."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "bicep_origin_group = \"\"\"param profileName string = 'afd-ai-edge'\n",
        "param originGroupName string = 'og-ai-platform'\n",
        "\n",
        "resource originGroup 'Microsoft.Cdn/profiles/originGroups@2024-02-01' = {\n",
        "  name: '${profileName}/${originGroupName}'\n",
        "  properties: {\n",
        "    sessionAffinityState: 'Disabled'\n",
        "    healthProbeSettings: {\n",
        "      probePath: '/health'\n",
        "      probeProtocol: 'Https'\n",
        "      probeRequestType: 'GET'\n",
        "      probeIntervalInSeconds: 30\n",
        "    }\n",
        "    loadBalancingSettings: {\n",
        "      sampleSize: 4\n",
        "      successfulSamplesRequired: 3\n",
        "      additionalLatencyInMilliseconds: 0\n",
        "    }\n",
        "  }\n",
        "}\n",
        "\"\"\"\n",
        "\n",
        "origin_group_file = infra_dir / '02-origin-group.bicep'\n",
        "origin_group_file.write_text(bicep_origin_group, encoding='utf-8')\n",
        "print(origin_group_file.read_text(encoding='utf-8'))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Required variables for deployment-oriented Bicep\n",
        "\n",
        "The next Bicep example references a custom domain resource ID and assumes a subscription and resource group context. Provide these values before using the route definition in a real deployment:\n",
        "\n",
        "- `profileName`\n",
        "- `endpointName`\n",
        "- `originGroupName`\n",
        "- `customDomainId`\n",
        "- subscription and resource group matching the resource IDs used in the template"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Code example: Route separation at the edge\n",
        "\n",
        "This route definition shows the core pattern from the tutorial: separate route classes at the edge instead of sending all AI traffic through one catch-all path. That separation is what lets you validate inference, streaming, and agent APIs independently."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "bicep_route = \"\"\"param profileName string = 'afd-ai-edge'\n",
        "param endpointName string = 'ai-global'\n",
        "param originGroupName string = 'og-ai-platform'\n",
        "param customDomainId string = '/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg/providers/Microsoft.Cdn/profiles/afd-ai-edge/customDomains/api-contoso-com'\n",
        "\n",
        "resource inferenceRoute 'Microsoft.Cdn/profiles/afdEndpoints/routes@2024-02-01' = {\n",
        "  name: '${profileName}/${endpointName}/rt-inference'\n",
        "  properties: {\n",
        "    originGroup: {\n",
        "      id: '/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg/providers/Microsoft.Cdn/profiles/${profileName}/originGroups/${originGroupName}'\n",
        "    }\n",
        "    customDomains: [\n",
        "      {\n",
        "        id: customDomainId\n",
        "      }\n",
        "    ]\n",
        "    supportedProtocols: [\n",
        "      'Https'\n",
        "    ]\n",
        "    patternsToMatch: [\n",
        "      '/inference/*'\n",
        "    ]\n",
        "    forwardingProtocol: 'HttpsOnly'\n",
        "    httpsRedirect: 'Enabled'\n",
        "    linkToDefaultDomain: 'Disabled'\n",
        "  }\n",
        "}\n",
        "\"\"\"\n",
        "\n",
        "route_file = infra_dir / '03-route-inference.bicep'\n",
        "route_file.write_text(bicep_route, encoding='utf-8')\n",
        "print(route_file.read_text(encoding='utf-8'))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Compose a minimal main.bicep\n",
        "\n",
        "To make the Bicep examples easier to validate, this cell writes a single `main.bicep` that combines the profile, endpoint, origin group, and three route classes. This extends the blog's single route example into a practical validation artifact."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "main_bicep = \"\"\"param profileName string = 'afd-ai-edge'\n",
        "param endpointName string = 'ai-global'\n",
        "param location string = 'global'\n",
        "param skuName string = 'Premium_AzureFrontDoor'\n",
        "param originGroupName string = 'og-ai-platform'\n",
        "param customDomainId string = '/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg/providers/Microsoft.Cdn/profiles/afd-ai-edge/customDomains/api-contoso-com'\n",
        "\n",
        "resource profile 'Microsoft.Cdn/profiles@2024-02-01' = {\n",
        "  name: profileName\n",
        "  location: location\n",
        "  sku: {\n",
        "    name: skuName\n",
        "  }\n",
        "}\n",
        "\n",
        "resource endpoint 'Microsoft.Cdn/profiles/afdEndpoints@2024-02-01' = {\n",
        "  name: '${profile.name}/${endpointName}'\n",
        "  location: location\n",
        "  properties: {\n",
        "    enabledState: 'Enabled'\n",
        "  }\n",
        "}\n",
        "\n",
        "resource originGroup 'Microsoft.Cdn/profiles/originGroups@2024-02-01' = {\n",
        "  name: '${profile.name}/${originGroupName}'\n",
        "  properties: {\n",
        "    sessionAffinityState: 'Disabled'\n",
        "    healthProbeSettings: {\n",
        "      probePath: '/health'\n",
        "      probeProtocol: 'Https'\n",
        "      probeRequestType: 'GET'\n",
        "      probeIntervalInSeconds: 30\n",
        "    }\n",
        "    loadBalancingSettings: {\n",
        "      sampleSize: 4\n",
        "      successfulSamplesRequired: 3\n",
        "      additionalLatencyInMilliseconds: 0\n",
        "    }\n",
        "  }\n",
        "}\n",
        "\n",
        "resource inferenceRoute 'Microsoft.Cdn/profiles/afdEndpoints/routes@2024-02-01' = {\n",
        "  name: '${profile.name}/${endpoint.name}/rt-inference'\n",
        "  properties: {\n",
        "    originGroup: {\n",
        "      id: originGroup.id\n",
        "    }\n",
        "    customDomains: [\n",
        "      {\n",
        "        id: customDomainId\n",
        "      }\n",
        "    ]\n",
        "    supportedProtocols: [\n",
        "      'Https'\n",
        "    ]\n",
        "    patternsToMatch: [\n",
        "      '/inference/*'\n",
        "    ]\n",
        "    forwardingProtocol: 'HttpsOnly'\n",
        "    httpsRedirect: 'Enabled'\n",
        "    linkToDefaultDomain: 'Disabled'\n",
        "  }\n",
        "}\n",
        "\n",
        "resource streamRoute 'Microsoft.Cdn/profiles/afdEndpoints/routes@2024-02-01' = {\n",
        "  name: '${profile.name}/${endpoint.name}/rt-stream'\n",
        "  properties: {\n",
        "    originGroup: {\n",
        "      id: originGroup.id\n",
        "    }\n",
        "    customDomains: [\n",
        "      {\n",
        "        id: customDomainId\n",
        "      }\n",
        "    ]\n",
        "    supportedProtocols: [\n",
        "      'Https'\n",
        "    ]\n",
        "    patternsToMatch: [\n",
        "      '/stream/*'\n",
        "    ]\n",
        "    forwardingProtocol: 'HttpsOnly'\n",
        "    httpsRedirect: 'Enabled'\n",
        "    linkToDefaultDomain: 'Disabled'\n",
        "  }\n",
        "}\n",
        "\n",
        "resource agentsRoute 'Microsoft.Cdn/profiles/afdEndpoints/routes@2024-02-01' = {\n",
        "  name: '${profile.name}/${endpoint.name}/rt-agents'\n",
        "  properties: {\n",
        "    originGroup: {\n",
        "      id: originGroup.id\n",
        "    }\n",
        "    customDomains: [\n",
        "      {\n",
        "        id: customDomainId\n",
        "      }\n",
        "    ]\n",
        "    supportedProtocols: [\n",
        "      'Https'\n",
        "    ]\n",
        "    patternsToMatch: [\n",
        "      '/agents/*'\n",
        "    ]\n",
        "    forwardingProtocol: 'HttpsOnly'\n",
        "    httpsRedirect: 'Enabled'\n",
        "    linkToDefaultDomain: 'Disabled'\n",
        "  }\n",
        "}\n",
        "\"\"\"\n",
        "\n",
        "main_file = infra_dir / 'main.bicep'\n",
        "main_file.write_text(main_bicep, encoding='utf-8')\n",
        "print(main_file.read_text(encoding='utf-8'))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Optional local validation of Bicep files\n",
        "\n",
        "If Azure CLI and Bicep are available in your environment, you can validate the generated files. This cell only prints the commands so the notebook remains portable."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "commands = [\n",
        "    'az bicep build --file infra/01-profile-endpoint.bicep',\n",
        "    'az bicep build --file infra/02-origin-group.bicep',\n",
        "    'az bicep build --file infra/03-route-inference.bicep',\n",
        "    'az bicep build --file infra/main.bicep',\n",
        "]\n",
        "print('\\n'.join(commands))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Inventory the request path\n",
        "\n",
        "The blog recommends a fast inventory pass before standardizing the edge. The original sample was PowerShell; this notebook uses Python to produce a similar inventory worksheet you can validate without requiring PowerShell in the kernel."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "inventory_targets = pd.DataFrame([\n",
        "    {'resource_type': 'Microsoft.Cdn/profiles/afdEndpoints', 'purpose': 'Global edge endpoint', 'public_entry': True},\n",
        "    {'resource_type': 'Microsoft.ApiManagement/service', 'purpose': 'API mediation and governance', 'public_entry': 'Depends'},\n",
        "    {'resource_type': 'Microsoft.App/containerApps', 'purpose': 'Regional app runtime for agent APIs', 'public_entry': 'Depends'},\n",
        "    {'resource_type': 'Microsoft.CognitiveServices/accounts', 'purpose': 'AI service endpoint', 'public_entry': 'Usually regional/private'},\n",
        "])\n",
        "inventory_targets"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Reachability worksheet\n",
        "\n",
        "Use this simple worksheet to flag which components are externally reachable versus regional or private. If much of the path is not public, that is a strong signal not to force a global edge onto everything."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "reachability_report = pd.DataFrame([\n",
        "    {'Name': 'ai-global', 'Type': 'Microsoft.Cdn/profiles/afdEndpoints', 'Location': 'global', 'Reachability': 'External'},\n",
        "    {'Name': 'apim-ai', 'Type': 'Microsoft.ApiManagement/service', 'Location': 'eastus', 'Reachability': 'External'},\n",
        "    {'Name': 'aca-agent-api', 'Type': 'Microsoft.App/containerApps', 'Location': 'eastus', 'Reachability': 'RegionalOrPrivate'},\n",
        "    {'Name': 'aoai-eastus', 'Type': 'Microsoft.CognitiveServices/accounts', 'Location': 'eastus', 'Reachability': 'RegionalOrPrivate'},\n",
        "])\n",
        "reachability_report.sort_values(['Reachability', 'Type', 'Name'])"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Route probe matrix\n",
        "\n",
        "This is the repeatable route test matrix from the tutorial, adapted to use the configured base URL. It compares status and latency across inference, streaming, and agent-facing routes."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "tests = [\n",
        "    {'name': 'inference', 'url': f'{API_BASE_URL}{INFERENCE_PATH}'},\n",
        "    {'name': 'stream', 'url': f'{API_BASE_URL}{STREAM_PATH}'},\n",
        "    {'name': 'agents', 'url': f'{API_BASE_URL}{AGENTS_PATH}'},\n",
        "]\n",
        "\n",
        "results = []\n",
        "for test in tests:\n",
        "    started = time.perf_counter()\n",
        "    try:\n",
        "        with urllib.request.urlopen(test['url'], timeout=15) as resp:\n",
        "            body = resp.read(256).decode('utf-8', errors='ignore')\n",
        "            status = resp.status\n",
        "    except urllib.error.HTTPError as e:\n",
        "        status, body = e.code, str(e)\n",
        "    except Exception as e:\n",
        "        status, body = 0, str(e)\n",
        "    latency_ms = round((time.perf_counter() - started) * 1000, 1)\n",
        "    results.append({\n",
        "        'route': test['name'],\n",
        "        'status': status,\n",
        "        'latency_ms': latency_ms,\n",
        "        'sample': body[:80]\n",
        "    })\n",
        "\n",
        "print(json.dumps(results, indent=2))\n",
        "pd.DataFrame(results)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Streaming probe\n",
        "\n",
        "Streaming paths deserve their own test because first-byte latency and total completion time matter. This cell performs a minimal SSE-style probe and captures both measurements."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "url = f'{API_BASE_URL}{STREAM_EVENTS_PATH}'\n",
        "req = urllib.request.Request(url, headers={'Accept': 'text/event-stream'})\n",
        "\n",
        "stream_result = {}\n",
        "start = time.perf_counter()\n",
        "try:\n",
        "    with urllib.request.urlopen(req, timeout=30) as resp:\n",
        "        first_line = resp.readline().decode('utf-8', errors='ignore').strip()\n",
        "        first_byte_ms = round((time.perf_counter() - start) * 1000, 1)\n",
        "        lines = [first_line]\n",
        "        for _ in range(2):\n",
        "            lines.append(resp.readline().decode('utf-8', errors='ignore').strip())\n",
        "        total_ms = round((time.perf_counter() - start) * 1000, 1)\n",
        "        stream_result = {\n",
        "            'status': resp.status,\n",
        "            'first_byte_ms': first_byte_ms,\n",
        "            'total_ms': total_ms,\n",
        "            'preview': lines,\n",
        "        }\n",
        "except Exception as e:\n",
        "    stream_result = {\n",
        "        'status': 0,\n",
        "        'first_byte_ms': None,\n",
        "        'total_ms': round((time.perf_counter() - start) * 1000, 1),\n",
        "        'preview': [str(e)],\n",
        "    }\n",
        "\n",
        "print(json.dumps(stream_result, indent=2))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Capability review matrix\n",
        "\n",
        "The tutorial recommends evaluating newer Front Door capabilities as architecture decisions, not feature checkboxes. This worksheet captures the five questions to answer for each candidate capability."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "capability_review = pd.DataFrame([\n",
        "    {'capability': 'native gRPC support', 'available_for_path': 'Validate', 'constraints': 'SDKs, streaming semantics, retries, tracing', 'best_route_classes': '/stream/* or specialized APIs', 'rollout_owner': 'Platform + app team', 'success_signal': 'Correct semantics and observability'},\n",
        "    {'capability': 'edge actions', 'available_for_path': 'Validate', 'constraints': 'Rule complexity and ownership', 'best_route_classes': '/inference/*, /agents/*', 'rollout_owner': 'Platform team', 'success_signal': 'Reduced backend burden without policy drift'},\n",
        "    {'capability': 'rate-limit grouping', 'available_for_path': 'Validate', 'constraints': 'Need fair consumer boundary', 'best_route_classes': '/agents/*, /inference/*', 'rollout_owner': 'Security + platform', 'success_signal': 'Fairness under burst and abuse'},\n",
        "    {'capability': 'post-quantum TLS', 'available_for_path': 'Validate', 'constraints': 'Client and partner support, rollback', 'best_route_classes': 'Selected public routes', 'rollout_owner': 'Security + network + platform', 'success_signal': 'Handshake compatibility with explicit acceptance'},\n",
        "])\n",
        "capability_review"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Abuse scenarios\n",
        "\n",
        "Abuse protection should be testable. Start by defining what you are defending against before choosing rate limits or grouping keys."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "abuse_scenarios = pd.DataFrame([\n",
        "    {'scenario': 'One tenant consumes disproportionate capacity', 'boundary_to_test': 'tenant ID or API key', 'affected_routes': '/inference/*, /agents/*'},\n",
        "    {'scenario': 'Repeated agent tool calls from a bad loop', 'boundary_to_test': 'token claim or route + principal', 'affected_routes': '/agents/*'},\n",
        "    {'scenario': 'Malformed requests', 'boundary_to_test': 'WAF signatures and schema validation', 'affected_routes': 'All public routes'},\n",
        "    {'scenario': 'Concentrated bursts from one client population', 'boundary_to_test': 'client IP or token claim', 'affected_routes': '/inference/*, /stream/*'},\n",
        "    {'scenario': 'Retries amplify a partial outage', 'boundary_to_test': 'retry policy + origin health', 'affected_routes': 'All public routes'},\n",
        "])\n",
        "abuse_scenarios"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Metrics to capture during validation\n",
        "\n",
        "The blog calls out the minimum evidence needed to decide whether the edge pattern belongs in production. This cell creates a blank scorecard you can fill in after test runs."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "scorecard = pd.DataFrame([\n",
        "    {'route_class': 'inference', 'p50_ms': None, 'p95_ms': None, 'p99_ms': None, 'error_rate_pct': None, 'first_byte_ms': None, 'failover_behavior': '', 'operator_effort_notes': ''},\n",
        "    {'route_class': 'stream', 'p50_ms': None, 'p95_ms': None, 'p99_ms': None, 'error_rate_pct': None, 'first_byte_ms': None, 'failover_behavior': '', 'operator_effort_notes': ''},\n",
        "    {'route_class': 'agents', 'p50_ms': None, 'p95_ms': None, 'p99_ms': None, 'error_rate_pct': None, 'first_byte_ms': None, 'failover_behavior': '', 'operator_effort_notes': ''},\n",
        "])\n",
        "scorecard"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Code example: GitHub Actions deployment workflow\n",
        "\n",
        "Once the pattern is proven, automate the minimum. This workflow validates and deploys the Bicep template without adding unnecessary ceremony."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "github_actions_yaml = \"\"\"name: deploy-ai-edge\n",
        "on:\n",
        "  workflow_dispatch:\n",
        "jobs:\n",
        "  deploy:\n",
        "    runs-on: ubuntu-latest\n",
        "    steps:\n",
        "      - uses: actions/checkout@v4\n",
        "      - uses: azure/login@v2\n",
        "        with:\n",
        "          creds: ${{ secrets.AZURE_CREDENTIALS }}\n",
        "      - run: az bicep build --file infra/main.bicep\n",
        "      - run: >\n",
        "          az deployment group create\n",
        "          --resource-group rg-ai-edge\n",
        "          --template-file infra/main.bicep\n",
        "          --parameters profileName=afd-ai-edge endpointName=ai-global\n",
        "\"\"\"\n",
        "\n",
        "workflow_dir = Path('.github/workflows')\n",
        "workflow_dir.mkdir(parents=True, exist_ok=True)\n",
        "workflow_file = workflow_dir / 'deploy-ai-edge.yml'\n",
        "workflow_file.write_text(github_actions_yaml, encoding='utf-8')\n",
        "print(workflow_file.read_text(encoding='utf-8'))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Required secrets for GitHub Actions\n",
        "\n",
        "The workflow uses Azure login with a GitHub secret. You will need:\n",
        "\n",
        "- `AZURE_CREDENTIALS`: service principal credentials in the JSON format expected by `azure/login`\n",
        "\n",
        "You will also need the target resource group to exist, or you should extend the workflow to create it."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Sequence view for agent-facing traffic\n",
        "\n",
        "This sequence diagram highlights why `/agents/*` often needs separate governance and abuse controls. A single request can fan out into tool calls, model calls, and telemetry."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "sequence_diagram = \"\"\"sequenceDiagram\n",
        "    participant C as Client\n",
        "    participant F as Azure Front Door\n",
        "    participant W as WAF\n",
        "    participant A as Agent API\n",
        "    participant O as Azure OpenAI\n",
        "    participant M as Monitor\n",
        "\n",
        "    C->>F: GET /agents/run\n",
        "    F->>W: Apply policy + route match\n",
        "    W->>A: Forward request\n",
        "    A->>O: Tool/model call\n",
        "    O-->>A: Completion\n",
        "    A-->>F: JSON response\n",
        "    F-->>C: Global edge response\n",
        "    F->>M: Edge metrics\n",
        "    A->>M: App traces\n",
        "    O->>M: Model telemetry\n",
        "\"\"\"\n",
        "print(sequence_diagram)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Approval rubric\n",
        "\n",
        "Use this rubric to decide whether a route should get Front Door or stay simpler."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "approval_rubric = {\n",
        "    'approve_front_door_when': [\n",
        "        'public exposure',\n",
        "        'distributed users or clients',\n",
        "        'resilience requirement across regions or origins',\n",
        "        'meaningful abuse risk',\n",
        "        'edge-level routing or security value',\n",
        "        'operational team ready to own it'\n",
        "    ],\n",
        "    'keep_simpler_when': [\n",
        "        'internal-only',\n",
        "        'single region',\n",
        "        'low traffic',\n",
        "        'low abuse risk',\n",
        "        'protocol behavior is sensitive and unproven at the edge',\n",
        "        'no measurable benefit from another layer'\n",
        "    ]\n",
        "}\n",
        "print(json.dumps(approval_rubric, indent=2))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Sources and references\n",
        "\n",
        "- Azure Front Door overview: https://learn.microsoft.com/en-us/azure/frontdoor/front-door-overview\n",
        "- Azure Front Door WAF: https://learn.microsoft.com/en-us/azure/web-application-firewall/afds/afds-overview\n",
        "- Azure Front Door rate limiting: https://learn.microsoft.com/en-us/azure/web-application-firewall/afds/waf-front-door-rate-limit-configure\n",
        "- Azure Front Door origin groups and health probes: https://learn.microsoft.com/en-us/azure/frontdoor/origin?pivots=front-door-standard-premium\n",
        "- Azure Front Door gRPC support: https://learn.microsoft.com/en-us/azure/frontdoor/standard-premium/how-to-configure-grpc\n",
        "- Azure Front Door rule sets: https://learn.microsoft.com/en-us/azure/frontdoor/front-door-rules-engine\n",
        "- Azure API Management gateway and policy overview: https://learn.microsoft.com/en-us/azure/api-management/api-management-key-concepts\n",
        "- Azure Architecture Center: https://learn.microsoft.com/en-us/azure/architecture/\n",
        "- Cloud Adoption Framework: https://learn.microsoft.com/en-us/azure/cloud-adoption-framework/\n",
        "- Trusted Launch Azure AI Landing Zone Architecture: https://blog.limitlessdata.ai/trusted-launch-azure-ai-landing-zone-architecture/\n",
        "- Azure Copilot Agent Access Architecture and Governance: https://blog.limitlessdata.ai/azure-copilot-agent-access-architecture-and-governance/\n",
        "- AI agent cost optimization for Azure platform teams guide: https://blog.limitlessdata.ai/ai-agent-cost-optimization-for-azure-platform-teams-guide/"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Summary\n",
        "\n",
        "The standardized pattern in this notebook is intentionally narrow:\n",
        "\n",
        "- classify routes first\n",
        "- put Front Door only on public or distributed paths that justify it\n",
        "- separate `/inference/*`, `/stream/*`, and `/agents/*` early\n",
        "- keep the AI control plane regional\n",
        "- validate resilience, protocol behavior, and abuse controls before standardizing new edge capabilities\n",
        "- preserve simpler regional or private patterns for internal and low-scale workloads\n",
        "\n",
        "## Next Steps\n",
        "\n",
        "1. Replace placeholder resource IDs and domain values in `infra/main.bicep`.\n",
        "2. Run Bicep validation and deploy to a non-production resource group.\n",
        "3. Execute the route probe and streaming probe against real endpoints.\n",
        "4. Fill in the scorecard with p50, p95, p99, error rate, first-byte latency, failover behavior, and operator effort.\n",
        "5. Decide route-by-route whether Front Door, API Management, or a regional ingress pattern is the right default."
      ]
    }
  ]
}