Showing posts with label CloudArchitecture. Show all posts
Showing posts with label CloudArchitecture. Show all posts

Sunday, May 17, 2026

Microsoft Azure Solutions Architect Expert (AZ-305) Complete Guide

Microsoft Azure Solutions Architect Expert (AZ-305) — Complete Guide

Well-Architected Framework · Identity & Governance · Data Storage · Infrastructure · Business Continuity · Landing Zones · Scenarios · Cheat Sheet

Top Hashtags: #AZ305, #AzureSolutionsArchitect, #MicrosoftAzure, #CloudArchitecture, #AzureArchitect, #WellArchitectedFramework, #CloudAdoptionFramework, #AzureDesign, #MicrosoftCertified, #CloudComputing


Table of Contents

  1. Exam Overview & Architect Mindset
  2. Design Identity, Governance & Monitoring (25–30%)
  3. Design Data Storage Solutions (25–30%)
  4. Design Infrastructure Solutions (30–35%)
  5. Design Business Continuity Solutions (10–15%)
  6. Azure Well-Architected Framework & Landing Zones
  7. Scenario-Based Questions
  8. Cheat Sheet — Quick Reference

1. Exam Overview & Architect Mindset

AZ-305 Exam at a Glance

The AZ-305 exam validates expertise in designing cloud and hybrid solutions — translating business requirements into Azure architectures aligned with the Well-Architected Framework and Cloud Adoption Framework. This is a design exam, not a configuration exam.

Skill Domain Exam Weight
Design infrastructure solutions 30–35% ← LARGEST
Design identity, governance, and monitoring solutions 25–30%
Design data storage solutions 25–30%
Design business continuity solutions 10–15%

Prerequisite: AZ-104 (Azure Administrator Associate) must be held before earning AZ-305 Expert certification.

Critical mindset shift: AZ-305 questions present a business scenario with stated requirements and ask you to recommend, evaluate, or compare Azure services. The key skill is understanding WHY one service fits a scenario better than another — not just knowing what each service does.


What is the Azure Well-Architected Framework?

The Azure Well-Architected Framework (WAF) is Microsoft's set of guiding principles for building high-quality cloud solutions. Every AZ-305 design decision should be justified using WAF pillars.

Five WAF Pillars:

1. Reliability:
→ Design for failure — assume components will fail
→ Use redundancy: Availability Zones, geo-replication, multi-region
→ Define and meet RTO (Recovery Time Objective) and RPO (Recovery Point Objective)
→ Health monitoring, automatic failover, circuit breakers
→ Example: deploy SQL Database with zone-redundant Business Critical tier
             + auto-failover group to paired region

2. Security:
→ Defence in depth: multiple layers of security
→ Principle of least privilege: minimum permissions needed
→ Zero Trust: verify explicitly, assume breach, limit blast radius
→ Encrypt data at rest and in transit; manage secrets in Key Vault
→ Example: Private Endpoints for PaaS, WAF on Application Gateway,
             Managed Identity instead of service accounts

3. Cost Optimisation:
→ Right-size resources — don't over-provision
→ Match consumption to business value (pay for what you use)
→ Reserved Instances for predictable workloads
→ Use PaaS over IaaS where possible (lower management overhead)
→ Azure Hybrid Benefit for existing licences

4. Operational Excellence:
→ Infrastructure as Code (Bicep/Terraform) — repeatable, version-controlled
→ CI/CD pipelines for deployment automation
→ Monitoring: Azure Monitor, Log Analytics, Application Insights
→ Runbooks and automated remediation
→ Change management: blue-green deployments, feature flags

5. Performance Efficiency:
→ Scale horizontally (add instances) not just vertically (bigger VM)
→ Cache frequently accessed data (Azure Cache for Redis)
→ CDN for static content delivery (Azure Front Door / CDN)
→ Choose the right service tier for the workload profile
→ Autoscaling: VMSS, App Service autoscale, AKS cluster autoscaler

What is the Cloud Adoption Framework (CAF)?

Cloud Adoption Framework (CAF):
→ Microsoft's guidance for adopting Azure at enterprise scale
→ Covers: strategy, planning, landing zones, governance, operations

CAF phases:
Strategy:    define business justification, expected outcomes
Plan:        assess current state, create migration backlog
Ready:       set up landing zones, management groups hierarchy
Adopt:       migrate or modernise workloads (lift-and-shift, re-architecture)
Govern:      establish guardrails — Azure Policy, cost management, security baseline
Manage:      operations baseline — monitoring, backup, disaster recovery
Innovate:    build cloud-native solutions, AI/ML, data analytics

Azure Landing Zone:
→ Preconfigured, governance-ready Azure environment for enterprise adoption
→ Includes: management group hierarchy, Azure Policy assignments, networking,
            identity, security baseline, monitoring
→ Conceptual architecture: Platform vs Application landing zones
→ Platform: connectivity hub, identity, management subscriptions (managed by central IT)
→ Application: individual workload subscriptions (managed by application teams)
→ Accelerator: Bicep/Terraform modules to deploy landing zone in hours

Management Group hierarchy (CAF-recommended):
Tenant Root Group
  ├── Platform (managed by central IT)
  │     ├── Management (Log Analytics, Automation)
  │     ├── Identity (AD DS, Entra Connect)
  │     └── Connectivity (hub VNet, VPN/ExpressRoute, Firewall)
  └── Landing Zones (workload teams)
        ├── Corp (connected to hub, private)
        └── Online (internet-facing, DMZ)

2. Design Identity, Governance & Monitoring (25–30%)

How do you design an identity architecture for a hybrid enterprise?

Hybrid identity decision tree:

Question 1: Do you have on-premises Active Directory?
No:  → Cloud-only Entra ID. Use Entra ID Joined devices. Done.
Yes: → Need Entra Connect for identity synchronisation

Question 2: Authentication method for synchronised identities?
Password Hash Sync (PHS): → RECOMMENDED for most orgs
  Pros: works if on-prem unavailable, leaked credential detection,
        seamless SSO with seamless SSO extension
  Cons: password hash in cloud (some orgs have policy against this)

Pass-Through Auth (PTA): → when policy prohibits cloud password hashes
  Pros: passwords never leave on-prem, real-time account state
  Cons: requires on-prem PTA agent availability, no leaked cred detection

Federation (AD FS): → only when advanced requirements (smart cards,
                       complex claims transformation)
  Pros: full control over authentication claims
  Cons: complex, expensive infrastructure, Microsoft recommends migrating away

Question 3: Device management?
Cloud-native devices:  → Entra ID Joined + Intune (MDM)
Existing domain:       → Hybrid Entra ID Joined (domain join + Entra registration)
BYOD:                  → Entra ID Registered + MAM (App Protection Policies)

Identity architecture for a 10,000-person hybrid enterprise:
→ Entra Connect with PHS + Seamless SSO
→ All admin roles in PIM (eligible assignments, not permanent)
→ Break-glass accounts: 2 cloud-only Global Admins, excluded from all CA
→ Conditional Access: MFA all users, block legacy auth, require compliant device
→ Identity Protection: sign-in risk ≥ Medium → MFA, user risk High → password reset
→ Named locations: corporate IP ranges for trusted sign-in signals
→ B2B: Entitlement Management for partner access, time-limited, self-service
→ Entra ID P2 required for PIM, Identity Protection risk policies, Access Reviews

How do you design a governance architecture at scale?

Governance architecture layers:

Layer 1 — Management Group hierarchy:
Root → Decommissioned MG | Platform MG | Landing Zones MG | Sandbox MG
→ Azure Policy applied at MG level inherits to all child subscriptions
→ RBAC applied at MG level inherits to all child subscriptions

Layer 2 — Azure Policy:
Initiative: "CIS Azure Benchmark" or custom baseline
Key policies:
  Deny:  "No public IP on VMs" (enforces private-only VMs)
  Deny:  "Allowed locations: UK South, UK West" (data residency)
  Deny:  "Allowed VM SKUs" (prevent large SKUs in dev)
  Audit: "Storage accounts should use private endpoints"
  DINE:  "Deploy Azure Monitor Agent if missing" (auto-remediate)

Layer 3 — Azure Blueprints (or Bicep/Terraform for landing zones):
→ Combine: role assignments + policy assignments + ARM templates
→ Assign to subscriptions for consistent baseline deployment
→ Note: Bicep + Azure DevOps is now preferred over Blueprints for new designs

Layer 4 — RBAC design:
Management Group → Owner (cloud platform team only — use PIM)
Subscription → Contributor (workload team — via PIM)
Resource Group → Contributor/specific roles (workload developers)
Resources → Reader/specific data roles (application service principals)

Layer 5 — Tagging strategy:
Mandatory tags enforced by Azure Policy:
  Environment: Production | Development | Test
  Owner:        team or product owner email
  CostCentre:   cost allocation code
  Application:  application name/ID
  DataClass:    Public | Internal | Confidential | Restricted
Cost Management: filter by tag to see per-team, per-app spending

Layer 6 — Subscription design:
Option A: One subscription per environment (simplest)
  Prod-Sub | Dev-Sub | Test-Sub
Option B: One subscription per workload (better isolation)
  Sales-Prod | HR-Prod | Finance-Prod (separate blast radius, billing)
Option C: Hybrid (recommended for large orgs)
  Platform subs (connectivity, identity, management) + Workload subs

How do you design a monitoring solution for Azure?

Monitoring architecture:
→ Centralised Log Analytics workspace (one per environment or per org)
→ All resources send diagnostic logs and metrics to central workspace
→ Azure Monitor alerts trigger action groups (email, Teams, PagerDuty)

Data sources and collection:
Activity Log:        subscription-level control plane operations (all subs → workspace)
Resource Diagnostics: service-level logs (SQL queries, App Gateway access, Key Vault ops)
VM Guest OS:          Azure Monitor Agent + Data Collection Rules → workspace
Application:          Application Insights SDK → telemetry (requests, exceptions, dependencies)
Container:            Container Insights → AKS node + pod metrics to workspace
Security:             Microsoft Defender for Cloud → security findings to workspace
Network:              Network Watcher → flow logs, connection monitor

Application Insights:
→ APM (Application Performance Monitoring) for web applications
→ Instrumentation: add SDK or use auto-instrumentation (App Service, AKS)
→ Telemetry: requests, exceptions, dependencies (SQL, HTTP calls), custom events
→ Live Metrics: real-time monitoring during deployment
→ Availability tests: ping test every 5 minutes from multiple Azure regions
→ Smart detection: ML-based anomaly detection (failure rate spikes, performance degradation)

Azure Monitor Alerts:
Metric alerts:   trigger on: CPU > 80%, DTU > 90%, response time > 2s
Log alerts (KQL): trigger on: error rate > 5%, specific exception count
Activity log:    trigger on: resource deleted, policy denied, security event

Action Groups (what happens when alert fires):
Email:           notify team
SMS:             notify on-call
Teams webhook:   post to Teams channel
Azure Function:  auto-remediate (restart service, scale out)
Logic App:       create ITSM ticket, update status page
Automation Runbook: execute remediation script

Dashboard and visualisation:
Azure Monitor Dashboards: operational view for NOC
Azure Workbooks:          custom parameterised reporting and analysis
Power BI:                 management-level KPI reporting from Log Analytics
Grafana:                  popular open-source dashboards (integrates with Azure Monitor)

3. Design Data Storage Solutions (25–30%)

How do you choose the right Azure storage service?

Storage service selection matrix:

