Library

Volume 1 · Cloud-Native Architecture

Notebook
Sign in

Section 26

Cloud Cost Optimization & FinOps

700 words · about 3 min

26.1 Cost Optimization Hierarchy (AWS, generalizes to Azure/GCP)

1. RIGHT-SIZE     → Match instance/SKU type and size to actual utilization
2. RESERVE        → Reserved Instances/Savings Plans (1yr/3yr) for predictable workloads (30-72% savings)
3. SPOT            → Spot/Low-priority VMs for stateless, fault-tolerant, interruptible workloads (up to 90% savings)
4. SERVERLESS      → Lambda/Fargate/Functions — pay per use, zero idle cost
5. SAVINGS PLANS   → Flexible commitment across compute types (AWS) / Reserved capacity (Azure)

26.2 Cost Visibility & Governance Tooling

Tool (AWS) Tool (Azure) Purpose
Cost Explorer Cost Management Visualize, analyze, forecast spend
Budgets Budget Alerts Threshold-based alerting
Trusted Advisor Advisor Rightsizing, idle-resource recommendations
Compute Optimizer Advisor (VM right-sizing) ML-based rightsizing recommendations
S3 Intelligent-Tiering Blob lifecycle policies Auto-move cold data to cheaper tiers

26.3 FinOps Practices for AI Workloads Specifically

  • Token cost attribution: tag every LLM call with feature/team/tenant so cost can be broken down by business unit, not just by AWS/Azure account — this is the AI-era equivalent of resource tagging.
  • Model-tiering by query complexity: route simple/high-volume queries to a cheaper model (Haiku/GPT-4o-mini class) and reserve frontier models for genuinely complex reasoning — often the single largest lever on GenAI spend.
  • Cache aggressively: cache embeddings and repeated-prompt responses; semantic caching (cache hit on near-duplicate queries, not just exact match) can cut token spend substantially in support/FAQ-style workloads.
  • PTU/reserved throughput vs. pay-per-token: model the break-even point — PTU (Azure) / provisioned throughput (Bedrock) makes sense only once volume is high and predictable enough that the reserved cost beats variable pay-per-token.
  • GPU utilization: for self-hosted inference (vLLM on EKS/AKS), track GPU utilization directly — an idle GPU node pool is the most expensive form of waste in an AI platform; use continuous batching and autoscale-to-zero for bursty GPU workloads.
  • Governance: tag every resource (including AI/token spend where the platform supports cost-center tags), set budget alerts per team, run weekly cost reviews during ramp-up phases of a new AI feature.

26.4 AI-Driven Cost & Operations Automation

Cloud Infrastructure
    │
    ├── Logs (CloudWatch/Log Analytics) ── GenAI Log Analysis
    │                                       "Summarize errors in the last hour"
    │                                       "What's driving the 5xx spike?"
    │
    ├── Metrics ── Predictive Scaling
    │               ML model forecasts traffic, pre-scales before peak
    │
    ├── Events ── Anomaly Detection
    │              Unsupervised ML flags unusual patterns, auto-remediation for known issues
    │
    └── Cost ── Cost Optimization Agent
                 Identifies underutilized resources, recommends right-sizing

Predictive scaling example (Prophet forecasting driving ASG capacity):

from prophet import Prophet
import boto3

def predict_and_scale():
    metrics = cloudwatch.get_metric_data(metric="RequestCount", period="1h", days=30)

    model = Prophet(yearly_seasonality=False)
    model.fit(historical_data)
    forecast = model.predict(next_24_hours)

    predicted_peak = forecast["yhat_upper"].max()
    required_instances = calculate_instances(predicted_peak)

    autoscaling.update_desired_capacity(
        group="inference-processing",
        desired=required_instances
    )

26.5 Interview Q&A

Q1: Your GenAI feature’s cloud bill jumped 40% this month. Walk through your investigation.

A: Start in Cost Explorer/Cost Management filtered by service and tag to confirm it’s token spend, not compute. Break down token consumption by feature/endpoint via structured request logging. Common root causes I check first: a prompt regression causing unbounded context growth (e.g., appending full history every turn instead of summarizing), a retry loop firing on transient errors and re-billing tokens each time, or a feature launch driving genuine legitimate volume growth. Fixes depend on cause: route simple queries to a cheaper model, add semantic caching, cap max tokens per request, fix the retry/backoff logic, or move to reserved throughput (PTU/provisioned throughput) if volume is now consistently high. I’d also make sure per-feature cost tagging exists going forward so this is visible within a day, not a monthly bill surprise.

Q2: How do you decide between Reserved Instances/Savings Plans and Spot for a given workload?

A: Reserved/Savings Plans for anything with predictable, steady-state utilization — production API servers, always-on databases, baseline GPU capacity for a production inference service. Spot for stateless, fault-tolerant, interruptible work — batch document processing, model training jobs with checkpointing, CI/CD build agents. The two combine well: run baseline capacity on Reserved/Savings Plans, burst capacity on Spot with graceful interruption handling (checkpoint training jobs, drain connections on ECS/EKS spot termination notices), and true spiky/low-volume work on serverless (Lambda/Fargate) where neither reservation nor spot management is worth the operational overhead.