Azure patterns

From FerroxLabs/murage · View interactive version

Azure patterns is an AI agent skill from the GitHub repository FerroxLabs/murage. Guides expert-level azure architecture patterns implementation: cloud and architecture decision frameworks, production-ready patterns, and concrete templates for azure patterns workflows. Use when the user asks about azure architecture patterns, azure patterns configuration, or cloud best practices

How to use this skill

Skill file

Azure Architecture Patterns

When to Use

Use this skill when:

Do NOT use this skill when:


Process

1. Establish Workload Context and Requirements

Before recommending any pattern, extract the full workload profile:

Produce a one-page workload context card before recommending any pattern.


2. Select the Foundational Topology Pattern

Apply this decision framework in order:


3. Apply the Appropriate Architectural Pattern

Match the workload type to a named pattern:

Event-Driven / Async Patterns
Resilience Patterns
Scaling Patterns
Integration Patterns

4. Design the Security Architecture

Every Azure pattern must include a security architecture -- never defer it:


5. Design for Observability

Observability must be architected -- not added retroactively:


6. Define the Deployment Architecture


7. Validate the Architecture

Before finalizing, apply these validation passes:


8. Produce Deliverables

Emit the following concrete artifacts:


Output Format

Workload Context Card

Workload Name:        [name]
SLA Target:           [99.9% / 99.95% / 99.99%]
Peak Load:            [RPS] at [time window], p99 target [ms]
Data Volume:          [GB/day ingest], [TB total stored]
Read/Write Ratio:     [read%] / [write%]
Compliance Baseline:  [None / CIS Benchmark / PCI DSS v4 / HIPAA / FedRAMP]
Team Maturity:        [PaaS-oriented / IaaS-capable / Kubernetes-proficient]
Multi-Region:         [Yes -- Active/Active | Yes -- Active/Passive | No]
Key Integrations:     [list of external systems]

Service Selection Decision Matrix

| Dimension | Option 1 | Option 2 | Option 3 | Recommendation | Rationale |

|-----------|----------|----------|----------|----------------|-----------|

| Compute | App Service P3v3 | Container Apps | AKS Standard D4s_v5 | [choice] | [reason] |

| Messaging | Service Bus Standard | Service Bus Premium | Event Hubs Standard | [choice] | [reason] |

| Primary DB | Azure SQL General Purpose | Azure SQL Hyperscale | Cosmos DB NoSQL | [choice] | [reason] |

| Cache | Redis Basic C1 | Redis Standard C2 | Redis Enterprise E10 | [choice] | [reason] |

| API Gateway | APIM Consumption | APIM Standard v2 | APIM Premium | [choice] | [reason] |

Pattern Recommendation Card

Primary Pattern:        [Pattern Name]
Supporting Patterns:    [list]
Rationale:              [2-3 sentences linking pattern choice to workload requirements]
Key Risks:              [top 2 risks of this pattern for this workload]
Alternatives Rejected:  [pattern] -- rejected because [reason]

Security Architecture Checklist

[ ] All PaaS services have Private Endpoints configured
[ ] Public network access disabled on: [list services]
[ ] Managed Identity assigned to all compute resources
[ ] Key Vault references used for all secrets (no plaintext env vars)
[ ] Azure RBAC assignments scoped to resource level (not subscription)
[ ] NSG flow logs enabled, retention 90 days minimum
[ ] Azure Firewall / NVA deployed in Hub (if Hub-Spoke topology)
[ ] Defender for Cloud Enhanced Security Features enabled
[ ] Azure Policy assignments: [list applicable initiatives]
[ ] TLS 1.2 minimum enforced at gateway and service level
[ ] Customer-Managed Keys configured for: [list if regulated]
[ ] Workload Identity configured for AKS (if applicable)

Production Configuration Template -- Container Apps (Example)

// container-app.bicep
// Production-ready Azure Container Apps deployment
// Assumptions: Private VNet integration, KEDA scaling, Managed Identity

