Library

Volume 1 · Cloud-Native Architecture

Notebook
Sign in

Section 22

Azure AI Stack

1,216 words · about 6 min

22.1 Service Reference

Service Use Case Notes
Azure OpenAI Service GPT-4o, embeddings, enterprise GenAI BAA/compliance coverage, PTU for predictable throughput
Azure AI Search Hybrid RAG search Vector + keyword + semantic ranking in one index
Azure Document Intelligence Form/document extraction Prebuilt models for invoices, receipts, forms
AKS Container orchestration GPU node pools, Workload Identity, KEDA-native scaling
Cosmos DB Global NoSQL Multi-region writes, 5 consistency levels, agent state store
Service Bus Enterprise messaging FIFO sessions, transactions, dead-lettering
Event Hubs High-throughput streaming Telemetry, logs, Kafka-protocol compatible
Azure ML Custom ML/MLOps SageMaker equivalent — pipelines, model registry, endpoints
Text Analytics for Health Clinical/domain NER Managed medical NLP
Azure Health Data Services FHIR/DICOM APIs Healthcare interoperability

22.2 Azure OpenAI Deployment Pattern

from openai import AzureOpenAI

client = AzureOpenAI(
    azure_endpoint="https://my-org-ai.openai.azure.com/",
    api_key=os.getenv("AZURE_OPENAI_API_KEY"),
    api_version="2024-06-01"
)

# PTU (Provisioned Throughput Units) for predictable, reserved capacity
# vs. pay-per-token (standard deployment) for variable/bursty workloads

PTU vs. Standard decision: PTU when you have predictable, high-volume traffic and need latency guarantees (reserved GPU capacity, billed regardless of usage). Standard (pay-per-token) when traffic is bursty/unpredictable and you want to avoid paying for idle capacity.

22.3 Reference Architecture — Multi-Tier AI-Enabled Web Application

                         ┌─────────────┐
                         │  Azure CDN  │
                         │ /Front Door │
                         └──────┬──────┘
                                │
                         ┌──────▼──────┐
                         │  Azure API  │
                         │ Management  │
                         │  (Gateway)  │
                         └──────┬──────┘
                                │
              ┌─────────────────┼─────────────────┐
              │                 │                 │
       ┌──────▼──────┐  ┌──────▼──────┐  ┌──────▼──────┐
       │  Container  │  │  Container  │  │   Azure     │
       │  App: API   │  │  App: Worker│  │  Functions  │
       └──────┬──────┘  └──────┬──────┘  └──────┬──────┘
              │                │                 │
       ┌──────▼────────────────▼─────────────────▼──────┐
       │              Azure Service Bus                   │
       └──────┬────────────────┬─────────────────┬──────┘
              │                │                 │
       ┌──────▼──────┐  ┌─────▼──────┐  ┌──────▼──────┐
       │ Azure OpenAI│  │  Cosmos DB │  │  Redis      │
       │  + AI Search│  │  (NoSQL)   │  │  Cache      │
       └─────────────┘  └────────────┘  └─────────────┘

22.4 Azure SQL vs. Cosmos DB — Decision Framework

Factor Azure SQL Cosmos DB
Data model Relational, normalized Document/key-value/graph
Schema Fixed Flexible, evolves freely
Consistency Strong (ACID) 5 tunable consistency levels
Scaling Vertical + read replicas Horizontal (partitioning)
Global distribution Geo-replication Multi-region write
Cost model DTU or vCore Request Units (RU/s)
Best for Transactional, complex joins High-scale, global, flexible schema, agent state

Cosmos DB partitioning example:

Partition Key: /tenantId
┌────────────┐  ┌────────────┐  ┌────────────┐
│ Partition 1│  │ Partition 2│  │ Partition N│
│ tenant-001 │  │ tenant-002 │  │ tenant-N   │
│ Max 20 GB  │  │ Max 20 GB  │  │ Max 20 GB  │
└────────────┘  └────────────┘  └────────────┘

Good partition keys: tenantId, userId, region
Bad partition keys: status (low cardinality → hot partition), createdDate (write hotspot)

22.5 Managed Identity — Eliminating Secrets

// ❌ OLD: Connection strings with secrets baked in
var client = new BlobServiceClient("DefaultEndpointsProtocol=https;AccountKey=SECRET...");

// ✅ MODERN: Managed Identity — zero stored secrets
var credential = new DefaultAzureCredential();
var client = new BlobServiceClient(new Uri("https://myaccount.blob.core.windows.net"), credential);

