EngineeringSolution ArchitectAzure Architecture

Session 05 - Azure Cost Optimization

Tổng quan

Cost optimization không phải cắt giảm chi phí bằng mọi giá - mà là tối đa hóa business value trên mỗi đồng chi phí. Đây là pillar thường bị bỏ qua cho đến khi bill tháng gây shock.

Compute Pricing - So sánh

Reserved Instances vs Pay-as-you-go vs Spot VMs

Tiêu chíPay-as-you-goReserved (1 năm)Reserved (3 năm)Spot VMs
Discount0% (baseline)~20-40%~40-60%~60-90%
CommitmentKhông1 năm3 nămKhông
Eviction riskKhôngKhôngKhôngCó (bị thu hồi bất kỳ lúc nào)
Phù hợp choDev/test, burstyProduction stableLong-term infraBatch, CI/CD, stateless
FlexibilityCao nhấtCó thể exchange/cancelCó thể exchangeCao
BillingPer secondUpfront hoặc monthlyUpfront hoặc monthlyPer second (giá thay đổi)

Ví dụ tiết kiệm (Standard_D4s_v5 - Southeast Asia)

ModelChi phí/tháng (ước tính)Tiết kiệm
Pay-as-you-go~$140Baseline
Reserved 1 năm~$9036%
Reserved 3 năm~$6057%
Spot VM~$20-4070-85%

Right-sizing với Azure Advisor

bash
# Xem right-sizing recommendations
az advisor recommendation list \
  --category Cost \
  --output table

# Xem chi tiết VM utilization
az monitor metrics list \
  --resource /subscriptions/{sub}/resourceGroups/{rg}/providers/Microsoft.Compute/virtualMachines/{vm} \
  --metric "Percentage CPU" \
  --interval PT1H \
  --start-time 2026-04-03T00:00:00Z \
  --end-time 2026-04-10T00:00:00Z \
  --output table

Right-sizing Decision Tree

Azure Cost Management - Playbook

Step 1: Tagging Strategy

Mọi resource bắt buộc phải có tags để phân bổ chi phí.

bash
# Mandatory tags
az tag create --name environment
az tag create --name cost-center
az tag create --name owner
az tag create --name project

# Áp dụng tags cho resource group
az group update \
  --name rg-ecommerce-prod \
  --tags \
    environment=production \
    cost-center=CC-1234 \
    owner=team-platform \
    project=ecommerce

Tag policy - enforce bằng Azure Policy:

bash
# Require tag on resource groups
az policy assignment create \
  --name require-cost-center-tag \
  --policy "/providers/Microsoft.Authorization/policyDefinitions/96670d01-0a4d-4649-9c89-2d3abc0a5025" \
  --params '{"tagName": {"value": "cost-center"}}' \
  --scope /subscriptions/{sub-id}

Step 2: Setup Budgets + Alerts

bash
# Tạo monthly budget
az consumption budget create \
  --budget-name budget-ecommerce-prod \
  --amount 5000 \
  --category Cost \
  --time-grain Monthly \
  --start-date 2026-04-01 \
  --end-date 2027-03-31 \
  --resource-groups rg-ecommerce-prod

# Thêm alert notifications
# 50%, 80%, 100%, 120% thresholds

Bicep - Budget với alerts:

bicep
resource budget 'Microsoft.Consumption/budgets@2023-11-01' = {
  name: 'budget-ecommerce-prod'
  properties: {
    category: 'Cost'
    amount: 5000
    timeGrain: 'Monthly'
    timePeriod: {
      startDate: '2026-04-01'
      endDate: '2027-03-31'
    }
    notifications: {
      alert50: {
        enabled: true
        operator: 'GreaterThanOrEqualTo'
        threshold: 50
        contactEmails: ['platform-team@company.com']
        thresholdType: 'Actual'
      }
      alert80: {
        enabled: true
        operator: 'GreaterThanOrEqualTo'
        threshold: 80
        contactEmails: ['platform-team@company.com', 'manager@company.com']
        thresholdType: 'Actual'
      }
      forecast100: {
        enabled: true
        operator: 'GreaterThanOrEqualTo'
        threshold: 100
        contactEmails: ['platform-team@company.com', 'manager@company.com']
        thresholdType: 'Forecasted'
      }
    }
  }
}

Step 3: Cost Review Cadence

