Azure

Azure Cost Management

https://learn.microsoft.com/en-us/azure/cost-management-billing/

What is Azure Cost Management?

Azure Cost Management is a comprehensive suite of tools and practices for understanding, monitoring, and optimizing cloud spending in Microsoft Azure. Unlike traditional on-premises infrastructure with capital expenses (CapEx), Azure operates on an operational expense (OpEx) model where you pay for resources as you consume them.

When you manage costs in Azure, the platform:

  1. Tracks resource consumption through metered instances
  2. Generates usage records that calculate your bill
  3. Provides tools to analyze spending patterns
  4. Offers recommendations for optimization
  5. Enables budgets and alerts to control spending

Proactive cost management requires understanding cost drivers, implementing governance, and continuously optimizing resource usage.


Why Focus on Cost Management?

1. Cost Predictability

Without proper management, cloud costs can spiral unexpectedly. Cost management tools help forecast and control spending before it becomes problematic.

2. Resource Optimization

Many organizations over-provision resources "just in case." Cost management identifies underutilized resources and right-sizing opportunities, potentially reducing costs by 30-60%.

3. Business Accountability

Tracking costs by department, project, or application enables accurate chargeback/showback and ensures teams are accountable for their cloud consumption.

4. Strategic Planning

Understanding your cost patterns helps inform architectural decisions, migration strategies, and capacity planning for future growth.

5. Competitive Advantage

Organizations that master cloud cost management can reinvest savings into innovation, gaining competitive advantages over less efficient competitors.

6. Compliance and Governance

Cost management enforces spending policies, prevents unauthorized resource deployment, and maintains compliance with organizational budgets.


How Azure Billing Works

Basic Concept

Azure tracks resource consumption and generates bills based on multiple factors:

Resource Lifecycle:

Provision Resource → Meters Track Usage → Generate Usage Record → Calculate Bill

Example - Virtual Machine Cost Calculation:

VM Cost = (Compute Hours × Compute Rate) +
          (Storage GB × Storage Rate) +
          (Network Egress GB × Network Rate) +
          (License Costs if applicable)

Each resource type has specific meters that track:

  • Compute: CPU hours, memory allocation
  • Storage: GB stored, transactions, data retrieval
  • Networking: Data transfer, bandwidth usage
  • Database: DTUs, vCores, storage, backup retention

Important: Costs accumulate continuously while resources are running or allocated, not just when actively used.


Factors That Affect Costs in Azure

1. Resource Type and Configuration

Every Azure resource has unique pricing based on its type and settings.

Storage Account Example

Different configurations dramatically impact costs:

ConfigurationPrice ImpactUse Case
Blob Type: Block blobsStandard pricingGeneral purpose storage
Blob Type: Page blobsHigher pricingVM disks, random access
Performance Tier: StandardLower costRegular workloads
Performance Tier: Premium3-5x costHigh IOPS requirements
Access Tier: HotHigher storage, lower accessFrequently accessed data
Access Tier: CoolLower storage, higher accessInfrequently accessed (30+ days)
Access Tier: ArchiveLowest storage, highest accessRarely accessed (180+ days)
Redundancy: LRSBaseline costLocal redundancy only
Redundancy: GRS2x LRS costGeographic redundancy

Best Practice: Match storage tier to actual access patterns. Moving infrequently accessed data from Hot to Cool tier can reduce storage costs by 50%.

Virtual Machine Example

VM costs vary based on multiple factors:

Standard_D4s_v3 (4 vCPUs, 16 GB RAM) - East US
├── Compute: $0.192/hour
├── Storage: Premium SSD 128GB: $19.71/month
├── Network: Outbound data transfer: $0.087/GB (first 5GB free)
└── License: Windows Server: +$0.096/hour
    Total: ~$207/month (running 24/7)

Same VM with Reserved Instance (1-year):
└── Total: ~$124/month (40% savings)

Same VM with Reserved Instance (3-year):
└── Total: ~$89/month (57% savings)

Resource configuration choices made during provisioning have long-term cost implications.

2. Consumption Patterns

Azure's pay-as-you-go model means costs directly correlate with usage.

Pay-as-you-go vs Reserved Capacity

Scenario: Database hosting for consistent workload