// DefaultAzureCredential tries, in order:
// 1. Environment variables (CI/CD)
// 2. Managed Identity (when running on Azure)
// 3. Azure CLI / Visual Studio (local dev)
// 4. Interactive browser (fallback)
// Key Vault as a configuration source
builder.Configuration.AddAzureKeyVault(
    new Uri("https://my-vault.vault.azure.net/"),
    new DefaultAzureCredential());

var connectionString = builder.Configuration["DatabaseConnectionString"];

22.6 AWS ↔ Azure Service Equivalence

Azure Service AWS Equivalent Key Difference
App Service Elastic Beanstalk / App Runner App Service has more built-in platform features
Azure Functions Lambda Durable Functions add native orchestration
AKS EKS Broadly similar; AKS control plane is free
Container Apps ECS Fargate Container Apps has built-in KEDA scale-to-zero
Azure SQL RDS SQL Server Same underlying engine
Cosmos DB DynamoDB Cosmos offers more tunable consistency options
Service Bus SQS / SNS Service Bus adds sessions and transactions
Event Hubs Kinesis Similar streaming semantics, Kafka-protocol compatible
Entra ID IAM + Cognito Entra is more enterprise/B2B focused
Key Vault Secrets Manager Comparable capability
Blob Storage S3 Comparable capability
Azure OpenAI Service Bedrock Azure OAI is OpenAI-model-only; Bedrock is multi-model

22.7 Interview Q&A

Q1: You’re designing a new AI-enabled SaaS product on Azure. Walk through your architecture decisions.

A: Multi-tenancy: shared infrastructure, isolated data via database-per-tenant or shared DB with a tenant column, tenant identified via subdomain or JWT claim. Compute: Azure Container Apps for APIs (scale-to-zero, cost-effective), Azure Functions for event-driven background work, AKS only if I need complex GPU scheduling or custom networking. Data: Azure SQL for transactional data, Cosmos DB for high-scale read-heavy data and agent/session state, Redis for hot-path caching, Blob Storage for documents. AI: Azure OpenAI Service behind an internal gateway, Azure AI Search for hybrid RAG. Security: Entra ID for auth (B2C for end users, B2B for enterprise SSO), Managed Identity everywhere so zero secrets are stored, private endpoints for all data services, Key Vault for anything that must remain a literal secret. Observability: Application Insights for APM, Azure Monitor for infra, Log Analytics for centralized logs, custom dashboards for business/AI-quality metrics (token cost, latency, guardrail trigger rate).

Q2: When would you choose Cosmos DB over Azure SQL for an AI platform?

A: Cosmos DB when I need global multi-region writes, schema that varies or evolves per record, massive read/write scale, sub-10ms global read latency, or a document/hierarchical shape — this makes it a natural fit for agent conversation state and session memory. Azure SQL when I need complex joins, non-negotiable ACID consistency, strong existing SQL expertise on the team, or regulated reporting/analytics workloads. In practice I run both in a polyglot-persistence model: Azure SQL for financial/transactional records, Cosmos DB for catalog data and conversational agent state, Redis as a caching layer over both.

Q3: How do you handle secrets management in a cloud-native AI application?

A: Never commit secrets to source control — enforce with .gitignore and pre-commit hooks/git-secrets scanning. Store all secrets — connection strings, API keys, model provider keys, certificates — in Key Vault (Azure) or Secrets Manager (AWS). Use Managed Identity / IRSA so compute can authenticate to the secrets store without holding a bootstrap secret. Load secrets as configuration at startup (AddAzureKeyVault() in .NET) rather than reading them ad hoc. Rotate automatically where the platform supports it (storage keys, SQL passwords); for API keys that can’t auto-rotate, put rotation on a runbook with alerting on key age. For local dev, use dotnet user-secrets or a scoped developer identity against Key Vault — never a shared .env with production keys.

Q4: Your cloud bill jumped 40% this month, apparently from the new GenAI feature. How do you investigate and optimize?

A: Start in Cost Management/Cost Explorer filtered by resource group, tag, and service to find the actual spender — for GenAI features it’s usually token consumption (Azure OpenAI/Bedrock), not compute. Break down token cost by feature/endpoint using request logging so I can see which prompt or feature is driving volume. Common fixes: switch simple queries to a cheaper/smaller model via the LLM gateway’s routing logic; cache repeated queries/embeddings; enforce max-token limits per request; move to PTU/reserved throughput if volume is now predictable and higher than pay-per-token break-even; check for a prompt bug causing retry storms or unbounded context growth. On the infra side: Reserved Instances for stable compute, autoscaling with sane min/max, right-sizing via Advisor/Compute Optimizer, scale-to-zero for non-prod after hours, Cool/Archive tiers for cold data. Put tagging and budget alerts in place so this is caught within a day next time, not a month.