resource containerApp 'Microsoft.App/containerApps@2023-05-01' = {
  name: '${workloadName}-${environment}'
  location: location
  tags: {
    environment: environment
    workload: workloadName
    costCenter: costCenter
    owner: ownerAlias
  }
  identity: {
    type: 'UserAssigned'
    userAssignedIdentities: {
      '${managedIdentityId}': {}
    }
  }
  properties: {
    managedEnvironmentId: containerAppsEnvironmentId
    configuration: {
      ingress: {
        external: false          // Internal only -- exposed via APIM, not directly
        targetPort: 8080
        transport: 'http2'
        traffic: [
          { weight: 100, latestRevision: true }
        ]
      }
      secrets: [
        // Secrets referenced from Key Vault -- never inline values
        { name: 'db-connection', keyVaultUrl: dbConnectionSecretUri, identity: managedIdentityId }
      ]
      activeRevisionsMode: 'Single'  // Use 'Multiple' for canary deployments
    }
    template: {
      containers: [
        {
          name: workloadName
          image: '${containerRegistryLoginServer}/${imageName}:${imageTag}'
          resources: {
            cpu: '0.5'    // Start conservative; tune from Metrics after load test
            memory: '1Gi'
          }
          env: [
            { name: 'ASPNETCORE_ENVIRONMENT', value: environment }
            { name: 'ApplicationInsights__ConnectionString', secretRef: 'ai-connection' }
          ]
          probes: [
            {
              type: 'Liveness'
              httpGet: { path: '/health/live', port: 8080 }
              initialDelaySeconds: 10
              periodSeconds: 30
              failureThreshold: 3
            }
            {
              type: 'Readiness'
              httpGet: { path: '/health/ready', port: 8080 }
              initialDelaySeconds: 5
              periodSeconds: 10
              failureThreshold: 3
              // Readiness probe checks DB + cache connectivity
            }
          ]
        }
      ]
      scale: {
        minReplicas: 2        // Never 0 for production -- cold start penalty
        maxReplicas: 20
        rules: [
          {
            name: 'servicebus-queue-scaler'
            custom: {
              type: 'azure-servicebus'
              metadata: {
                queueName: inputQueueName
                messageCount: '50'  // Scale up when queue depth > 50 messages per replica
                namespace: serviceBusNamespace
              }
              auth: [{ secretRef: 'servicebus-connection', triggerParameter: 'connection' }]
            }
          }
        ]
      }
    }
  }
}

Observability Setup Checklist

[ ] Log Analytics Workspace created (per-environment, not shared)
[ ] Application Insights resource created (per-application)
[ ] Diagnostic settings configured for: Azure SQL, Service Bus, Key Vault, APIM, Container Apps
[ ] Adaptive sampling configured (minimum 20% in production)
[ ] W3C distributed trace headers propagated through APIM
[ ] Azure Monitor Metric Alerts: CPU >85% (5 min), HTTP 5xx >1% (5 min), Queue Depth >1000 (10 min)
[ ] Azure Monitor Log Alert: Business-critical event failure threshold
[ ] Action Group: Severity 0-1 -> PagerDuty; Severity 2-3 -> Teams + email
[ ] Azure Workbook: SLO dashboard (availability %, p95 latency, error rate)
[ ] Resource Health Alerts configured for all critical Azure services

Cost Estimate Range

| Load Level | Estimated Monthly Cost | Top Cost Driver | Optimization Lever |

|------------|------------------------|-----------------|-------------------|

| 50% expected | $[low] | [service] | [action] |

| 100% expected | $[mid] | [service] | [action] |

| 200% expected | $[high] | [service] | [action] |