Pay-as-you-go Pricing:
├── Azure SQL Database (4 vCores, Gen5)
├── Cost: $1.46/hour
└── Monthly Cost (24/7): $1,051

Reserved Capacity (1-year commitment):
├── Discount: 33% off pay-as-you-go
└── Monthly Cost: $704 (saving $347/month)

Reserved Capacity (3-year commitment):
├── Discount: 62% off pay-as-you-go
└── Monthly Cost: $399 (saving $652/month)

When to Use Reserved Instances:

  • Workloads running 24/7 for at least one year
  • Production databases and application servers
  • Predictable, steady-state resource needs
  • Can commit capacity in advance

When to Use Pay-as-you-go:

  • Development and testing environments
  • Unpredictable or spiky workloads
  • Short-term projects (< 6 months)
  • Need maximum flexibility

Auto-scaling Example

{
  "profiles": [
    {
      "name": "Business hours",
      "capacity": {
        "minimum": 2,
        "maximum": 10,
        "default": 2
      },
      "rules": [
        {
          "metricTrigger": {
            "metricName": "CpuPercentage",
            "operator": "GreaterThan",
            "threshold": 75,
            "timeWindow": "PT5M"
          },
          "scaleAction": {
            "direction": "Increase",
            "value": 2
          }
        },
        {
          "metricTrigger": {
            "metricName": "CpuPercentage",
            "operator": "LessThan",
            "threshold": 25,
            "timeWindow": "PT5M"
          },
          "scaleAction": {
            "direction": "Decrease",
            "value": 1
          }
        }
      ],
      "recurrence": {
        "frequency": "Week",
        "schedule": {
          "timeZone": "Pacific Standard Time",
          "days": ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"],
          "hours": [8],
          "minutes": [0]
        }
      }
    },
    {
      "name": "Off hours",
      "capacity": {
        "minimum": 1,
        "maximum": 2,
        "default": 1
      }
    }
  ]
}

Cost Impact:

  • Business hours (8 AM - 6 PM): 2-10 instances
  • Off hours: 1-2 instances
  • Potential savings: 40-60% compared to running 10 instances 24/7

3. Maintenance and Resource Hygiene

Orphaned and unused resources are a primary source of waste.

Common Orphaned Resources

Scenario: VM Deprovisioning

Original VM Deployment Creates:
├── Virtual Machine
├── OS Disk (Premium SSD 128GB): $19.71/month
├── Network Interface: Minimal cost
├── Public IP Address: $3.65/month
├── Network Security Group: Free
└── Virtual Network: Free (within limits)

After VM Deletion (if not properly cleaned):
├── OS Disk: Still charged $19.71/month ❌
├── Network Interface: Still exists ❌
├── Public IP Address: Still charged $3.65/month ❌
└── Orphaned snapshots: Additional charges ❌

Total wasted cost: $23.36/month per forgotten VM

Prevention Strategy:

az vm delete \
  --resource-group MyResourceGroup \
  --name MyVM \
  --yes

az disk delete --ids $(az disk list --resource-group MyResourceGroup --query "[?contains(name,'MyVM')].id" -o tsv)
az network nic delete --ids $(az network nic list --resource-group MyResourceGroup --query "[?contains(name,'MyVM')].id" -o tsv)
az network public-ip delete --ids $(az network public-ip list --resource-group MyResourceGroup --query "[?contains(name,'MyVM')].id" -o tsv)

4. Geography and Regional Pricing

Azure resources cost differently across regions due to local economic factors.

Regional Price Comparison

Example: Standard_D4s_v3 Virtual Machine (4 vCPUs, 16 GB RAM)

RegionHourly CostMonthly Cost (730 hrs)Difference from Cheapest
East US$0.192$140.16Baseline
West US$0.192$140.160%
North Europe$0.211$154.03+10%
West Europe$0.218$159.14+14%
Japan East$0.240$175.20+25%
Brazil South$0.282$205.86+47%
Australia East$0.253$184.69+32%

Storage Account - Hot Tier Comparison:

RegionFirst 50 TB/monthDifference
East US$0.0184/GBBaseline
West Europe$0.0202/GB+10%
Southeast Asia$0.0250/GB+36%

Strategic Regional Selection