Tần suấtHành độngAi thực hiện
Hàng ngàyCheck anomaly alertsOn-call engineer
Hàng tuầnReview Advisor recommendationsPlatform team
Hàng thángCost report by project/teamEngineering Manager
Hàng quýRI coverage review, right-sizingFinOps team

Dev/Test Pricing

bash
# Tạo subscription loại Dev/Test (discount đáng kể)
# Cần Visual Studio subscription
# Discount: Windows VMs chỉ tính Linux price, PaaS giảm giá

# Auto-shutdown cho dev VMs
az vm auto-shutdown \
  --resource-group rg-dev \
  --name vm-dev-01 \
  --time 1900 \
  --timezone "SE Asia Standard Time"

Dev/Test savings tiêu biểu:

ServiceProduction PriceDev/Test PriceSavings
Windows VM (D4s_v5)~$280/month~$140/month50%
Azure SQL (S3)~$150/month~$75/month50%
App Service (P1v3)~$100/month~$50/month50%

Serverless Cost Patterns

Azure Functions - Consumption Plan

Cost = Execution count x Price per execution
     + Execution time (GB-s) x Price per GB-s

Free grant per month:
  - 1 million executions
  - 400,000 GB-s
ScenarioMonthly CallsAvg DurationMemoryEstimated Cost
Light API500K200ms256MB~$0 (free tier)
Medium API5M500ms512MB~$15
Heavy processing50M1s1GB~$350
Comparison: App Service P1v3UnlimitedN/A8GB~$100 fixed

Rule of thumb: Serverless rẻ hơn khi traffic < 3M requests/month hoặc rất bursty. Ổn định > 10M requests/month thì App Service / Container Apps rẻ hơn.

Storage Tier Optimization

TierLatencyStorage Cost (per GB/month)Phù hợp
Premium< 1ms~$0.15Database disks, real-time analytics
Hot< 10ms~$0.02Frequently accessed data
Cool< 10ms~$0.01Infrequent access (> 30 ngày)
Cold< 10ms~$0.005Rare access (> 90 ngày)
ArchiveHours~$0.001Compliance, backup (> 180 ngày)
bash
# Set lifecycle management policy
az storage account management-policy create \
  --account-name stmyapp \
  --resource-group rg-app \
  --policy @lifecycle-policy.json
json
{
  "rules": [
    {
      "name": "move-to-cool",
      "type": "Lifecycle",
      "definition": {
        "filters": {
          "blobTypes": ["blockBlob"],
          "prefixMatch": ["logs/"]
        },
        "actions": {
          "baseBlob": {
            "tierToCool": { "daysAfterModificationGreaterThan": 30 },
            "tierToArchive": { "daysAfterModificationGreaterThan": 180 },
            "delete": { "daysAfterModificationGreaterThan": 365 }
          }
        }
      }
    }
  ]
}

Quick Wins - Top 10 Actions

#ActionEffortImpact
1Auto-shutdown dev/test VMs ngoài giờ30 phút65% savings dev
2Right-size over-provisioned VMs (Advisor)1 giờ20-40% savings
3Reserved Instances cho production stable2 giờ30-60% savings
4Storage lifecycle policy (hot -> cool -> archive)1 giờ50-80% storage savings
5Xóa orphaned disks, IPs, snapshots30 phútLoại bỏ waste
6Sử dụng Spot VMs cho CI/CD agents2 giờ70-90% CI savings
7Enable autoscale thay vì fixed instances2 giờ30-50% off-peak savings
8Review App Service plans - consolidate apps1 giờLoại bỏ empty plans
9Sử dụng Azure Hybrid Benefit (Windows/SQL licenses)30 phút40-55% savings
10Tag enforcement policy1 giờVisibility (nền tảng)

Trade-off Analysis

Quyết địnhTiết kiệmRủi ro
Reserved Instances 3 nămSavings cao nhất (60%)Lock-in, khó thay đổi architecture
Spot VMs cho production70-90% savingsEviction gây downtime
Aggressive auto-scalingTốt cho off-peakCold start latency, scale-up delay
Serverless cho mọi thứKhông tốn khi idleChi phí tăng nhanh ở high traffic
Archive tier cho data~$0.001/GBRehydration mất hàng giờ

Nguyên tắc FinOps: Optimize liên tục, không phải một lần. Thiết lập cost review cadence và accountability cho từng team.