Rules

  1. Never recommend App Service Consumption plan for production APIs -- the cold start latency (2-10 seconds for .NET, 5-15 seconds for Java) violates most SLOs. Use Premium v3 (always warm) or Container Apps with minReplicas: 2.
  1. Never use Cosmos DB Session consistency for financial transaction data -- Session consistency guarantees reads see your own writes but not other clients' writes. Financial aggregates (account balances, inventory) require Bounded Staleness or Strong consistency, accepting higher RU cost.
  1. Never share a Log Analytics Workspace across production and non-production environments -- cross-environment data in a single workspace creates compliance risks (prod data accessible to dev engineers), noisy alert conditions, and makes cost attribution impossible.
  1. Always use Private Endpoints for PaaS services in production -- public endpoints expose services to Internet-based enumeration and attack surface. The operational overhead of Private DNS Zones is fixed; the security risk of public endpoints compounds over time. There are no production scenarios that justify public endpoint access for Azure SQL, Key Vault, Storage, or Service Bus.
  1. Never put Azure Service Bus connection strings in application configuration files or environment variables -- use Managed Identity with Azure.Service Bus.ServiceBusClient(namespaceUri, new DefaultAzureCredential()). Connection strings rotate, get leaked in logs, and violate zero-trust principles.
  1. Always separate AKS System node pools from User node pools -- system pool runs kube-system components (CoreDNS, tunnelfront, metrics-server). If an application workload starves system components of resources, the entire cluster becomes unstable. Use taints: [CriticalAddonsOnly=true:NoSchedule] on system pools.
  1. Never design an Active-Active multi-region architecture without a conflict resolution strategy for Cosmos DB -- multi-master writes across regions require explicit last-writer-wins or custom conflict resolution policies. An architecture diagram showing two regions writing to Cosmos DB without a conflict policy defined is incomplete and will produce data corruption in production.
  1. Always cost-model Cosmos DB provisioned RU/s against actual access patterns before committing -- at 100 RU/s per container minimum and $0.008/hour per 100 RU/s, a naively partitioned model with 50 containers costs $2,880/month before data storage. Autoscale (1/10 ratio max-to-min) reduces waste but does not eliminate poor partition key choices that cause hot partitions.
  1. Never use Azure Front Door Standard when the workload requires WAF custom rules or Bot Protection -- Standard tier includes only managed WAF rule sets. Custom rules (IP allowlisting, geo-blocking, rate limiting by header) and Bot Manager require Front Door Premium. Discovering this post-deployment requires a tier migration that has a multi-hour propagation window.
  1. Always set resource locks (ReadOnly or Delete) on production hub networking resources -- Azure Firewall, VPN Gateway, and ExpressRoute Circuit deletions are instantaneous and can take hours to restore. A CanNotDelete lock on the hub VNet resource group prevents accidental deletion by engineers with Owner role. This is a last-resort control that does not replace RBAC hygiene.

Edge Cases

Multi-Region Active-Active with Stateful Workloads

Active-Active requires more than deploying the same resources in two regions. Address:

Legacy On-Premises Integration via ExpressRoute

Integrating a new Azure workload with on-premises systems via ExpressRoute introduces routing complexity:

APIM at Scale (>1000 RPS Sustained)

API Management throughput varies dramatically by tier:

Azure Kubernetes Service Cluster Upgrade Pressure

AKS Kubernetes version support windows are shorter than teams expect:

Cosmos DB Partition Key Design Failure

Poor partition key selection is the most common Cosmos DB production failure mode:

Regulated Workloads (PCI DSS v4 / HIPAA)

Regulated workloads on Azure require architectural constraints beyond standard best practices:


Example

Input: "We're building a multi-tenant SaaS order management system for 200 enterprise customers. Peak load is around 500 orders/minute during business hours, dropping to near zero overnight. Orders involve inventory reservation, payment processing (Stripe), and email notifications. We need 99.9% uptime and data must stay in the EU. The team of 8 is comfortable with containers but has limited Kubernetes experience. We're on a startup budget, so cost efficiency matters."


Output:

Workload Context Card

Workload Name:        SaaS Order Management Platform
SLA Target:           99.9% (8.7 hours downtime/year)
Peak Load:            500 orders/minute (~8.3 RPS), business hours EU timezone
                      Order processing latency target: <3 seconds end-to-end (async acceptable)
Data Volume:          ~50 orders/minute average, ~72,000 orders/day, ~2-3 GB/day
Read/Write Ratio:     60% read (order status, history) / 40% write (order create, update)
Compliance Baseline:  No regulated data (Stripe handles PCI scope); standard GDPR data residency
Team Maturity:        Container-proficient, Kubernetes-limited -- favor PaaS/managed services
Multi-Region:         No -- single EU region (West Europe / Amsterdam); data residency constraint
Key Integrations:     Stripe Payments API (outbound), email via SendGrid (outbound),
                      Customer ERP systems (inbound webhooks)
Budget Constraint:    Startup -- optimize for cost; accept operational trade-offs

Service Selection Decision Matrix

| Dimension | Option 1 | Option 2 | Option 3 | Recommendation | Rationale |

|-----------|----------|----------|----------|----------------|-----------|

| Compute | App Service P2v3 | Azure Container Apps | AKS Standard | Container Apps | Team knows containers; AKS operational overhead unjustified at this scale; App Service lacks KEDA scaling |

| Order Queue | Service Bus Standard | Service Bus Premium | Event Hubs | Service Bus Standard | Standard tier supports queues + topics with DLQ; sessions for per-customer ordering; Premium unnecessary at 500 orders/min |