Decision Framework:
├── Data Residency Requirements
│   └── Must store data in specific geography for compliance
├── User Location
│   └── Choose region closest to end users (latency < 50ms optimal)
├── Service Availability
│   └── Not all services available in all regions
├── Disaster Recovery
│   └── Pair primary region with appropriate secondary
└── Cost Optimization
    └── Select cheapest region meeting above requirements

Example Strategy:

Application: E-commerce platform
Primary Users: United States
Requirements: 
├── Low latency for users
├── Data sovereignty: US data must stay in US
├── High availability required
└── Cost optimization important

Recommended Architecture:
├── Primary Region: East US (lowest US cost)
├── Secondary Region: West US 2 (DR, same cost)
├── CDN: Azure Front Door (global)
└── Database Replicas: Read replicas in East US only
    (avoid cross-region replication costs)

Cost Savings vs Suboptimal Selection:
└── Avoided Brazil South: Saved 47% on compute
└── Avoided West Europe: Saved 14% on compute
└── Single region database: Saved ~$200/month on geo-replication

5. Network Traffic and Bandwidth

Data transfer is often overlooked but can become significant at scale.

Understanding Billing Zones

Azure organizes regions into billing zones for data transfer pricing:

Zone 1: North America, Europe, UK Zone 2: Australia, Asia Pacific, Middle East, Africa Zone 3: South America

Data Transfer Pricing Structure

Inbound Data Transfer (Ingress):
└── Free for all scenarios ✅

Outbound Data Transfer (Egress) - Monthly Tiers:
├── First 5 GB: Free
├── 5 GB - 10 TB: $0.087/GB (Zone 1)
├── 10 TB - 50 TB: $0.083/GB (Zone 1)
├── 50 TB - 150 TB: $0.070/GB (Zone 1)
└── 150 TB - 500 TB: $0.050/GB (Zone 1)

Cross-Zone Pricing (more expensive):
├── Zone 1 to Zone 2: $0.120/GB
└── Zone 1 to Zone 3: $0.150/GB

Data Transfer Within Azure:
├── Same Region: Free ✅
├── Same Zone (different regions): $0.02/GB
└── Different Zones: Regular egress rates

Network Cost Optimization Example

Scenario: Video streaming platform

Original Architecture (High Cost):
├── Web servers: East US
├── Database: West Europe (geo-replicated)
├── Object storage: Australia East
├── CDN: Not used
└── Monthly data egress: 100 TB

Cost Breakdown:
├── Database cross-region replication: 50 TB/month × $0.02 = $1,000
├── Application to database traffic: 30 TB/month × $0.02 = $600
├── Direct video streaming: 100 TB × $0.083 = $8,300
└── Total Network Cost: $9,900/month

Optimized Architecture (Low Cost):
├── Web servers: East US
├── Database: East US (local only)
├── Object storage: East US
├── CDN: Azure Front Door with caching
└── Monthly data egress: 100 TB (via CDN, discounted)

Cost Breakdown:
├── Database cross-region replication: Eliminated ✅
├── Application to database traffic: Free (same region) ✅
├── CDN egress: 100 TB × $0.067 (CDN discount) = $6,700
└── Total Network Cost: $6,700/month

Monthly Savings: $3,200 (32% reduction)

Best Practices:

  • Co-locate resources in the same region when possible
  • Use Azure CDN for content delivery
  • Implement caching to reduce origin traffic
  • Compress data before transfer
  • Use Azure ExpressRoute for consistent high-volume traffic

6. Subscription Type and Benefits

Different Azure subscription types include various benefits and allowances.

Subscription Comparison

Azure Free Tier:

Includes:
├── $200 credit for first 30 days
├── 12 months of popular services free:
│   ├── 750 hours B1s Linux VM
│   ├── 750 hours B1s Windows VM
│   ├── 5 GB blob storage
│   ├── 250 GB SQL Database
│   └── 15 GB outbound data transfer
└── 25+ always-free services:
    ├── 10 web, mobile, or API apps
    ├── 1 million Azure Functions executions
    └── 20 compute hours Azure Container Instances

Best for: Learning, prototyping, small projects

Pay-as-you-go:

Characteristics:
├── No upfront commitment
├── Pay only for what you use
├── Full pricing (no discounts)
└── Maximum flexibility