Requirement                                  → Best Service
Unstructured blobs (documents, images, video) → Azure Blob Storage
Virtual machine disks                         → Azure Managed Disks
File shares (SMB/NFS, lift-and-shift)         → Azure Files
Hybrid file server (on-prem + cloud cache)    → Azure File Sync
NoSQL document database (JSON)                → Azure Cosmos DB (SQL API)
NoSQL key-value at massive scale              → Azure Cosmos DB (Table API)
Globally distributed, multi-write            → Azure Cosmos DB (any API)
Relational data, OLTP workloads              → Azure SQL Database
SQL Server features, lift-and-shift           → Azure SQL Managed Instance
Data warehouse, analytical queries (OLAP)    → Azure Synapse Analytics / Fabric
Real-time analytics over streaming data      → Azure Synapse Analytics + Event Hubs
Message queue (simple, cheap, massive)        → Azure Storage Queues
Enterprise messaging (ordering, DLQ, pub/sub) → Azure Service Bus
Event streaming (millions/sec, telemetry)     → Azure Event Hubs
Time-series / IoT analytics                  → Azure Data Explorer / KQL
Graph data (relationships between entities)  → Azure Cosmos DB (Gremlin API)
Cache layer (session, query results)          → Azure Cache for Redis

Blob storage access tiers (cost vs latency):
Hot:     frequent access, highest storage cost, lowest access cost
Cool:    30-day minimum, cheaper storage, higher access cost
Cold:    90-day minimum, very cheap storage, higher access cost
Archive: 180-day minimum, cheapest storage, OFFLINE (rehydrate before read)
Lifecycle policy: automatically tier blobs based on last modified age

Blob storage redundancy (durability vs cost):
LRS:   3 copies, single datacenter, cheapest
ZRS:   3 copies across AZs, zone-resilient (recommended for most production)
GRS:   LRS + async copy to paired region, secondary readable only after failover
GZRS:  ZRS + async to paired region, highest durability (16 nines)
RA-GRS/RA-GZRS: read from secondary at all times (DR read scale-out)

How do you design a relational database solution on Azure?

Azure SQL options:

Azure SQL Database (fully managed PaaS):
→ Serverless tier: auto-pause during idle (cost saving for dev/test)
→ General Purpose: balanced compute/storage (most production OLTP)
→ Business Critical: in-memory OLTP, readable secondary, local SSD
→ Hyperscale: up to 100 TB, fast backup/restore (large databases)
→ Elastic Pool: share resources across multiple databases (multi-tenant SaaS)
→ Auto-failover groups: automatic geo-replication + failover (RPO < 5 sec)
→ Zone-redundant: Business Critical and General Purpose (zonal HA)

Azure SQL Managed Instance (PaaS with near-full SQL Server compatibility):
→ Lift-and-shift of SQL Server workloads needing: SQL Agent, CLR, linked servers,
  Service Broker, CDC, cross-database queries (not available in SQL Database)
→ Deployed INSIDE a VNet (private, no public endpoint by default)
→ Business Critical tier: in-memory OLTP + readable secondary
→ Migration: Database Migration Service from on-prem SQL Server
→ Choice: if application needs SQL Agent or cross-database queries → Managed Instance

SQL Server on Azure VM (IaaS):
→ Full SQL Server control (any version, any edition, OS-level access)
→ Use when: need features only available on bare SQL Server (SSRS, SSAS, SSIS),
            or specific versions/configurations not supported in PaaS
→ Higher management overhead vs PaaS options

Decision framework:
Can PaaS SQL Database handle the requirements?
  Yes: use SQL Database (lowest management overhead)
  Needs SQL Agent, cross-DB queries, Service Broker?
    Yes: use SQL Managed Instance
    Needs full OS control or specific SQL Server version?
      Yes: SQL Server on Azure VM

High availability for SQL:
Single region:    Business Critical tier → built-in Always On AG (3 replicas, ZR)
Multi-region:     Auto-failover group → geo-replication + automatic DNS failover
RPO:              < 5 seconds (geo-replication log shipping)
RTO:              < 30 seconds (automatic failover with DNS redirect)

How do you design a Cosmos DB solution?

Azure Cosmos DB:
→ Globally distributed, multi-model NoSQL database
→ SLA: 99.999% availability, single-digit millisecond latency (P99)
→ APIs: SQL (Core), MongoDB, Cassandra, Gremlin (graph), Table, PostgreSQL

Key design decisions:

1. Partition key selection (MOST CRITICAL decision):
→ Must provide even distribution of data (high cardinality)
→ Must be included in most queries (enables partition-targeted reads)
→ Cannot be changed after container creation
→ Good: UserId, CustomerId, TenantId, ProductId
→ Bad: Boolean, Status (low cardinality — hot partitions)
→ Synthetic key: if single key has low cardinality, combine fields
   e.g., {country}-{city} instead of country alone

2. Consistency levels (5 levels, stronger = more latency/cost):
Strong:           linearisable — always reads latest write (highest cost)
Bounded Staleness: reads lag writes by configurable window (K ops or T seconds)
Session:           strong consistency within a session (DEFAULT — best for most apps)
Consistent Prefix: reads never see out-of-order writes
Eventual:          weakest — reads may lag, highest performance

3. Request Units (RUs):
→ Currency of Cosmos DB — normalised unit of throughput
→ Every operation (read, write, query) consumes RUs
→ Provision throughput (guaranteed RU/s) or serverless (pay per op)
→ 1 RU = reading a 1 KB document by its partition key + id

4. Global distribution:
→ Add regions with one click — data replicated automatically
→ Single-write region: one primary write, any region reads (default)
→ Multi-region write: any region can write (use for write-heavy global apps)
→ Conflict resolution: needed for multi-write (last write wins or custom)

5. Change Feed:
→ Ordered stream of inserts and updates in a Cosmos DB container
→ Use for: event-driven microservices, materialised views, ETL to analytics
→ Consumers: Azure Functions trigger, Spark, SDK change feed processor

4. Design Infrastructure Solutions (30–35%)

How do you design a compute solution — choosing between VM, App Service, AKS, and Functions?

Compute service selection framework:

Azure Virtual Machines (IaaS):
→ Use when: need full OS control, specific OS/software, GPU, legacy apps
→ Lift-and-shift: move existing apps without code changes
→ HA pattern: Availability Zones + Standard Load Balancer (99.99% SLA)
→ Scale: VM Scale Sets (VMSS) for auto-scaling clusters
→ Avoid for: stateless web apps (use App Service/containers instead)

Azure App Service (PaaS):
→ Use when: web apps, REST APIs, mobile backends in .NET, Java, Node, Python, PHP
→ No VM management: Azure handles OS, patching, load balancing, scaling
→ Deployment slots: zero-downtime deployments, blue-green, A/B testing
→ VNet Integration: outbound private connectivity to databases/services
→ Private Endpoint: inbound private access (no public internet)
→ Scale: horizontal (add instances) up to 30, vertical (bigger plan)
→ Choose tier: Free/Basic (dev/test) → Standard (production, autoscale)
             → Premium (VNet integration) → Isolated (ASE, dedicated)

Azure Kubernetes Service (AKS):
→ Use when: microservices, containerised workloads, complex orchestration
→ Benefits: auto-scaling, rolling deployments, self-healing, rich ecosystem
→ Design: multiple node pools (system + user), node autoscaler, HPA
→ Networking: Azure CNI (direct pod IPs from VNet — needed for private)
→ Storage: Azure Disk (ReadWriteOnce) or Azure Files (ReadWriteMany)
→ Security: Managed Identity for pod-level Azure access (Workload Identity)
→ Ingress: Azure Application Gateway Ingress Controller (AGIC) for WAF

Azure Functions (Serverless):
→ Use when: event-driven compute, short-lived operations, unknown/spiky traffic
→ Scale to zero: pay only during execution (Consumption plan)
→ Premium plan: pre-warmed instances, VNet integration, longer timeout
→ Triggers: HTTP, Service Bus, Event Hub, Blob Storage, Timer, Cosmos DB
→ Durable Functions: stateful orchestration (fan-out/fan-in, long workflows)
→ Avoid for: long-running processes > 10 min (use App Service or AKS)

Decision tree:
Need OS-level control?              → VM
Containerised microservices?        → AKS
Web/API app, managed PaaS?          → App Service
Event-driven, short duration?       → Azure Functions
Burst traffic, stateless?           → Functions or App Service with autoscale
Complex stateful workflow?          → Durable Functions or Logic Apps

How do you design a network architecture for enterprise Azure?

Hub-Spoke network topology (recommended for most enterprises):

Hub VNet (central):
→ Shared services: Azure Firewall, VPN/ExpressRoute Gateway, Bastion, DNS
→ Managed by central networking team
→ All spoke traffic routes through hub (forced tunnelling)
→ Hub in each Azure region for global presence

Spoke VNets (per workload/environment):
→ Each application or team gets own spoke VNet
→ Peered to Hub: VNet Peering (low latency, same region)
               Global VNet Peering (cross-region)
→ No direct spoke-to-spoke peering (routes through hub firewall for inspection)
→ Subnet design: AppSubnet, DataSubnet, PrivateEndpointSubnet, etc.

Virtual WAN (alternative for large/global organisations):
→ Microsoft-managed hub-and-spoke at scale
→ Supports: any-to-any connectivity (spoke-spoke via VWAN hub)
→ Integrates: VPN, ExpressRoute, SD-WAN partners, Azure Firewall Manager
→ Use for: organisations with 10+ spokes or multiple regions

On-premises connectivity:
VPN Gateway:     encrypted IPsec over internet (up to 10 Gbps, simpler, cheaper)
ExpressRoute:    private dedicated circuit via connectivity provider
                 (consistent latency, up to 100 Gbps, higher cost, compliance)
ExpressRoute + VPN: redundant connectivity (ExpressRoute primary, VPN backup)

DNS architecture:
Azure Private DNS zones: private name resolution within Azure VNet
  privatelink.blob.core.windows.net → maps to storage private endpoint IPs
  privatelink.database.windows.net  → maps to SQL private endpoint IPs
Azure DNS Resolver: forward on-prem DNS queries to Azure private zones
                    forward Azure queries to on-prem DNS servers
  → Enables split-horizon DNS for hybrid environments

DDoS Protection:
DDoS Network Protection: per-VNet (recommended for public-facing)
DDoS IP Protection:      per-public IP (simpler, less features)
WAF:                     Application Gateway WAF or Front Door WAF
                         (protects against OWASP Top 10, layer 7 attacks)

How do you design a secure solution using Azure Key Vault?

Azure Key Vault:
→ Centralised secrets, keys, and certificates management
→ Every application should use Key Vault — NEVER store secrets in code/config