| Primary DB | Cosmos DB NoSQL | Azure SQL General Purpose | Azure SQL Hyperscale | Azure SQL General Purpose (GP_Gen5_4) | Multi-tenant relational schema with FK constraints; order domain is highly relational; Cosmos DB adds complexity without benefit at this scale |

| Cache | Redis Basic C1 | Redis Standard C2 | No cache | Redis Standard C2 | Inventory reservation hot path needs sub-ms reads; Standard C2 gives 6GB memory + replication; Basic has no SLA |

| API Gateway | APIM Consumption | APIM Standard v2 | None / App Gateway | APIM Standard v2 | Per-tenant rate limiting, subscription keys, JWT validation; Consumption too low for sustained load; Standard v2 fits budget |

| Blob Storage | LRS Standard | ZRS Standard | GRS Standard | ZRS Standard | EU-resident requirement, no cross-region replication needed; ZRS protects against zone failure; GRS would replicate outside EU |


Pattern Recommendation Card

Primary Pattern:        Choreography Saga (Order Processing)
Supporting Patterns:    - Competing Consumers (order queue workers)
                        - Queue-Based Load Leveling (HTTP -> Service Bus -> processors)
                        - Gateway Aggregation (APIM front-door)
                        - Strangler Fig (ERP integration anti-corruption layer)
                        - Retry with Exponential Backoff (all external API calls)
                        - Circuit Breaker (Stripe payment API calls)

Rationale:              Order processing involves three distinct steps (inventory reservation,
                        payment, notification) with independent failure modes. Choreography Saga
                        via Service Bus topics allows each step to fail and compensate independently
                        without a central orchestrator becoming a bottleneck. Queue-Based Load
                        Leveling absorbs the 500 orders/minute peak without over-provisioning
                        compute; Container Apps scales workers from minReplicas 2 to maxReplicas 20
                        based on Service Bus queue depth. Overnight scale-to-2-replicas reduces
                        cost during the 16-hour low-traffic window.

Key Risks:              1. Saga compensation complexity -- a failed payment after successful
                           inventory reservation requires an explicit inventory release event.
                           This compensating transaction must be idempotent and tested explicitly.
                        2. Tenant data isolation in a shared Azure SQL database requires
                           Row-Level Security (RLS) policies on all tables. A missing RLS
                           predicate causes cross-tenant data leakage -- the highest severity
                           risk for a multi-tenant SaaS.

Alternatives Rejected:  - AKS: operational maturity mismatch; adds $800-1200/month for cluster
                           management overhead (system node pool, ingress controller, cert-manager)
                        - Cosmos DB: relational order schema with FK constraints and JOIN-heavy
                           reporting queries maps poorly to document model; would require
                           denormalization that increases write complexity
                        - Durable Functions Orchestration Saga: viable but Durable Functions
                           storage overhead ($0.30/million executions + Storage) and cold start
                           behavior are less predictable than Container Apps at this scale

Architecture Data Flow

The order processing flow works as follows:

  1. Customer submits POST /api/orders to APIM endpoint. APIM validates JWT (Azure AD B2C tenant token), applies per-tenant rate limiting (100 orders/minute per tenant subscription key), and routes to the Order API Container App.
  1. Order API validates the request, writes an orders record with status = PENDING to Azure SQL (West Europe, ZRS), and publishes an order.created event to Service Bus Topic orders with the tenantId as the session ID.
  1. Inventory Service (Container App, KEDA-scaled on order.created subscription queue depth) receives the event, checks and reserves inventory in Azure SQL. On success, publishes inventory.reserved. On failure (out of stock), publishes order.cancelled to trigger compensation.
  1. Payment Service (Container App) receives inventory.reserved, calls Stripe API with retry (Polly, max 3 retries, 200ms base, jitter) and circuit breaker (open after 5 consecutive Stripe failures, half-open after 30 seconds). On success publishes payment.captured. On failure publishes payment.failed -- which triggers the Inventory Service to consume from the order.compensate topic and release the reservation.
  1. Notification Service (Container App, minReplicas 1 overnight) receives payment.captured, calls SendGrid API, marks order status = CONFIRMED in Azure SQL.
  1. Customer polls GET /api/orders/{id} via APIM. Order API reads from Azure Cache for Redis (order status cached for 30 seconds, invalidated on status change) to avoid repeated Azure SQL reads for status polling.

Security Architecture Checklist