Best for: Small businesses, variable workloads, short-term projects

Enterprise Agreement (EA):

Benefits:
├── Volume discounts (10-40% typically)
├── Azure Monetary Commitment
├── Flexible payment options
├── Centralized billing
├── Reserved Instance discounts stackable
└── Access to Azure Dev/Test pricing

Best for: Large organizations, predictable annual spend >$100K

Dev/Test Subscriptions:

Discounts:
├── Windows VMs: Save ~40% (no Windows license fee)
├── SQL Server VMs: Save ~55% (no SQL license fee)
├── Azure SQL Database: Save ~55%
└── Other compute services: Various discounts

Requirements:
├── Must be used for non-production workloads only
├── Requires Visual Studio subscription
└── Subject to audit

Best for: Development, testing, staging environments

Maximizing Subscription Benefits

public class SubscriptionCostAnalyzer
{
    public decimal CalculatePotentialSavings(
        List<Resource> resources, 
        SubscriptionType currentType)
    {
        decimal currentCost = 0;
        decimal optimizedCost = 0;
        
        foreach (var resource in resources)
        {
            currentCost += GetResourceCost(resource, currentType);
            
            // Determine optimal subscription type for this resource
            var optimalType = GetOptimalSubscriptionType(resource);
            optimizedCost += GetResourceCost(resource, optimalType);
        }
        
        return currentCost - optimizedCost;
    }
    
    private SubscriptionType GetOptimalSubscriptionType(Resource resource)
    {
        if (resource.IsProduction && resource.RunsConstantly)
        {
            return SubscriptionType.ReservedInstance;
        }
        else if (resource.IsDevelopment || resource.IsTest)
        {
            return SubscriptionType.DevTest;
        }
        else if (resource.IsSpiky || resource.IsShortTerm)
        {
            return SubscriptionType.PayAsYouGo;
        }
        
        return SubscriptionType.PayAsYouGo;
    }
}

7. Azure Marketplace Costs

Third-party solutions from Azure Marketplace include both Azure infrastructure costs and vendor fees.

Understanding Marketplace Pricing

Example: Fortinet FortiGate Next-Generation Firewall

Marketplace Solution Cost Breakdown:
├── Azure Infrastructure:
│   ├── VM Compute: Standard_D4s_v3: $0.192/hour
│   ├── Storage: Premium SSD 128GB: $19.71/month
│   ├── Public IP: $3.65/month
│   └── Data Transfer: Variable based on usage
│
└── Vendor Software License:
    ├── FortiGate License: $0.35/hour
    └── Support & Updates: Included
    
Total Hourly Cost: $0.192 + $0.35 = $0.542/hour
Total Monthly Cost: ~$396/month

Compare to:
├── Building your own firewall: Lower cost, higher effort
├── Managed Azure Firewall: $1.25/hour (~$912/month)
└── Marketplace provides middle ground

Marketplace Cost Optimization

Bring Your Own License (BYOL):

Standard Marketplace SQL Server VM:
├── VM Compute: $0.192/hour
├── SQL Server License: $0.967/hour
└── Total: $1.159/hour = $846/month

With BYOL (if you already own SQL licenses):
├── VM Compute: $0.192/hour
├── SQL Server License: $0/hour (using existing license)
└── Total: $0.192/hour = $140/month

Savings: $706/month (83% reduction on this component)

Marketplace Vendor Checklist:

Before deploying Marketplace solutions:

  • Compare vendor pricing across multiple Marketplace vendors
  • Check if you have existing licenses that qualify for BYOL
  • Review Azure-native alternatives (may be cheaper)
  • Understand what's included in vendor pricing
  • Check for annual prepay discounts from vendor
  • Verify support SLAs and what's covered
  • Test with Azure Free Trial credits if available

Azure Pricing Tools

Azure Pricing Calculator

The Pricing Calculator helps estimate costs before deployment.

Practical Example: Estimating Application Cost

Scenario: Three-tier web application

Application Requirements:
├── Frontend: Static website
├── API Layer: .NET Core application
├── Database: SQL Server
├── Storage: Images and documents
└── Expected Traffic: 100K users/month

Pricing Calculator Inputs:

1. Azure App Service:
   ├── Tier: Premium V3 (P1v3)
   ├── Instances: 2 (for high availability)
   ├── Compute Hours: 730/month
   └── Estimated Cost: $200/month

2. Azure SQL Database:
   ├── Model: vCore-based (General Purpose)
   ├── Hardware: Gen5, 4 vCores
   ├── Storage: 256 GB
   ├── Backup: 7-day retention
   └── Estimated Cost: $730/month
   
3. Azure Blob Storage:
   ├── Performance: Standard
   ├── Redundancy: GRS
   ├── Data Stored: 500 GB
   ├── Monthly Transactions: 1M
   └── Estimated Cost: $25/month
   
4. Azure CDN:
   ├── Data Transfer: 1 TB/month
   └── Estimated Cost: $82/month
   
5. Application Insights:
   ├── Data Ingestion: 5 GB/month
   └── Estimated Cost: $11/month

Total Monthly Cost: $1,048/month
Annual Cost: $12,576/year

With Reserved Instances (3-year):
├── App Service: Save 38% = $124/month saved
├── SQL Database: Save 62% = $452/month saved
└── Total Savings: $576/month or $6,912/year

New Annual Cost: $5,664/year (55% savings)

Using the Calculator Effectively

Best Practices:
├── Start with production estimates, then add dev/test
├── Include disaster recovery costs
├── Factor in data egress for accurate network costs
├── Add 20% buffer for unexpected usage
├── Compare reserved vs pay-as-you-go scenarios
├── Export estimate for stakeholder review
└── Update estimate quarterly as requirements change

Common Mistakes to Avoid:
├── Forgetting to include backups and snapshots
├── Underestimating network egress
├── Not accounting for development environments
├── Ignoring managed service overhead costs
└── Assuming linear scaling of costs

Total Cost of Ownership (TCO) Calculator

The TCO Calculator compares on-premises infrastructure costs to Azure.

Comprehensive TCO Analysis

Scenario: Mid-sized company migration

Current On-Premises Infrastructure:

Hardware:
├── 20 physical servers (refreshed every 5 years)
├── Initial Hardware Cost: $500,000
├── Storage: 100 TB SAN: $150,000
├── Network Equipment: $50,000
└── Hardware Annual Depreciation: $140,000

Facility Costs:
├── Data Center Space: $24,000/year
├── Power & Cooling: $48,000/year
└── Physical Security: $12,000/year

IT Labor:
├── 3 Infrastructure Engineers: $300,000/year
├── 1 Database Administrator: $120,000/year
└── 0.5 Network Administrator: $60,000/year

Software Licenses:
├── Windows Server: $40,000/year
├── SQL Server: $80,000/year
├── Virtualization Platform: $30,000/year
└── Monitoring & Backup Tools: $25,000/year

Total Annual On-Premises Cost: $839,000

Over 5 Years: $4,195,000

Equivalent Azure Environment:

Compute (IaaS Equivalent):
├── 20 Standard_D4s_v3 VMs
├── Pay-as-you-go: $2,803/month × 12 = $33,636/year
├── 3-year Reserved: $1,780/month × 12 = $21,360/year

Migrated to PaaS:
├── 10 App Service Plans (P2v3): $292/month × 12 = $3,504/year
├── 5 Azure SQL Databases: $365/month × 12 = $4,380/year
├── 5 Function Apps: $14/month × 12 = $168/year

Storage:
├── 100 TB Premium Storage: $4,906/month × 12 = $58,872/year
├── Backup & Archive: $800/month × 12 = $9,600/year

Networking:
├── VPN Gateway: $263/month × 12 = $3,156/year
├── Load Balancer: $18/month × 12 = $216/year
├── Data Egress (5 TB/month): $435/month × 12 = $5,220/year

Management:
├── Azure Monitor & Log Analytics: $200/month × 12 = $2,400/year
├── Azure Backup: Included in storage costs

Licenses (Hybrid Benefit):
├── Windows Server: $0 (using Azure Hybrid Benefit)
├── SQL Server: $0 (using Azure Hybrid Benefit)

Labor Reduction:
├── 2 Infrastructure Engineers: $200,000/year (1 engineer eliminated)
├── 0.5 Database Administrator: $60,000/year (50% reduction)
├── 0.25 Network Administrator: $30,000/year (50% reduction)
└── New Azure Cloud Engineer: $140,000/year