Key Vault uses:
Secrets:      connection strings, API keys, passwords
Keys:         RSA/EC keys for envelope encryption, signing
Certificates: X.509 certificates with auto-renewal (Let's Encrypt, DigiCert)

Access patterns:
Managed Identity (RECOMMENDED):
  → Application Managed Identity → assigned Key Vault Secrets User role
  → No credentials to manage, no rotation risk
  → Code: var secret = await client.GetSecretAsync("ConnectionString");

RBAC roles for Key Vault:
  Key Vault Secrets User:    read secret values (applications)
  Key Vault Secrets Officer: manage secrets, not read values (operations)
  Key Vault Administrator:   full control (admin — use PIM)
  Key Vault Reader:          read metadata, not values (audit)

Key Vault networking:
  Private Endpoint:     Key Vault accessible only via private IP in VNet
  Service Endpoint:     traffic stays on Azure backbone (no private IP)
  Firewall:             allowlist specific IPs/VNets; deny all others
  Production: always Private Endpoint + disable public access

Soft delete + Purge Protection:
  Soft delete (90 days): deleted secrets recoverable for 90 days
  Purge Protection:      prevents permanent deletion for retention period
  Both required for: compliance, ransomware protection, accidental deletion
  NEVER disable purge protection in production

Key rotation:
  Manual:   generate new version, update application to use latest version
  Automatic (certificates): Key Vault rotates before expiry via CA integration
  Event-driven: Key Vault fires Event Grid event on near-expiry
                → Logic App / Azure Function generates and stores new key
                → Notifies application to reload secret

5. Design Business Continuity Solutions (10–15%)

How do you design for high availability and disaster recovery?

Key definitions:
RTO (Recovery Time Objective):
  Maximum acceptable time for service to be restored after failure
  "We can be down for no more than 4 hours" → RTO = 4 hours

RPO (Recovery Point Objective):
  Maximum acceptable data loss measured in time
  "We cannot lose more than 15 minutes of transactions" → RPO = 15 minutes

SLA tiers and what they require:
99.9%   = 8.7 hours downtime/year  → single instance + Standard SSD (min)
99.95%  = 4.4 hours downtime/year  → Availability Set (2+ VMs)
99.99%  = 52 minutes downtime/year → Availability Zones (2+ VMs, 2+ AZs)
99.999% = 5.2 minutes downtime/year → multi-region active-active

Azure HA architecture patterns:

Single region HA (protects against hardware/datacenter failure):
  Azure Load Balancer + VM Scale Set across 3 Availability Zones
  SQL: Business Critical (3 replicas, zone-redundant)
  Storage: ZRS (3 copies across AZs)
  App Service: Premium tier (zone redundancy)
  SLA: 99.99% for compute + 99.99% for database

Multi-region HA (protects against region-wide outage):
Active-Passive (failover):
  Primary region handles traffic
  Secondary region: pre-deployed, inactive (warm standby)
  DNS failover via Azure Traffic Manager or Azure Front Door
  SQL: auto-failover group with automatic DNS failover
  RTO: minutes (DNS TTL), RPO: < 5 seconds (geo-replication)
  Use for: moderate RTO/RPO requirements

Active-Active (both regions serve traffic simultaneously):
  Both regions active, load balanced globally
  Data: Cosmos DB multi-write, or synchronous replication
  DNS: Azure Front Door (anycast routing, fastest region wins)
  RTO: near-zero (no failover needed — traffic shifts automatically)
  RPO: near-zero (no replication lag for active-active write)
  Use for: highest availability requirements, global user base

Azure Site Recovery (ASR):
  VM replication to secondary region
  Recovery Plans: orchestrated failover in correct order
  Test failover: validate DR without impact to production
  RTO: 1-2 hours (VM startup + DNS propagation)
  RPO: 15 minutes (replication interval)

How do you design a backup strategy?

Azure Backup architecture:

Recovery Services Vault vs Backup Vault:
Recovery Services Vault: VMs, SQL in VM, Azure Files, on-prem (MARS/MABS)
Backup Vault:            newer vault type — Blobs, Disks, AKS, PostgreSQL Flexible

Backup policies (design per RPO/RTO/retention):
Frequency:  hourly, daily, weekly
Retention:  daily (7-30 days), weekly (up to 5 years), monthly/yearly (compliance)
Cross-region restore: restore to paired region for DR (opt-in, extra cost)

Azure Backup for VMs:
→ Crash-consistent (default) or application-consistent (VSS on Windows)
→ Instant restore: restore individual files in minutes from snapshot
→ Soft delete: 14 days protection against accidental/ransomware deletion
→ Immutable vault: prevents deletion of backup data (locked permanently)

SQL Server in Azure VM:
→ Workload-aware backup: full + differential + log backup
→ Log backup every 15 minutes → RPO of 15 minutes for SQL
→ Compression enabled by default

Azure SQL Database:
→ Built-in automated backups: full weekly, differential 12-24h, log every 5-12 min
→ Point-In-Time Restore (PITR): restore to any second within retention period
→ Long-term retention (LTR): store backups up to 10 years (compliance)

Geo-redundant backup storage:
→ Recovery Services Vault: GRS (default) or LRS
→ Cross-region restore: restore backup from primary in secondary region
→ Required for: regulatory compliance, DR strategy validation

Backup monitoring:
→ Azure Backup Reports (Power BI): compliance dashboard, which VMs NOT backed up
→ Azure Monitor alerts: backup job failures → email/Teams notification
→ Recovery Services Vault → Backup Jobs → filter by status = Failed

6. Azure Well-Architected Framework & Landing Zones

What is the Azure Architecture Centre and key architecture patterns?

Azure Architecture Centre (docs.microsoft.com/azure/architecture):
→ Microsoft's official reference for proven Azure architectural patterns
→ Reference architectures: tested designs for common scenarios
→ Design patterns: reusable solutions to recurring problems

Key cloud design patterns for AZ-305:

1. Retry pattern:
   Transient failures (network timeout, throttling) → automatically retry
   Exponential backoff: wait 1s, 2s, 4s, 8s between retries
   Circuit Breaker: stop retrying after threshold → fail fast

2. Circuit Breaker pattern:
   Prevent cascading failures when a downstream service is unhealthy
   States: Closed (normal) → Open (failing, reject calls) → Half-Open (test)
   Implementation: Polly (C#), resilience4j (Java)

3. CQRS (Command Query Responsibility Segregation):
   Separate read and write models
   Write model: transactional database (SQL), optimised for writes
   Read model: denormalised read store (Cosmos DB, Redis), optimised for reads
   Event sourcing: store events, not state; rebuild state by replaying events

4. Strangler Fig pattern:
   Incrementally replace a monolith with microservices
   New requests → new service; old requests → legacy system
   Gradually migrate functionality until legacy system is empty

5. Event-driven architecture:
   Services communicate via events (loose coupling)
   Event Grid: routing discrete state change events
   Service Bus: reliable ordered message delivery
   Event Hubs: high-volume event streaming

6. Bulkhead pattern:
   Isolate critical resources — if one component fails, others continue
   e.g., separate thread pools, connection pools per downstream service
   Prevents one slow service from exhausting all resources

7. Cache-Aside pattern:
   Application manages cache explicitly:
   1. Check cache (Redis) — if found, return cached value
   2. If not found: query database, store in cache, return value
   3. On update: update database, INVALIDATE cache (not update)
   Use: Azure Cache for Redis + Azure SQL / Cosmos DB

8. Federated Identity pattern:
   Delegate authentication to external identity provider (IdP)
   Application trusts tokens from Entra ID (or ADFS, Google, etc.)
   Benefits: SSO across apps, no password management per app

What are the key networking design patterns for AZ-305?

Private Endpoint (most important networking concept for AZ-305):
→ Assign a private IP from your VNet to an Azure PaaS service
→ Traffic between your VNet and the PaaS service never leaves the Microsoft backbone
→ Disable public endpoint on PaaS resource for maximum security
→ Requires: Private DNS Zone to resolve FQDN to private IP

Pattern: secure multi-tier application
  App Service (private endpoint inbound) ← only VNet traffic allowed
    ↓ (VNet Integration — outbound)
  Azure SQL Database (private endpoint) ← no public access
  Azure Key Vault (private endpoint) ← no public access
  Azure Storage (private endpoint) ← no public access

Azure Front Door:
→ Global application delivery network: CDN + WAF + load balancing + failover
→ Anycast: routes users to the closest Azure PoP (Point of Presence)
→ WAF: OWASP protection globally at the edge
→ Origin groups: pool of backends (App Service in US + App Service in EU)
→ Health probes: automatically route away from unhealthy backends
→ Use for: global web applications with multi-region active-active

Azure Traffic Manager:
→ DNS-based global load balancing (NOT a reverse proxy — users connect directly to origin)
→ Routing methods:
  Priority:      primary region + failover regions
  Weighted:      distribute traffic by percentage (canary deployments)
  Performance:   route to lowest latency region for the user
  Geographic:    route users to specific region (data residency)
  Multivalue:    return all healthy endpoints, client picks
→ Use for: global routing of any protocol (not just HTTP), DNS-based failover

Azure Front Door vs Traffic Manager:
Front Door:       HTTP/HTTPS only, reverse proxy, WAF, anycast, CDN, SSL offload
Traffic Manager:  any protocol, DNS-based (no proxy), no WAF, no CDN
Choose Front Door for modern web applications
Choose Traffic Manager for non-HTTP workloads or existing architectures

7. Scenario-Based Questions

Scenario: Design a globally available, zero-trust e-commerce platform handling 1M users.

Requirements:
→ 99.99% SLA, global users, GDPR compliance (EU data residency)
→ Zero Trust security, no public access to backend services
→ Auto-scaling for seasonal traffic spikes

Architecture:

GLOBAL LAYER:
Azure Front Door Premium:
  → WAF policy: OWASP 3.2, custom rules (bot protection, rate limiting)
  → Origins: App Service (West Europe) + App Service (East US)
  → Health probes: route away from unhealthy origins automatically
  → CDN: static assets (images, JS, CSS) cached at edge PoPs
  → Private Link to App Service backend (Front Door → App Service private)

COMPUTE LAYER (West Europe — primary):
Azure App Service (Premium v3, zone-redundant):
  → Outbound via VNet Integration → private access to all backends
  → Private Endpoint for inbound (Front Door is the only entry point)
  → Auto-scale: 2-50 instances based on CPU and HTTP queue
  → Deployment slots: blue-green deployments (swap staging → production)

DATA LAYER:
Azure SQL Database (Business Critical, zone-redundant):
  → Auto-failover group → East US (passive secondary)
  → Private Endpoint: no public internet access
  → Encryption: Always Encrypted for PII columns (GDPR)
  → Auditing: all queries logged to Log Analytics

Azure Cosmos DB (SQL API):
  → Multi-region: West Europe (write) + East US (read)
  → Product catalogue, shopping cart, user sessions
  → Session consistency (strong within session, eventual across regions)
  → PITR: 30-day point-in-time restore

Azure Cache for Redis:
  → Product catalogue cache (60-minute TTL)
  → Session state store (24-hour TTL)
  → Private Endpoint

SECURITY LAYER:
Azure Key Vault (private endpoint): connection strings, API keys, TLS certs
Managed Identity: App Service → Key Vault, SQL, Storage (no stored credentials)
Private DNS Zones: all PaaS services resolve to private IPs
DDoS Network Protection: on all public-facing VNets
Microsoft Defender for Cloud: security posture management across all services
Microsoft Purview: classify and track PII data (GDPR compliance)

MONITORING:
Application Insights: request traces, exceptions, dependency calls, availability tests
Azure Monitor: infrastructure metrics, alerts, action groups
Log Analytics workspace: centralised logs from all services
KQL alert: failed login rate > 5% in 5 minutes → Teams alert

Scenario: A company wants to migrate a 3-tier on-premises application to Azure. Design the migration approach.

Current state: 
  Web tier: 3 IIS servers (Windows Server 2019)
  App tier:  4 .NET application servers
  Data tier: SQL Server 2019 cluster (500 GB, 100 concurrent connections)

Migration phases using CAF Migrate + Modernise:

Phase 1 — Assess (2 weeks):
  Azure Migrate: discover and assess all servers
    → Right-size recommendations (map on-prem specs to Azure SKUs)
    → Dependency analysis (what does each server call?)
    → Cost estimates for IaaS (lift-and-shift) vs PaaS (modernise)

Phase 2 — Lift-and-Shift (IaaS first — 4 weeks):
  Web tier:  3 × D4s_v5 VMs → Application Gateway → 3 VMs in AZ1/2/3
  App tier:  4 × D8s_v5 VMs → Internal Load Balancer → AZ1/2/3
  Data tier: SQL Server on Azure VM (business critical, zone-redundant)
  Migration tool: Azure Migrate + Replication (agent-based for physical)
  Cutover: DNS switch, 4-hour maintenance window, rollback plan ready
  
Phase 3 — Optimise and Modernise (3 months post-migration):
  Web tier:  migrate IIS apps → Azure App Service (Premium, ZR)
             Benefits: no VM management, built-in scaling, deployment slots
  App tier:  containerise .NET apps → Azure Kubernetes Service
             Benefits: better resource utilisation, rolling deployments
  Data tier: assess SQL Managed Instance compatibility
             Azure Database Migration Service (DMS) → online migration (< 1h cutover)
             If SQL Agent or Service Broker needed → SQL Managed Instance
             If standard T-SQL → Azure SQL Database Business Critical

Phase 4 — Govern and Secure (ongoing):
  Azure Policy: enforce tagging, no public IPs on VMs, encryption at rest
  Cost Management: reserved instances for stable workloads (save 40%)
  Monitoring: Azure Monitor + Application Insights (enable for modernised apps)
  Security: Defender for Servers (VMs) + Defender for SQL (databases)

Scenario: Design a multi-tenant SaaS architecture on Azure.

Multi-tenant SaaS: one deployment serves multiple customer organisations

Tenancy model decision:

Model A — Shared everything (full multi-tenant):
  → One database, one compute, all tenants share
  → Lowest cost, highest density
  → Risk: noisy neighbour, data isolation challenges
  → Use for: small tenants, cost-sensitive, lower compliance requirements
  → Data isolation: Row-Level Security in SQL Database (TenantId filter)
  → Compute isolation: App Service multi-tenant with Entra ID OIDC tenant filtering

Model B — Shared compute, separate databases (hybrid):
  → One App Service plan, one Cosmos DB container per tenant (partition by TenantId)
  → OR: Elastic Pool — separate databases sharing one SQL server
  → Elastic Pool: up to 500 databases, pooled DTUs/vCores
  → Good balance: isolation at data layer, shared compute cost
  → Use for: SMB SaaS with moderate isolation requirements

Model C — Fully isolated (silo):
  → Separate subscription or resource group per tenant
  → Highest isolation, highest cost
  → Use for: enterprise tenants, strict compliance (FinTech, Healthcare)
  → Deployment: Bicep template, deploy new resources per tenant onboarding

SaaS-specific design patterns:
Onboarding automation: Logic App / Azure Function → provision new tenant infra
Tenant routing:   App Service → header/domain-based routing to correct data
Tenant billing:   Azure Cost Management tags (TenantId) → per-tenant cost tracking
Tenant offboarding: Data export → soft delete retention → hard delete after 90 days
Compliance:       Purview sensitivity labels per tenant, separate Key Vault per tenant

Scenario: How do you design for cost optimisation without sacrificing reliability?

Cost optimisation architecture decisions:

1. Right-size with Azure Advisor:
   → Azure Advisor → Cost → Underutilised resources
   → VMs with < 5% average CPU → downsize (D4 → D2)
   → SQL DTUs < 20% average → move to smaller service objective

2. Reserved Instances (40-72% savings):
   → 1-year RI for VMs known to run 24/7 (web servers, databases)
   → 3-year RI for very stable workloads (domain controllers, monitoring)
   → Scope: shared (across all subscriptions) for maximum flexibility

3. Azure Savings Plans (up to 65%):
   → Commitment to hourly spend on compute (any region, any size)
   → More flexible than Reserved Instances
   → Best for variable but consistent compute usage

4. Azure Hybrid Benefit:
   → Windows Server with SA: 40% savings on Windows VMs
   → SQL Server with SA: 55% savings on SQL licensing
   → Stack together with Reserved Instances for up to 80% savings

5. PaaS over IaaS:
   → Serverless/PaaS: pay only for what you use
   → App Service vs VMs: same capability, App Service scales to zero in some tiers
   → Azure Functions (Consumption): pay per execution (dev/test = free tier)

6. Autoscaling + scheduled scaling:
   → Scale in nights/weekends for non-production
   → VMSS: minimum 2 instances (HA), scale out on CPU > 70%
   → Dev VMs: auto-shutdown at 6pm via Azure Automation

7. Storage lifecycle management:
   → Blob: auto-tier (Hot → Cool after 30 days → Archive after 365 days)
   → Saves 70-95% on old data that must be retained

8. Dev/Test pricing:
   → Azure Dev/Test subscriptions: discounted Windows Server licensing
   → SQL in Dev/Test: no SQL licence cost (dev only workloads)

9. Spot VMs (up to 90% discount):
   → Fault-tolerant, interruptible workloads: batch processing, rendering, CI runners
   → Use VMSS with Spot priority + fallback to regular (Azure auto-evicts when needed)

10. Network costs:
    → Outbound bandwidth costs money; keep data in same region as consumers
    → VNet Peering cross-region: transfer costs (consider VPN vs peering)
    → CDN: serve static content from edge to reduce origin egress

8. Cheat Sheet — Quick Reference

AZ-305 Exam Domain Weights

Domain                                     Weight   Focus
Design infrastructure solutions            30-35%   Compute (VM/AKS/App Service/Functions)
                                                     Networking (hub-spoke, Front Door, VPN)
                                                     Security (Key Vault, Private Endpoints)
Design identity, governance & monitoring   25-30%   Hybrid identity, Conditional Access, PIM
                                                     Management Groups, Azure Policy, tagging
                                                     Azure Monitor, App Insights, Log Analytics
Design data storage solutions              25-30%   SQL DB vs MI vs VM, Cosmos DB design
                                                     Blob tiers, redundancy, Key Vault
                                                     Synapse / Fabric for analytics
Design business continuity solutions       10-15%   RTO/RPO, AZ vs multi-region, ASR
                                                     Azure Backup, immutable vault, PITR

Compute Decision Tree

Need OS-level control / specific software?     → VM + Availability Zones
Containerised microservices / complex scaling? → AKS
Web/API managed PaaS (.NET/Java/Node/Python)?  → App Service
Event-driven, short burst, unknown traffic?    → Azure Functions
Stateful orchestration (long workflow)?        → Durable Functions / Logic Apps
GPU workloads (AI/ML training, rendering)?     → N-series VMs
Burst compute (CI runners, batch)?             → Spot VMs or Batch
Virtual desktop for remote workers?            → Azure Virtual Desktop

SLA achieved by:
Single VM + Premium SSD:  99.9%
Availability Set (2+ VMs): 99.95%
Availability Zones (2+ AZs): 99.99%
Multi-region active-active: 99.999%

Storage Decision Matrix

Use case                              → Service
Blobs (unstructured: media, docs)     → Blob Storage (Hot/Cool/Archive)
VM Disks                              → Managed Disks (Premium SSD for prod)
Shared file system (SMB/NFS)          → Azure Files
Hybrid file server caching            → Azure File Sync
Relational OLTP (managed)             → Azure SQL Database
SQL Server features (SQL Agent, etc.) → Azure SQL Managed Instance
Full SQL Server control               → SQL Server on Azure VM
NoSQL document / JSON                 → Azure Cosmos DB (SQL API)
Global multi-region, multi-write      → Azure Cosmos DB
Data warehouse / OLAP                 → Azure Synapse Analytics / Fabric
Enterprise message queue              → Azure Service Bus
Event streaming (IoT, telemetry)      → Azure Event Hubs
Session cache, query cache            → Azure Cache for Redis
Graph data                            → Cosmos DB (Gremlin API)

Networking Quick Reference

Topology:           Hub-Spoke (most enterprises) or Azure Virtual WAN (large scale)
On-prem private:    ExpressRoute (dedicated, consistent) preferred over VPN
On-prem encrypted:  VPN Gateway (encrypted over internet, simpler, cheaper)
Global HTTP/HTTPS:  Azure Front Door (anycast, WAF, CDN, private link origins)
Global any protocol: Azure Traffic Manager (DNS-based, any protocol)
Regional HTTP:      Application Gateway (L7, WAF, SSL termination, URL routing)
Regional TCP/UDP:   Azure Load Balancer Standard (L4, zone-redundant)
Private PaaS:       Private Endpoint + Private DNS Zone (production standard)
Admin access:       Azure Bastion (no public IP on VMs, browser-based RDP/SSH)
Perimeter firewall: Azure Firewall Premium (IDPS, TLS inspection, centralised)
DDoS:               DDoS Network Protection (per-VNet for public-facing workloads)

Business Continuity Quick Reference

RTO/RPO targets → design pattern:
Hours/Hours:     Azure Backup + ASR warm standby (passive failover)
Minutes/Minutes: Auto-failover group + Traffic Manager / Front Door failover
Near-zero/zero:  Active-active multi-region (Cosmos DB multi-write, Front Door)

SQL DR:
Single region: Business Critical (3 replicas, AZ) — 99.995% SLA
Multi-region:  Auto-failover group → automatic DNS failover
               RPO: < 5 seconds, RTO: < 30 seconds

VM DR:
Azure Site Recovery: replicate VMs to secondary region
Recovery Plans: orchestrate failover order (DC first, then app, then DB)
Test failover: validate quarterly without impacting production

Backup essentials:
Soft delete: 14 days recovery after accidental deletion
Immutable vault (locked): ransomware protection (cannot be disabled)
Cross-region restore: restore backup in secondary region for DR validation
PITR (SQL): restore to any second in the retention window

Well-Architected Framework Pillars Summary

Pillar           Key services / patterns
Reliability      AZs, multi-region, auto-failover, health probes, retry+circuit breaker
Security         Zero Trust, Private Endpoints, Key Vault, Managed Identity, WAF
Cost             Reserved Instances, right-sizing, lifecycle tiers, PaaS over IaaS
Operational Exc. IaC (Bicep), CI/CD, Azure Monitor, runbooks, deployment slots
Performance      Autoscale, CDN (Front Door), Redis cache, read replicas, AKS HPA

Top 10 Tips

  1. AZ-305 is a DESIGN exam, not a configuration exam — every question presents a business scenario asking you to RECOMMEND, COMPARE, or EVALUATE. The key skill is justifying WHY one service fits better than another — not knowing every configuration option.

  2. Infrastructure is 30–35% of the exam — the largest domain. Master: compute service selection (VM vs App Service vs AKS vs Functions), hub-spoke networking, Private Endpoints, Key Vault, and Azure Front Door vs Traffic Manager.

  3. Always anchor decisions in the Well-Architected Framework — every design choice has a WAF justification. "Why Private Endpoints?" → Security pillar (defence in depth). "Why Reserved Instances?" → Cost pillar. love WAF-framed answers.

  4. Private Endpoints are the production networking standard — any PaaS service (SQL, Storage, Key Vault, App Service) in production should have a Private Endpoint and disabled public access. Service Endpoints are insufficient for most enterprise requirements.

  5. Managed Identity eliminates credential management — any Azure resource authenticating to another Azure service should use Managed Identity. No secrets in code, no rotation risk, no leakage. Always the first recommendation for any "how do you authenticate" question.

  6. Hub-Spoke topology with Azure Firewall — the standard enterprise network architecture. Hub contains shared services (Firewall, VPN/ExpressRoute GW, Bastion). Spokes are workload VNets peered to hub. All spoke-to-spoke traffic inspected via hub Azure Firewall.

  7. RTO and RPO drive the HA design — before answering any HA/DR question, establish the RTO and RPO requirements. RTO/RPO in hours → warm standby + ASR. Minutes → auto-failover groups + Traffic Manager. Near-zero → active-active multi-region with Cosmos DB.

  8. SQL Database vs SQL Managed Instance — the most commonly confused SQL decision. SQL Database = most managed, best for greenfield. SQL Managed Instance = when you need SQL Agent, cross-database queries, Service Broker, or CLR. Know this boundary cold.

  9. Azure Front Door vs Traffic Manager — Front Door is a reverse proxy (HTTP/HTTPS, WAF, CDN, anycast, SSL offload). Traffic Manager is DNS-based routing (any protocol, no proxy, no WAF). Global web apps → Front Door. Non-HTTP global routing → Traffic Manager.

  10. The Cloud Adoption Framework provides the governance story — management group hierarchy, landing zones, Azure Policy at scale, and subscription design are all CAF concepts. For any "how do you govern 50 subscriptions" question, the answer starts with CAF landing zones.



Wednesday, April 29, 2026

Azure Integration Services Complete Guide

 

Azure Integration Services — Complete Guide

Logic Apps · Service Bus · API Management · Event Grid · Integration Patterns · Scenarios · Cheat Sheet


Table of Contents

  1. Azure Integration Services Overview
  2. Azure Logic Apps — Deep Dive
  3. Azure Service Bus — Deep Dive
  4. Azure API Management — Deep Dive
  5. Azure Event Grid
  6. Integration Patterns & Architecture
  7. Scenario-Based Questions
  8. Cheat Sheet — Quick Reference

1. Azure Integration Services Overview

What are Azure Integration Services and what problems do they solve?

Azure Integration Services is a suite of cloud services for connecting applications, data, and processes across cloud and on-premises environments.

Service Purpose
Azure Logic Apps Workflow orchestration — automate processes and integrate systems using a designer-based workflow engine
Azure Service Bus Enterprise message broker — reliable, ordered, durable message queuing and pub/sub
Azure API Management (APIM) API gateway — publish, secure, transform, and monitor APIs
Azure Event Grid Event routing — reactive, event-driven architecture at scale
Azure Event Hubs Big data streaming — high-throughput event ingestion (millions/sec)

Key positioning: Logic Apps = orchestration (do things in sequence). Service Bus = decoupling (reliable async messaging). APIM = API facade (secure and manage). Event Grid = events (react to things that happened). Event Hubs = telemetry streaming.


What is the difference between Logic Apps and Power Automate?

Logic Apps and Power Automate share the same underlying engine and connector library.

Logic Apps Power Automate
Audience Developers, IT, enterprise architects Business users, makers
Hosting Azure subscription Microsoft-managed SaaS
Pricing Pay-per-execution (Consumption) or App Service Plan (Standard) Per user/flow licence
VNET/private endpoints Yes (Standard and Premium) No
Source control / IaC ARM/Bicep templates, workflow JSON Solution packages
B2B EDI Yes (Integration Account) No
Local development Yes (VS Code, Standard tier) No

Tip: Same engine, different audience and infrastructure control. Enterprise integration with VNET, IaC, and B2B = Logic Apps. Business user automation = Power Automate.


What is the difference between Logic Apps Consumption and Standard plans?

Consumption Standard
Infrastructure Shared multi-tenant Dedicated App Service Plan
Pricing Pay per action execution Fixed plan cost
VNET integration No Yes
Private endpoints No Yes
Workflows per resource One Many
Local development No Yes (VS Code)
Stateless workflows No Yes (much faster)
Best for Low-volume, simple, quick deploy Enterprise production, high-volume

What is Azure Event Grid and how does it differ from Service Bus?

Event Grid Service Bus
Model Pub/sub event routing Message broker
Delivery guarantee At-least-once At-least-once with acknowledgement
Ordering Not guaranteed FIFO with sessions
Message retention 24h (default, max 7 days) Up to 14 days
Throughput 10M events/sec Up to 1000 msg/sec (Premium)
Use for Something happened — notify subscribers Message MUST be processed exactly once
Dead letter Yes Yes (DLQ)
Use Event Grid when:
→ Azure resource events (blob created, VM deallocated)
→ High-volume, low-latency event fan-out
→ Fire-and-forget is acceptable
→ Many subscribers need the same event

Use Service Bus when:
→ Message MUST be processed exactly once
→ Order of processing matters (sessions)
→ Consumer may be temporarily offline
→ Transactional messaging required
→ Complex routing with filter rules

2. Azure Logic Apps — Deep Dive

What are the key components of a Logic Apps workflow?

Component Description
Trigger Starts the workflow. Types: polling, push (webhook), recurrence, manual (HTTP)
Actions Steps after trigger. Each is a connector operation.
Connectors Wrappers around APIs. 400+ built-in. Custom connectors via OpenAPI.
Control flow Condition (if/else), Switch, For Each, Until, Scope
Variables Mutable state within a workflow run
Expressions @{body('action')}, @{utcNow()} — same syntax as Power Automate

What is the difference between stateful and stateless workflows in Logic Apps Standard?

Stateful workflow: each step's input/output persisted in Azure Storage. Full run history available. Can pause for external callbacks or approvals. Supports long-running workflows (days/weeks). Higher latency, higher cost.

Stateless workflow: data kept in memory only — not persisted. No run history. Cannot pause/resume. Maximum duration: minutes. Much faster (no storage I/O). Much lower cost. Best for high-volume synchronous processing.

Tip: Use stateless for high-volume, fast API transformations (hundreds per second). Use stateful for long-running processes, human-in-the-loop approvals, and workflows needing audit trails.


How does error handling work in Logic Apps?

Logic Apps uses the same Run After and Scope patterns as Power Automate:

Try-Catch-Finally pattern:

[Try Scope]
  → Main workflow steps

[Catch Scope]  ← Run After: Try scope → Failed
  → Alert via email/Teams
  → Log to Application Insights
  → Access error: @{result('Try_scope')[0]['error']['message']}
  → Access failed action: @{result('Try_scope')[0]['name']}

[Finally Scope]  ← Run After: Try + Catch → all states
  → Cleanup (always runs)

Retry policy per action:
→ None / Fixed / Exponential
→ Count: 1–90, Interval: configurable
→ Auto-retries on HTTP 408, 429, 5xx

What is an Integration Account in Logic Apps?

An Integration Account is an Azure resource providing B2B EDI integration capabilities.

Feature Description
Trading partners Define business partners and their identities
Agreements Message exchange agreements (send/receive settings)
Schemas XML schemas for validating/transforming EDI messages
Maps (XSLT) Transform message formats between partners
Certificates Message signing and encryption
EDI protocols AS2 (secure HTTP), X12 (US EDI), EDIFACT (international EDI)

Tip: Integration Account is the answer to any question about B2B EDI, trading partners, or AS2/X12/EDIFACT in Logic Apps .


How do you implement Logic Apps in a DevOps CI/CD pipeline?

Consumption plan (ARM templates):

# Export workflow as ARM template
# Store in Git
# Deploy via Azure CLI or DevOps ARM task
az deployment group create \
  --resource-group myRG \
  --template-file logicapp.json \
  --parameters @params.dev.json

Standard plan (workflow JSON — like Azure Functions):

# GitHub Actions deployment
- name: Deploy Logic App Standard
  uses: Azure/functions-action@v1
  with:
    app-name: my-logic-app-standard
    package: ./src/logicapp

Environment-specific config:

App Settings per environment (dev/test/prod):
→ Connection strings
→ API endpoints
→ Feature flags

Key Vault references for secrets:
@Microsoft.KeyVault(SecretUri=https://myvault.vault.azure.net/secrets/apikey)

What are managed connectors vs built-in connectors in Logic Apps Standard?

Managed connectors: run in Microsoft's shared cloud infrastructure. Make outbound calls to external services (Salesforce, SAP, ServiceNow). Subject to connector throttling limits. Same as Power Automate connectors.

Built-in connectors (Standard only): run inside the Logic App's own host process. Faster, no throttling limits. Include: HTTP, Service Bus, Event Hubs, Azure Blob, SQL, Dataverse, B2B operations. Use built-in over managed where available for better performance.


3. Azure Service Bus — Deep Dive

What is Azure Service Bus and what are its key components?

Component Description
Namespace Top-level container. Unique hostname: contoso.servicebus.windows.net
Queue Point-to-point. One sender, competing consumers. Each message processed once.
Topic Pub/sub. One publisher, multiple subscriptions each receiving a copy.
Subscription Named receiver on a topic. Has its own queue + filter rules.
Message Body (256KB Standard / 100MB Premium) + system + custom properties
Queue (point-to-point):
Producer → [Queue] → Consumer A (competing)
                   → Consumer B (competing)
→ ONE consumer processes each message

Topic/Subscription (pub/sub):
Publisher → [Topic] → [Sub A: filter Region='EMEA'] → Consumer A
                    → [Sub B: filter Priority='High'] → Consumer B
                    → [Sub C: no filter]              → Consumer C
→ EACH subscription gets its own independent copy

What are Service Bus tiers and which should you use for production?

Tier Queues Topics Max Msg Size VNET Best For
Basic ✓ ✗ 256KB ✗ Dev/test only
Standard ✓ ✓ 256KB ✗ Low-criticality workloads
Premium ✓ ✓ 100MB ✓ Enterprise production

Premium features: dedicated capacity units, geo-disaster recovery, VNET/private endpoints, predictable performance, availability zones.

Warning: Always use Premium for enterprise production — dedicated resources, VNET integration, and predictable latency. Standard has noisy neighbour risk and no network isolation.


What is the Dead Letter Queue (DLQ) and when are messages sent to it?

The DLQ is a sub-queue storing messages that cannot be processed. Every queue and subscription has its own DLQ.

Messages are dead-lettered when:

  1. Max delivery count exceeded — consumer abandons (nacks) message more than MaxDeliveryCount times (default: 10)
  2. TTL expired — message not consumed before Time-To-Live expires (if dead-lettering on expiry enabled)
  3. Subscription filter error — filter expression throws an exception
  4. Consumer explicitly dead-letters — calls deadLetterAsync() for unprocessable messages
DLQ message properties:
DeadLetterReason            → WHY it was dead-lettered
DeadLetterErrorDescription  → Detailed error message
EnqueuedTimeUtc             → When original message was sent
DeliveryCount               → How many times delivery was attempted

DLQ path:
Queue: myqueue/$DeadLetterQueue
Subscription: mytopic/mysubscription/$DeadLetterQueue

Critical: An overflowing DLQ means data loss. Always monitor DLQ counts with Azure Monitor alerts and have a process for reviewing, resubmitting, or archiving dead-lettered messages.


What are Sessions in Service Bus and when do you use them?

Sessions enable FIFO ordered processing of related messages. A session groups messages by SessionId — all messages with the same SessionId are processed in order by the same consumer instance.

Without sessions (no ordering guarantee):
Producer sends: Order-123-Created, Order-123-Paid, Order-123-Shipped
3 competing consumers → may process Shipped before Paid → wrong state

With sessions (SessionId = "Order-123"):
→ All messages with SessionId="Order-123" locked to ONE consumer
→ Processed in order: Created → Paid → Shipped
→ Other sessions (Order-456, Order-789) processed in parallel by other consumers
→ Scale: number of concurrent sessions = throughput

Enable sessions on queue/subscription:
RequiresSession = true (must be set at creation time)

Send with session:
message.SessionId = orderId;

Receive with session:
var session = await receiver.AcceptNextSessionAsync();

Tip: Sessions are the answer to "how do you guarantee message ordering in Service Bus." Without sessions, ordering is not guaranteed even with a single consumer.


What is the difference between peek-lock and receive-and-delete?

Peek-Lock (recommended):

  1. Consumer receives message — it is locked (invisible to others) for lock duration
  2. Consumer processes and calls Complete() → deleted from queue
  3. Or calls Abandon() → released back to queue for retry
  4. Or calls DeadLetter() → moved to DLQ
  5. If consumer crashes — lock expires, message re-queues automatically
  6. Guaranteed at-least-once delivery

Receive-and-Delete:

  1. Message deleted immediately on receive
  2. If consumer crashes after receive but before processing → message is permanently lost
  3. Use only for non-critical, idempotent scenarios (metrics, logging)

Warning: Always use Peek-Lock for business-critical messages. Receive-and-Delete risks data loss if the consumer fails between receiving and completing processing.


What is duplicate detection in Service Bus?

Duplicate detection allows Service Bus to discard messages with a previously seen MessageId within a configurable time window (1 min – 7 days).

// Enable at queue/topic creation:
new CreateQueueOptions("myqueue") {
  RequiresDuplicateDetection = true,
  DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(10)
};

// Set MessageId on the sender side:
var message = new ServiceBusMessage(body) {
  MessageId = $"{orderId}-{timestamp}"
};

Use when producers may retry sending on network failure — prevents double-processing of the same business event.


4. Azure API Management — Deep Dive

What is Azure API Management and what problem does it solve?

Azure API Management (APIM) is a fully managed API gateway between API consumers (clients) and API backends.

Core capabilities:

Capability Description
Security OAuth 2.0, JWT validation, subscription keys, client certificates, IP filtering
Rate limiting Rate limit and quota per subscription, IP, or custom key
Transformation Modify requests/responses without touching backend code
Versioning Manage multiple API versions, route to different backends
Developer portal Self-service API documentation and subscription management
Caching Cache responses to reduce backend load
Analytics Request logs, metrics, tracing via Azure Monitor + Application Insights

Key value: Decouple API consumers from backends. Backend can change without consumers knowing — APIM handles the translation.


What are APIM policies and what are the most important ones to know?

Policies are XML-based rules applied in four sections: inbound, backend, outbound, on-error.

<policies>
  <inbound>
    <!-- Validate JWT (Entra ID) -->
    <validate-jwt header-name="Authorization" failed-validation-httpcode="401">
      <openid-config url="https://login.microsoftonline.com/{tenantId}/v2.0/.well-known/openid-configuration"/>
      <required-claims>
        <claim name="aud"><value>api://my-api-id</value></claim>
      </required-claims>
    </validate-jwt>

    <!-- Rate limit per subscription: 100 calls/60s -->
    <rate-limit-by-key calls="100" renewal-period="60"
      counter-key="@(context.Subscription.Id)"/>

    <!-- Add internal key to backend request -->
    <set-header name="X-Internal-Key" exists-action="override">
      <value>{{internal-api-key-named-value}}</value>
    </set-header>

    <!-- Route to different backend based on header -->
    <choose>
      <when condition="@(context.Request.Headers.GetValueOrDefault('X-Version','v1') == 'v2')">
        <set-backend-service base-url="https://v2.api.backend.com"/>
      </when>
      <otherwise>
        <set-backend-service base-url="https://v1.api.backend.com"/>
      </otherwise>
    </choose>
  </inbound>

  <outbound>
    <!-- Remove internal header from response -->
    <set-header name="X-Powered-By" exists-action="delete"/>
    <!-- Cache successful responses for 5 minutes -->
    <cache-store duration="300"/>
    <!-- Transform XML response to JSON -->
    <xml-to-json kind="direct" apply="always"/>
  </outbound>

  <on-error>
    <return-response>
      <set-status code="@((int)context.Response.StatusCode)" reason="@(context.Response.StatusReason)"/>
      <set-body>@("Error: " + context.LastError.Message)</set-body>
    </return-response>
  </on-error>
</policies>

What are APIM tiers?

Tier SLA VNET Multi-region Scale Units Best For
Developer None No No 1 Dev/test only
Basic 99.95% No No 2 Small, non-critical
Standard 99.95% No No 4 Medium volume
Premium 99.99% Yes Yes 31 Enterprise production
Consumption 99.95% No No Serverless Very low volume, serverless

Tip: Premium is the only tier with VNET integration and multi-region deployment. Required when backends are in private networks or when global availability is needed.


What are APIM Products, APIs, and Subscriptions?

API: a backend service exposed through APIM
  → Has operations: GET /orders, POST /orders, DELETE /orders/{id}
  → Has policies applied at API or operation level

Product: a bundle of one or more APIs
  → Controls access: who can subscribe
  → Applies shared rate limits and quotas
  → Types: Open (no approval needed) | Protected (subscription required)

Subscription: a consumer's access key to a Product
  → Primary and secondary keys (for key rotation without downtime)
  → Passed in header: Ocp-Apim-Subscription-Key: {key}
  → Can be scoped to: All APIs | Product | Single API

Example:
APIs: Orders, Inventory, Customers, Analytics

Products:
  "Developer Tier" → Orders API only, 10 calls/min, free
  "Standard Tier"  → Orders + Inventory, 100 calls/min
  "Enterprise"     → All APIs, 1000 calls/min, SLA guaranteed

Consumer A subscribes to "Standard Tier":
→ Gets subscription key
→ Can call Orders and Inventory up to 100 calls/min
→ Cannot call Customers or Analytics

How do you implement API versioning in APIM?

Three versioning schemes:

Scheme URL Format Example
URL path /v{version}/resource /v1/orders, /v2/orders
Query string /resource?api-version={ver} /orders?api-version=2024-01-01
Header Api-Version: {version} Header: Api-Version: 2024-01-01

Each version can point to a different backend, have different policies, and be independently documented. A version set groups all versions together in the developer portal.

Tip: Always create a version set when deploying v1. Retrofitting versioning to an existing API with consumers is painful and disruptive.


What are Named Values in APIM and why are they important?

Named Values (formerly Properties) are key-value pairs stored in APIM and referenced in policies using {{name}} syntax.

<!-- Instead of hardcoding: -->
<set-header name="X-API-Key"><value>abc123supersecret</value></set-header>

<!-- Use Named Value: -->
<set-header name="X-API-Key"><value>{{backend-api-key}}</value></set-header>

Types:

  • Plain: static string value
  • Secret: encrypted, not visible after saving
  • Key Vault reference: value retrieved from Azure Key Vault at runtime

Best practice: Always use Named Values (preferably Key Vault-backed) for secrets and environment-specific values in APIM policies. Never hardcode secrets in policy XML.


5. Azure Event Grid

What is Azure Event Grid and what are its key components?

Event Grid is a fully managed event routing service for building reactive, event-driven architectures.

Component Description
Event source What emits events: Azure resources (Blob Storage, Resource Groups, Service Bus) or custom apps
Topic Endpoint where events are sent. System topics (Azure resources) or custom topics
Event subscription Maps a topic to an event handler with optional filter rules
Event handler What processes the event: Azure Functions, Logic Apps, Event Hubs, Service Bus, Webhooks
Azure Blob Storage (event source)
  → BlobCreated event published to System Topic
  → Event Grid routes to:
    Subscription 1 (filter: blobType=image) → Azure Function (resize image)
    Subscription 2 (no filter) → Logic App (archive to cold storage)
    Subscription 3 (filter: container=reports) → Power Automate (notify team)

When should you use Event Grid vs Event Hubs vs Service Bus?

Event Grid:
→ Discrete events (something happened)
→ Azure resource events (blob created, VM stopped)
→ Low volume, reactive architecture
→ Fan-out to many subscribers
→ Events expire after 24h–7 days

Event Hubs:
→ High-throughput streaming (millions/sec)
→ Time-series data, telemetry, logs
→ Replay capability (retention up to 90 days)
→ Big data pipelines (Spark, Stream Analytics)

Service Bus:
→ Reliable transactional messaging
→ Message must be processed exactly once
→ Order matters (sessions)
→ Consumer may be offline
→ Complex routing with business rules

6. Integration Patterns & Architecture

What is the Competing Consumers pattern?

Multiple consumer instances process messages from a single queue concurrently — scaling throughput horizontally. Each message processed by exactly one consumer.

Service Bus Queue with 3 consumers:
Producer → [Queue: 1000 messages]
  Consumer 1 (Azure Function instance) ← picks up messages
  Consumer 2 (Azure Function instance) ← picks up messages
  Consumer 3 (Azure Function instance) ← picks up messages

→ Each message processed by EXACTLY ONE consumer
→ Scale out by adding consumers
→ Azure Functions + Service Bus trigger auto-scales based on queue depth

What is the Saga pattern and how do you implement it?

The Saga pattern manages long-running distributed transactions without a central transaction coordinator. Each step publishes an event; compensating transactions undo completed steps if a later step fails.

Order Processing Saga — Orchestration (Logic App):

Step 1: Reserve Inventory API
  → Success: continue
  → Failure: STOP (nothing to compensate)

Step 2: Charge Payment API
  → Success: continue
  → Failure: call Inventory API to RELEASE reservation (compensate Step 1)

Step 3: Create Shipment API
  → Success: Saga complete
  → Failure: call Payment API to REFUND (compensate Step 2)
           + call Inventory API to RELEASE (compensate Step 1)

Choreography (Service Bus Topics):
  Each service subscribes to its trigger event
  Publishes result event → triggers next service
  Compensating events flow in reverse on failure
  No central orchestrator — fully decoupled

What is the Claim Check pattern?

Offloads large message payloads to external storage and sends only a reference in the Service Bus message.

Problem: Message payload = 5MB → exceeds 256KB Service Bus limit

Solution:
Producer:
  1. Upload full payload to Azure Blob Storage
  2. Get SAS URL (time-limited access token)
  3. Send small message: { "claimCheck": "{sasUrl}", "type": "OrderCreated" }

Consumer:
  1. Receive small message from Service Bus
  2. Download full payload from Blob using claimCheck URL
  3. Process the full payload
  4. Delete the blob after successful processing

How do Logic Apps, Service Bus, and APIM work together in enterprise integration?

External systems / Trading partners / Mobile apps
        ↓ HTTPS
[APIM] ← API Gateway (North-South traffic)
  → Authenticate: validate JWT/OAuth/mTLS
  → Rate limit external callers
  → Route to correct backend version
  → Transform: REST→SOAP, JSON→XML
        ↓
[Logic Apps] ← Orchestration layer
  → Receives HTTP request from APIM
  → Calls multiple backend services (SAP, D365, SQL)
  → Handles retry, error handling, compensation
  → Sends responses back and notifications
        ↓
[Service Bus] ← Async decoupling layer (East-West traffic)
  → Decouples Logic App from slow backend systems
  → Reliable delivery to downstream consumers
  → Topics/subscriptions fan out to multiple consumers
        ↓
Backend services (SAP, Dynamics 365, SQL, Custom APIs)

Design principle:
APIM    = North-South gateway (external ↔ internal boundary)
Service Bus = East-West bus (internal service ↔ service decoupling)
Logic Apps  = Orchestration across both layers

What is the Throttling / Rate Limiting pattern in APIM?

<!-- Rate limit per subscriber: 100 calls per 60 seconds -->
<rate-limit-by-key calls="100" renewal-period="60"
  counter-key="@(context.Subscription.Id)"
  increment-condition="@(context.Response.StatusCode >= 200
    and context.Response.StatusCode < 300)"/>

<!-- Rate limit per IP address -->
<rate-limit-by-key calls="50" renewal-period="60"
  counter-key="@(context.Request.IpAddress)"/>

<!-- Weekly quota (business tier limit) -->
<quota-by-key calls="50000" bandwidth="102400"
  renewal-period="604800"
  counter-key="@(context.Subscription.Id)"/>

<!-- Spike arrest: max 10 calls/second to protect backend -->
<rate-limit calls="10" renewal-period="1"/>

When limit exceeded:

  • Returns HTTP 429 Too Many Requests
  • Include Retry-After header
  • Custom error body via policy

Tip: Implement both rate-limit (short window, protect from spikes) and quota (long window, enforce business tier limits) for complete throttling strategy.


7. Scenario-Based Questions

Scenario: Design a reliable order processing system using Service Bus for 10,000 orders/hour.

  1. Service Bus Premium namespace: dedicated capacity, ~1000 msg/sec throughput, VNET integration
  2. Topic: orders with subscriptions:
    • inventory-sub: filter OrderType = 'Physical'
    • payment-sub: no filter (all orders), sessions enabled (SessionId = OrderId)
    • analytics-sub: no filter (all orders)
  3. Azure Functions consumers with Service Bus trigger: KEDA-based auto-scaling
  4. Dead Letter Queue monitoring: Azure Monitor alert when DLQ count > 0. Logic App notifies ops team.
  5. Duplicate detection: MessageId = OrderId + SubmissionTimestamp — prevents double-processing on producer retry
  6. Geo-Disaster Recovery: paired secondary namespace in secondary region. Failover RTO < 1 minute.
  7. Message TTL: 24h — orders not processed in 24h → DLQ alert for manual review

Scenario: A backend API averages 3 second responses. How do you use APIM to improve consumer experience?

  1. Response caching for stable reference data (product catalogue, lookup tables):
    <cache-lookup vary-by-developer="false">  <vary-by-header>Accept</vary-by-header></cache-lookup><!-- In outbound: --><cache-store duration="300"/>
    
  2. Circuit breaker pattern: on repeated backend failures, return cached last-good response or a meaningful error:
    <retry condition="@(context.Response.StatusCode >= 500)"  count="3" interval="2" first-fast-retry="true"/>
    
  3. Async pattern for operations > 1s:
    • APIM accepts request → sends to Service Bus → returns 202 Accepted + jobId
    • Backend processes async → stores result
    • Consumer polls GET /jobs/{jobId} for status
  4. Mock response for dev/test environments — no backend call
  5. Backend timeout policy: set explicit timeout so slow responses don't exhaust APIM threads
  6. Backend load balancing: configure multiple backend pool members — APIM round-robins or health-checks

Scenario: How do you expose an on-premises SAP API securely to external partners via APIM?

  1. APIM Premium with Internal VNET mode: APIM deployed inside a VNET. SAP reachable via ExpressRoute/VPN into the same VNET.
  2. Application Gateway in front of APIM: AG provides public endpoint, WAF, SSL termination. Forwards to internal APIM only.
  3. Partner authentication: mutual TLS (client certificates) or OAuth 2.0 client credentials. APIM validates certificates against trusted CA store.
  4. Request transformation: APIM policy transforms REST JSON → SOAP for SAP. Partners never see SAP's native SOAP interface.
  5. Rate limiting: per-partner subscription limits prevent any partner overwhelming SAP.
  6. Schema validation: APIM validates request payloads at gateway — bad requests rejected before reaching SAP.
  7. Logging: all partner API calls → Azure Monitor + Application Insights for audit compliance.

Scenario: Design a Logic App that syncs orders from e-commerce to Dynamics 365 every 15 minutes with deduplication.

  1. Trigger: Recurrence — every 15 minutes
  2. Fetch new orders: HTTP GET ?modifiedAfter=@{addMinutes(utcNow(),-15)}
  3. Parse JSON: extract orders array
  4. For Each (concurrency 5): parallel processing of 5 orders at a time
    • Query D365 by external order ID → does it exist?
    • No: create new D365 record
    • Yes: compare modifiedOn → if changed, update
  5. Try-Catch per order: wrap each order in a Try scope. Catch: log failed orderId + error to Azure Table Storage. Continue to next order — don't fail entire run on one bad record.
  6. Summary notification: Teams message after loop: "Sync complete: X created, Y updated, Z failed. See log for details."
  7. Persist last sync timestamp: update a D365 config record with current timestamp for next run's filter query.

Scenario: How do you implement a pub/sub notification system where different teams receive different order events?

Architecture:
Order Service → publishes to Service Bus Topic: "order-events"

Subscriptions with SQL filter rules:
inventory-team-sub:
  Filter: OrderStatus = 'Confirmed' OR OrderStatus = 'Cancelled'
  Action: Set RouteTo = 'inventory-queue'

finance-team-sub:
  Filter: OrderTotal > 1000 AND PaymentStatus = 'Charged'

shipping-team-sub:
  Filter: OrderStatus = 'ReadyToShip' AND DeliveryType = 'Express'

analytics-sub:
  No filter — receives ALL events for reporting

Implementation:
Order service sends with properties:
message.ApplicationProperties["OrderStatus"] = "Confirmed";
message.ApplicationProperties["OrderTotal"] = 1500.00;
message.ApplicationProperties["DeliveryType"] = "Express";

Each team's consumer only receives events matching their filter.
Teams can be added/removed without changing the producer.

8. Cheat Sheet — Quick Reference

Service Selection Guide

Need to...                              → Use
Orchestrate a multi-step process        → Logic Apps
Decouple services reliably              → Service Bus Queue
Fan out events to multiple consumers    → Service Bus Topic OR Event Grid
React to Azure resource events          → Event Grid
Ingest millions of telemetry events/sec → Event Hubs
Secure and manage APIs                  → API Management
Transform request/response format       → APIM policy
Rate limit API callers                  → APIM rate-limit policy
Guarantee message order                 → Service Bus + Sessions
Handle large payloads (>256KB)          → Claim Check pattern + Blob Storage
B2B EDI (AS2, X12, EDIFACT)            → Logic Apps + Integration Account

Service Bus Quick Reference

Namespace tiers: Basic (queues only) | Standard | Premium (enterprise)
Max message size: 256KB (Standard) | 100MB (Premium)
Message retention: up to 14 days
Max delivery count: default 10 (configurable)

Queue (point-to-point):
→ Competing consumers
→ Each message processed once
→ Enable sessions for FIFO ordering

Topic (pub/sub):
→ Multiple subscriptions
→ SQL filter rules per subscription
→ Each subscription gets independent copy

Message receive modes:
Peek-Lock: safe, acknowledged, retryable    ← always use for business data
Receive-Delete: immediate delete, risk loss ← only for non-critical

DLQ: every queue/subscription has one
Monitor: alert when DLQ count > 0
Path: myqueue/$DeadLetterQueue

APIM Policy Reference

<!-- JWT validation -->
<validate-jwt header-name="Authorization" failed-validation-httpcode="401">
  <openid-config url="https://login.microsoftonline.com/{tid}/v2.0/.well-known/openid-configuration"/>
</validate-jwt>

<!-- Rate limit per subscription -->
<rate-limit-by-key calls="100" renewal-period="60"
  counter-key="@(context.Subscription.Id)"/>

<!-- Cache response -->
<cache-store duration="300"/>

<!-- Transform XML to JSON -->
<xml-to-json kind="direct" apply="always"/>

<!-- Set backend URL -->
<set-backend-service base-url="https://api.backend.com"/>

<!-- Add header -->
<set-header name="X-Key" exists-action="override">
  <value>{{named-value}}</value>
</set-header>

<!-- Remove response header -->
<set-header name="X-Powered-By" exists-action="delete"/>

<!-- Mock response -->
<mock-response status-code="200" content-type="application/json"/>

<!-- Return custom error -->
<return-response>
  <set-status code="400"/>
  <set-body>{"error": "Invalid request"}</set-body>
</return-response>

Logic Apps — Connectivity Modes

Consumption plan:
→ Shared infrastructure
→ Pay per action (~$0.000025/action)
→ No VNET
→ One workflow per resource
→ Good for: low-volume, quick start

Standard plan:
→ Dedicated App Service Plan
→ Fixed cost, predictable
→ VNET integration + private endpoints
→ Multiple workflows per resource
→ Stateless workflows (fast, no history)
→ Local development in VS Code
→ Good for: enterprise production

Top 10 Tips

  1. Logic Apps vs Power Automate — same engine, different infrastructure control. Enterprise = Logic Apps (VNET, IaC, B2B). Business users = Power Automate. Never say "they're the same thing."
  2. Standard vs Consumption — Standard is the enterprise choice (VNET, stateless, multi-workflow). Consumption for quick prototypes only. Know this before any architecture question.
  3. Service Bus sessions = FIFO — sessions are the ONLY way to guarantee message ordering. Without them, ordering is not guaranteed even with a single consumer.
  4. Peek-Lock, always — Receive-and-Delete risks message loss on consumer crash. Peek-Lock with Complete/Abandon is the correct pattern for any business-critical message.
  5. DLQ monitoring is non-negotiable — an overflowing DLQ is silent data loss. Azure Monitor alert on DLQ count > 0 is a standard architecture requirement.
  6. APIM Premium for VNET — it's the only tier with private network integration. If backends are on-premises or in a private VNET, you need Premium.
  7. Named Values for secrets in APIM policies — never hardcode API keys or connection strings in policy XML. Named Values (Key Vault-backed) are the correct approach.
  8. Products in APIM — how you bundle APIs and control consumer access tiers. Many candidates know APIs but miss Products as the access control layer.
  9. Integration Account for B2B EDI — AS2, X12, EDIFACT in Logic Apps requires an Integration Account. This is the expected answer for any B2B/trading partner question.
  10. APIM + App Gateway pattern — exposing APIM in Internal VNET mode behind an Application Gateway is the standard enterprise pattern for secure public API exposure with backend network isolation.


Thursday, October 23, 2025

Azure Cache for Redis CRUD (Create, Read, Update, Delete) operations

Azure Cache for Redis CRUD (Create, Read, Update, Delete) operations:

Azure Cache for Redis facilitates standard CRUD (Create, Read, Update, Delete) operations on data stored in memory. These operations are performed using Redis commands, which can be executed through various client libraries or directly via the Redis Console in the Azure portal.

1. Create (Set):
To create or add data to the cache, the SET command is typically used. This command associates a key with a value.
Code: 
    SET mykey "myvalue"

2. Read (Get):
To retrieve data from the cache, the GET command is used, specifying the key of the desired value.
Code:
    GET mykey

3. Update (Set/Incr/HSet):
Updating data can involve overwriting an existing value with SET, incrementing a numerical value with INCR (for integers), or modifying specific fields within a hash with HSET.
Code: 
    SET mykey "newvalue"  // Overwrite
    INCR counterkey      // Increment a numerical value
    HSET user:1 name "Alice" age 30 // Update fields in a hash

4. Delete (Del):
To remove data from the cache, the DEL command is used, specifying one or more keys to be deleted.
Code: 
    DEL mykey
    DEL key1 key2 key3

Data Types:
Redis supports various data types beyond simple strings, including hashes, lists, sets, and sorted sets, each with specific commands for performing CRUD-like operations on their respective structures. For example, LPUSH and RPUSH for lists, SADD for sets, and ZADD for sorted sets are used to add elements, while LPOP, RPOP, SREM, and ZREM are used to remove elements.

Python:
"""
pip install redis
py azure_redis_cache.py
Azure Redis Cache - Get and Set Methods
Simple example demonstrating connection and basic operations with Azure Redis Cache
"""

import redis
import json
from typing import Optional, Any

# Redis connection string
REDIS_CONNECTION_STRING = "myazurerediscache.redis.cache.windows.net:6380,password=password=,ssl=True,abortConnect=False"


class AzureRedisCache:
    """Azure Redis Cache client wrapper"""
   
    def __init__(self, connection_string: str):
        """
        Initialize Redis connection
       
        Args:
            connection_string: Redis connection string
        """
        # Parse connection string
        params = {}
        for param in connection_string.split(','):
            if '=' in param:
                key, value = param.split('=', 1)
                params[key.strip()] = value.strip()
            else:
                # First part is host:port
                host_port = param.split(':')
                params['host'] = host_port[0]
                params['port'] = int(host_port[1])
       
        # Create Redis client
        self.client = redis.StrictRedis(
            host=params.get('host'),
            port=params.get('port', 6380),
            password=params.get('password'),
            ssl=params.get('ssl', 'True').lower() == 'true',
            decode_responses=True
        )
       
        print(f"✓ Connected to Redis: {params.get('host')}")
   
    def set_value(self, key: str, value: Any, expiration: Optional[int] = None) -> bool:
        """
        Set a value in Redis cache
       
        Args:
            key: Cache key
            value: Value to store (will be JSON serialized if not a string)
            expiration: Optional expiration time in seconds
           
        Returns:
            True if successful, False otherwise
        """
        try:
            # Convert value to string if it's not already
            if not isinstance(value, str):
                value = json.dumps(value)
           
            if expiration:
                result = self.client.setex(key, expiration, value)
            else:
                result = self.client.set(key, value)
           
            print(f"✓ Set key '{key}' = '{value}'" + (f" (expires in {expiration}s)" if expiration else ""))
            return bool(result)
        except Exception as e:
            print(f"✗ Error setting key '{key}': {str(e)}")
            return False
   
    def get_value(self, key: str) -> Optional[Any]:
        """
        Get a value from Redis cache
       
        Args:
            key: Cache key
           
        Returns:
            Value if found, None otherwise
        """
        try:
            value = self.client.get(key)
            if value is None:
                print(f"✗ Key '{key}' not found")
                return None
           
            # Try to parse as JSON, otherwise return as string
            try:
                value = json.loads(value)
            except (json.JSONDecodeError, TypeError):
                pass
           
            print(f"✓ Get key '{key}' = '{value}'")
            return value
        except Exception as e:
            print(f"✗ Error getting key '{key}': {str(e)}")
            return None
   
    def delete_key(self, key: str) -> bool:
        """
        Delete a key from Redis cache
       
        Args:
            key: Cache key to delete
           
        Returns:
            True if key was deleted, False otherwise
        """
        try:
            result = self.client.delete(key)
            if result:
                print(f"✓ Deleted key '{key}'")
            else:
                print(f"✗ Key '{key}' not found")
            return bool(result)
        except Exception as e:
            print(f"✗ Error deleting key '{key}': {str(e)}")
            return False
   
    def key_exists(self, key: str) -> bool:
        """
        Check if a key exists in Redis cache
       
        Args:
            key: Cache key
           
        Returns:
            True if key exists, False otherwise
        """
        try:
            exists = self.client.exists(key)
            print(f"✓ Key '{key}' exists: {bool(exists)}")
            return bool(exists)
        except Exception as e:
            print(f"✗ Error checking key '{key}': {str(e)}")
            return False
   
    def ping(self) -> bool:
        """
        Test connection to Redis
       
        Returns:
            True if connection is successful, False otherwise
        """
        try:
            result = self.client.ping()
            print(f"✓ Ping successful: {result}")
            return result
        except Exception as e:
            print(f"✗ Ping failed: {str(e)}")
            return False


def main():
    """Main function demonstrating Redis operations"""
   
    print("=" * 60)
    print("Azure Redis Cache - Get and Set Demo")
    print("=" * 60)
    print()
   
    # Initialize Redis client
    cache = AzureRedisCache(REDIS_CONNECTION_STRING)
   
    # Test connection
    print("\n--- Testing Connection ---")
    cache.ping()
   
    # Example 1: Set and get a simple string
    print("\n--- Example 1: Simple String ---")
    cache.set_value("greeting", "Hello, Azure Redis!")
    cache.get_value("greeting")
   
    # Example 2: Set and get a JSON object
    print("\n--- Example 2: JSON Object ---")
    user_data = {
        "name": "John Doe",
        "email": "john.doe@example.com",
        "age": 30
    }
    cache.set_value("user:1001", user_data)
    retrieved_user = cache.get_value("user:1001")
   
    # Example 3: Set with expiration (10 seconds)
    print("\n--- Example 3: Value with Expiration ---")
    cache.set_value("temp_token", "abc123xyz", expiration=10)
    cache.get_value("temp_token")
   
    # Example 4: Check if key exists
    print("\n--- Example 4: Check Key Existence ---")
    cache.key_exists("greeting")
    cache.key_exists("nonexistent_key")
   
    # Example 5: Delete a key
    print("\n--- Example 5: Delete Key ---")
    cache.delete_key("greeting")
    cache.get_value("greeting")  # Should return None
   
    print("\n" + "=" * 60)
    print("Demo completed!")
    print("=" * 60)


if __name__ == "__main__":
    main()


Output:































C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using StackExchange.Redis;
using Newtonsoft.Json;

namespace AzureRedisCacheDemo
{
    /// <summary>
    /// Azure Redis Cache client wrapper
    /// </summary>
    public class AzureRedisCache : IDisposable
    {
        private readonly ConnectionMultiplexer _connection;
        private readonly IDatabase _db;
        private readonly string _host;

        /// <summary>
        /// Initialize Redis connection
        /// </summary>
        /// <param name="connectionString">Redis connection string</param>
        public AzureRedisCache(string connectionString)
        {
            // Parse connection string
            var parameters = ParseConnectionString(connectionString);
            _host = parameters["host"];

            // Create configuration options
            var configOptions = new ConfigurationOptions
            {
                EndPoints = { $"{parameters["host"]}:{parameters["port"]}" },
                Password = parameters["password"],
                Ssl = parameters.GetValueOrDefault("ssl", "true").Equals("true", StringComparison.OrdinalIgnoreCase),
                AbortOnConnectFail = parameters.GetValueOrDefault("abortConnect", "false").Equals("true", StringComparison.OrdinalIgnoreCase)
            };

            // Create Redis connection
            _connection = ConnectionMultiplexer.Connect(configOptions);
            _db = _connection.GetDatabase();

            Console.WriteLine($"✓ Connected to Redis: {_host}");
        }

        /// <summary>
        /// Parse connection string into parameters
        /// </summary>
        private Dictionary<string, string> ParseConnectionString(string connectionString)
        {
            var parameters = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            var parts = connectionString.Split(',');

            foreach (var part in parts)
            {
                var trimmedPart = part.Trim();
                if (trimmedPart.Contains('='))
                {
                    var keyValue = trimmedPart.Split(new[] { '=' }, 2);
                    parameters[keyValue[0].Trim()] = keyValue[1].Trim();
                }
                else
                {
                    // First part is host:port
                    var hostPort = trimmedPart.Split(':');
                    parameters["host"] = hostPort[0];
                    parameters["port"] = hostPort.Length > 1 ? hostPort[1] : "6380";
                }
            }

            return parameters;
        }

        /// <summary>
        /// Set a value in Redis cache
        /// </summary>
        /// <param name="key">Cache key</param>
        /// <param name="value">Value to store</param>
        /// <param name="expiration">Optional expiration time in seconds</param>
        /// <returns>True if successful, false otherwise</returns>
        public bool SetValue(string key, object value, int? expiration = null)
        {
            try
            {
                // Convert value to string
                string stringValue = value is string str ? str : JsonConvert.SerializeObject(value);

                // Set with or without expiration
                bool result;
                if (expiration.HasValue)
                {
                    result = _db.StringSet(key, stringValue, TimeSpan.FromSeconds(expiration.Value));
                    Console.WriteLine($"✓ Set key '{key}' = '{stringValue}' (expires in {expiration}s)");
                }
                else
                {
                    result = _db.StringSet(key, stringValue);
                    Console.WriteLine($"✓ Set key '{key}' = '{stringValue}'");
                }

                return result;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"✗ Error setting key '{key}': {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// Get a value from Redis cache
        /// </summary>
        /// <param name="key">Cache key</param>
        /// <returns>Value if found, null otherwise</returns>
        public string GetValue(string key)
        {
            try
            {
                var value = _db.StringGet(key);
                if (value.IsNullOrEmpty)
                {
                    Console.WriteLine($"✗ Key '{key}' not found");
                    return null;
                }

                string stringValue = value.ToString();
                Console.WriteLine($"✓ Get key '{key}' = '{stringValue}'");
                return stringValue;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"✗ Error getting key '{key}': {ex.Message}");
                return null;
            }
        }

        /// <summary>
        /// Get a value and deserialize to type T
        /// </summary>
        public T GetValue<T>(string key)
        {
            try
            {
                var value = GetValue(key);
                if (value == null) return default(T);

                // Try to deserialize as JSON
                try
                {
                    return JsonConvert.DeserializeObject<T>(value);
                }
                catch
                {
                    // If deserialization fails, try to cast directly
                    return (T)Convert.ChangeType(value, typeof(T));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"✗ Error deserializing key '{key}': {ex.Message}");
                return default(T);
            }
        }

        /// <summary>
        /// Delete a key from Redis cache
        /// </summary>
        /// <param name="key">Cache key to delete</param>
        /// <returns>True if key was deleted, false otherwise</returns>
        public bool DeleteKey(string key)
        {
            try
            {
                bool result = _db.KeyDelete(key);
                if (result)
                {
                    Console.WriteLine($"✓ Deleted key '{key}'");
                }
                else
                {
                    Console.WriteLine($"✗ Key '{key}' not found");
                }
                return result;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"✗ Error deleting key '{key}': {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// Check if a key exists in Redis cache
        /// </summary>
        /// <param name="key">Cache key</param>
        /// <returns>True if key exists, false otherwise</returns>
        public bool KeyExists(string key)
        {
            try
            {
                bool exists = _db.KeyExists(key);
                Console.WriteLine($"✓ Key '{key}' exists: {exists}");
                return exists;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"✗ Error checking key '{key}': {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// Test connection to Redis
        /// </summary>
        /// <returns>True if connection is successful, false otherwise</returns>
        public bool Ping()
        {
            try
            {
                var endPoint = _connection.GetEndPoints().First();
                var server = _connection.GetServer(endPoint);
                var latency = server.Ping();
                Console.WriteLine($"✓ Ping successful: {latency.TotalMilliseconds}ms");
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"✗ Ping failed: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// Dispose connection
        /// </summary>
        public void Dispose()
        {
            _connection?.Dispose();
        }
    }

    /// <summary>
    /// User data model for demonstration
    /// </summary>
    public class UserData
    {
        public string Name { get; set; } = string.Empty;
        public string Email { get; set; } = string.Empty;
        public int Age { get; set; }
    }

    class Program
    {
        // Redis connection string
        const string REDIS_CONNECTION_STRING = "myazurerediscache.redis.cache.windows.net:6380,password=password=,ssl=True,abortConnect=False";

        static void Main(string[] args)
        {
            Console.WriteLine("============================================================");
            Console.WriteLine("Azure Redis Cache - Get and Set Demo (C#)");
            Console.WriteLine("============================================================");
            Console.WriteLine();

            using (var cache = new AzureRedisCache(REDIS_CONNECTION_STRING))
            {
                // Test connection
                Console.WriteLine("\n--- Testing Connection ---");
                cache.Ping();

                // Example 1: Set and get a simple string
                Console.WriteLine("\n--- Example 1: Simple String ---");
                cache.SetValue("greeting", "Hello, Azure Redis!");
                cache.GetValue("greeting");

                // Example 2: Set and get a JSON object
                Console.WriteLine("\n--- Example 2: JSON Object ---");
                var userData = new UserData
                {
                    Name = "John Doe",
                    Email = "john.doe@example.com",
                    Age = 30
                };
                cache.SetValue("user:1001", userData);
                var retrievedUser = cache.GetValue<UserData>("user:1001");
                if (retrievedUser != null)
                {
                    Console.WriteLine($"  Retrieved: {retrievedUser.Name}, {retrievedUser.Email}, Age: {retrievedUser.Age}");
                }

                // Example 3: Set with expiration (10 seconds)
                Console.WriteLine("\n--- Example 3: Value with Expiration ---");
                cache.SetValue("temp_token", "abc123xyz", expiration: 10);
                cache.GetValue("temp_token");

                // Example 4: Check if key exists
                Console.WriteLine("\n--- Example 4: Check Key Existence ---");
                cache.KeyExists("greeting");
                cache.KeyExists("nonexistent_key");

                // Example 5: Delete a key
                Console.WriteLine("\n--- Example 5: Delete Key ---");
                cache.DeleteKey("greeting");
                cache.GetValue("greeting"); // Should return null

                Console.WriteLine("\n============================================================");
                Console.WriteLine("Demo completed!");
                Console.WriteLine("============================================================");
            }

            Console.WriteLine("\nPress any key to exit...");
            Console.ReadKey();
        }
    }
}


Output:





































Featured Post

Scoping Microsoft Graph Mail Permissions to a Single Mailbox with Exchange Online RBAC for Applications

Automations that read reports from a shared mailbox or send notifications from a service mailbox usually run as a daemon application. They ...

Popular posts