[x] Azure SQL: Private Endpoint in order-data subnet; public access DISABLED
[x] Redis Cache: Private Endpoint in cache subnet; public access DISABLED
[x] Service Bus Premium namespace: Private Endpoint (note: Standard tier does NOT support
    Private Endpoints -- upgrade to Premium if Private Endpoint is required; at startup
    budget, Standard with IP firewall rules restricting to Container Apps outbound IPs
    is an acceptable interim control)
[x] Key Vault: Private Endpoint; Container Apps reference secrets via Key Vault reference
    (not env vars)
[x] Container Apps: User-Assigned Managed Identity for Azure SQL access (Azure AD auth,
    not SQL auth), Redis access, Service Bus send/receive, Key Vault get
[x] APIM: Virtual Network Integration (External mode) -- APIM in dedicated subnet,
    NSG restricts inbound to port 443 from Internet + AzureLoadBalancer service tag
[x] Azure SQL: Azure AD-only authentication; SQL authentication DISABLED
[x] Row-Level Security on all Azure SQL tables with tenant_id predicate --
    enforced via security policy, not application-layer filtering alone
[x] NSG Flow Logs: enabled on all subnets, 90-day retention
[x] Defender for Cloud: Enhanced Security for Azure SQL, Key Vault, Container Apps
[x] Azure Policy: deny Storage public blob access, deny resources without required tags,
    require TLS 1.2 on App Service / APIM
[ ] CMK: not required (no regulated data); revisit if HIPAA or PCI scope changes
[ ] Azure Firewall: deferred (single workload; use NSGs as primary control at startup
    budget; add Firewall when second workload shares hub)

Cost Estimate (West Europe, USD/month approximate)

| Component | SKU | 50% Load | 100% Load | 200% Load |

|-----------|-----|----------|-----------|-----------|

| Container Apps | Consumption-based (2-20 replicas) | $90 | $160 | $290 |

| Azure SQL | GP_Gen5_4, 100GB | $370 | $370 | $520 (scale to GP_Gen5_8) |

| Redis Cache | Standard C2 | $95 | $95 | $95 |

| Service Bus | Standard tier | $10 | $18 | $35 |

| APIM | Standard v2 | $145 | $145 | $290 (add units) |

| Key Vault | Standard (operations) | $5 | $8 | $15 |

| Storage (ZRS) | 100GB blobs + queues | $5 | $8 | $12 |

| Log Analytics | ~10GB/day ingestion | $45 | $70 | $130 |

| Application Insights | Adaptive sampling 20% | $15 | $25 | $45 |

| Total | | ~$780 | ~$899 | ~$1,432 |

Top cost driver at all load levels: Azure SQL General Purpose. Optimization lever: evaluate Azure SQL Serverless (GP_S_Gen5_4) for steady-state workload -- Serverless auto-pauses after 1 hour idle (saving compute cost overnight) with autopause-resume latency of ~30 seconds, acceptable given async order processing architecture.

Reserved Instance opportunity at 100% load: Azure SQL 1-year Reserved Capacity reduces database cost by ~33% ($370 -> $248). Break-even in 7 months. Commit after 60 days of production data confirming utilization pattern.


Primary ADR: Azure SQL over Cosmos DB for Order Data

ADR-001: Relational Database (Azure SQL) for Order Domain
Date: [today]
Status: Accepted

Context:
The order management domain has highly relational data (Orders -> OrderLines ->
Products -> Tenants -> Inventory). Reporting requirements include cross-tenant
aggregation for the SaaS operator and per-tenant order history with complex filtering.
The team has strong SQL expertise and limited NoSQL experience.

Decision:
Use Azure SQL Database (General Purpose, GP_Gen5_4) with Azure AD authentication,
Row-Level Security for tenant isolation, and Private Endpoint for network security.

Consequences:
Positive: ACID transactions across order, inventory, and payment state. Complex
reporting queries via standard SQL. RLS enforces tenant isolation at database layer
(defense in depth against application bugs). Team can be productive immediately.

Negative: Vertical scaling limit (96 vCores max for single Azure SQL DB; use Elastic
Pool or sharding if tenant count exceeds 500 with high per-tenant write volume).
Cannot easily support global distribution if EU data residency constraint is relaxed
in future (Cosmos DB global distribution is superior for that scenario).

Revisit trigger: If write throughput exceeds 5,000 writes/second sustained or if
geographic expansion beyond EU requires multi-master writes -- at that point, evaluate
Cosmos DB with per-tenant containers and a partition key of tenantId_orderId.
Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.