Total Annual Azure Cost (PaaS): $318,876
Total Annual Labor Cost: $430,000

Total Annual Cost: $748,876

Over 5 Years: $3,744,380

Total 5-Year Savings: $450,620 (11% reduction)

Additional Benefits Not Quantified:
├── Improved disaster recovery capabilities
├── Better scalability for growth
├── Reduced time to market for new features
├── Enhanced security and compliance
├── No hardware refresh cycles
└── Global reach and lower latency for distributed users

TCO Calculator Inputs Checklist:

Hardware:

  • Server count and specifications
  • Storage capacity and type (SAN, NAS, DAS)
  • Network infrastructure
  • Hardware refresh cycle (typically 3-5 years)
  • Warranty and support costs

Software:

  • Operating system licenses
  • Database licenses
  • Virtualization platform
  • Backup and recovery software
  • Monitoring and management tools

Facilities:

  • Data center space costs or colocation fees
  • Power costs (including UPS)
  • Cooling costs
  • Physical security
  • Internet connectivity

Labor:

  • Infrastructure administration
  • Database administration
  • Network administration
  • Security management
  • Backup administration

Assumptions:

  • Server virtualization ratio
  • Storage utilization
  • Downtime costs
  • Migration costs (one-time)
  • Training costs (one-time)

Microsoft Cost Management Tool

Azure Cost Management provides comprehensive cost visibility and control.

Core Features

1. Cost Analysis

Visualize and analyze spending patterns across multiple dimensions.

Available Views:

Cost Analysis Dimensions:
├── Resource
├── Resource Group
├── Resource Type
├── Location (Region)
├── Service Name
├── Subscription
├── Tag
├── Publisher Type (First-party vs Marketplace)
└── Reservation (Reserved vs On-demand)

Time Periods:
├── Daily
├── Monthly
├── Custom date range
└── Accumulated (running total)

Grouping and Filtering:
├── Group by resource type to see which services cost most
├── Filter by tag to see project-specific costs
├── Compare time periods (month-over-month)
└── Export to Excel for offline analysis

Example Analysis Queries:

Query 1: Most Expensive Resources
└── Group by: Resource
└── Time: Last 30 days
└── Sort by: Cost descending
└── Result: Identifies top 10 cost drivers

Query 2: Cost Trend by Department
└── Group by: Tag (Department)
└── Time: Last 6 months
└── Chart: Line graph
└── Result: Shows departmental spending trends

Query 3: Unused Resources
└── Filter: Resource type = "Virtual Machine"
└── Metric: CPU utilization < 5%
└── Time: Last 7 days
└── Result: Candidate VMs for deletion or downsizing

Query 4: Storage Growth
└── Group by: Resource type = "Storage Account"
└── Metric: Capacity used
└── Time: Last 12 months
└── Result: Projects future storage needs

2. Budgets and Alerts

Set spending limits and receive notifications before exceeding them.

Budget Configuration Example:

{
  "budgetName": "Engineering-Team-Q1-2026",
  "amount": 50000,
  "timeGrain": "Monthly",
  "timePeriod": {
    "startDate": "2026-01-01",
    "endDate": "2026-03-31"
  },
  "category": "Cost",
  "filter": {
    "tags": {
      "Department": "Engineering",
      "Environment": "Production"
    }
  },
  "notifications": {
    "actual_80_percent": {
      "enabled": true,
      "operator": "GreaterThan",
      "threshold": 80,
      "contactEmails": [
        "[email protected]",
        "[email protected]"
      ],
      "contactRoles": [
        "Owner",
        "Contributor"
      ],
      "thresholdType": "Actual"
    },
    "actual_100_percent": {
      "enabled": true,
      "operator": "GreaterThan",
      "threshold": 100,
      "contactEmails": [
        "[email protected]",
        "[email protected]",
        "[email protected]"
      ],
      "contactGroups": [
        "/subscriptions/.../resourceGroups/.../providers/microsoft.insights/actionGroups/CriticalAlerts"
      ],
      "thresholdType": "Actual"
    },
    "forecasted_110_percent": {
      "enabled": true,
      "operator": "GreaterThan",
      "threshold":