🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Cutting ML Infrastructure Cost Without Slowing Teams

MLOpsCost Management⭐ Premium

Cutting ML Infrastructure Cost Without Slowing Teams

Difficulty: Senior Level | Companies: Google, Meta, Netflix, Uber, Stripe

Prerequisites

  • !Cloud billing basics and instance types
  • !How training and serving jobs consume resources
  • !Kubernetes resource requests

What You'll Learn

  • 1Break an ML bill into attributable, controllable components
  • 2Tag spend by model, team, and pipeline automatically
  • 3Use spot capacity with checkpoints and interruption handling
  • 4Right-size serving replicas against a latency SLO instead of instinct

Where ML money actually goes

ML cost rarely hides in one alarming line item; it hides in four moderate ones that nobody owns. Training runs that occupy a GPU while waiting for a data loader, experiment sweeps where eighty percent of variants were never going to be competitive, inference replicas sized for peak and idle most of the day, and storage of intermediate artifacts nobody has read in six months. Together these typically dominate the bill, and each is measurable the moment you decide to measure it. The obstacle is rarely technical — it is that no dashboard connects a dollar to a team, so optimization never gets prioritized over feature work.

The reframe that makes cost tractable is to treat compute as a product with unit economics. Cost per thousand predictions, cost per trained model, cost per experiment — these units survive scaling, because they change only when efficiency changes rather than when traffic does. A team that knows a model serves 1.2 million predictions a day at $4.30 per million can reason about a batching change; a team that only knows the monthly total can only ask someone to spend less.

Attribution before optimization

You cannot cut what you cannot attribute, so tagging comes first. Every job — training, evaluation, batch inference, notebook — should carry the model, team, and purpose tags from the moment it starts, and infrastructure without tags should be treated as a bug rather than a background cost. The table below is the minimum viable breakdown, and it maps directly onto who can act on each number.

Cost centerTypical shareControllable byFirst lever
Real-time serving30–50%Serving teamBatching, autoscaling, right-sizing
Training and sweeps20–35%Model teamsSpot capacity, early stopping, fewer trials
Batch inference10–20%Data platformScheduling off-peak, larger jobs
Storage and artifacts5–15%PlatformRetention policies, compression
Unassigned or idle5–20%PlatformTag enforcement, scale-to-zero

That last row is the fast win. Idle notebooks, forgotten dev clusters, and untagged experiments often account for a fifth of the bill with no technical difficulty attached — only a policy that stops resources from running unattended, plus a weekly report showing each team its own unassigned spend.

Tracking spend per run and per model

A lightweight tracker that ingests job metadata and price cards gives you the unit economics without waiting for a finance integration. The code below models what matters: per-resource usage, per-model rollups, and explicit detection of waste such as GPUs whose duty cycle is low because the job is input-bound.

python
# cost_tracking.py
from collections import defaultdict
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from typing import Dict, List, Optional


PRICES_PER_HOUR = {
    "gpu-a100": 3.20,
    "gpu-t4": 0.55,
    "cpu-8": 0.19,
    "memory-32": 0.12,
}


@dataclass
class Usage:
    resource: str
    hours: float
    quantity: float = 1.0

    @property
    def cost(self) -> float:
        return self.hours * self.quantity * PRICES_PER_HOUR.get(self.resource, 1.0)


@dataclass
class JobCost:
    job_id: str
    model: str
    team: str
    purpose: str
    started_at: datetime
    usage: List[Usage] = field(default_factory=list)
    gpu_utilization: Optional[float] = None
    predictions: int = 0

    @property
    def total(self) -> float:
        return sum(u.cost for u in self.usage)


class CostLedger:
    def __init__(self):
        self.jobs: List[JobCost] = []

    def record(self, job: JobCost) -> None:
        if not job.model or not job.team:
            raise ValueError(f"job {job.job_id} missing model or team tag")
        self.jobs.append(job)

    def by_model(self) -> Dict[str, float]:
        totals: Dict[str, float] = defaultdict(float)
        for job in self.jobs:
            totals[job.model] += job.total
        return dict(sorted(totals.items(), key=lambda kv: -kv[1]))

    def by_team(self) -> Dict[str, float]:
        totals: Dict[str, float] = defaultdict(float)
        for job in self.jobs:
            totals[job.team] += job.total
        return dict(sorted(totals.items(), key=lambda kv: -kv[1]))

    def unit_costs(self) -> Dict[str, Dict[str, float]]:
        out: Dict[str, Dict[str, float]] = {}
        per_model_jobs: Dict[str, List[JobCost]] = defaultdict(list)
        for job in self.jobs:
            per_model_jobs[job.model].append(job)

        for model, jobs in per_model_jobs.items():
            spend = sum(j.total for j in jobs)
            predictions = sum(j.predictions for j in jobs)
            runs = len(jobs)
            out[model] = {
                "spend": spend,
                "per_run": spend / max(runs, 1),
                "per_1k_predictions": spend / max(predictions, 1) * 1000,
            }
        return out

    def find_waste(self, min_utilization: float = 0.25,
                   idle_hours: float = 6.0) -> List[Dict[str, object]]:
        findings = []
        for job in self.jobs:
            gpu_hours = sum(u.hours for u in job.usage if u.resource.startswith("gpu"))
            if job.gpu_utilization is not None and job.gpu_utilization < min_utilization:
                findings.append({
                    "job": job.job_id,
                    "reason": "low gpu utilization",
                    "utilization": job.gpu_utilization,
                    "avoidable": gpu_hours * PRICES_PER_HOUR.get("gpu-a100", 3.20),
                })
            if job.gpu_utilization is None and gpu_hours >= idle_hours:
                findings.append({
                    "job": job.job_id,
                    "reason": "unmeasured long-running gpu job",
                    "hours": gpu_hours,
                    "avoidable": gpu_hours * PRICES_PER_HOUR.get("gpu-a100", 3.20),
                })
        return sorted(findings, key=lambda f: -float(f["avoidable"]))


ledger = CostLedger()
ledger.record(JobCost(
    job_id="churn-0421", model="churn-predictor", team="growth-ml",
    purpose="training", started_at=datetime.now(timezone.utc),
    usage=[Usage("gpu-a100", 2.5), Usage("cpu-8", 2.5)],
    gpu_utilization=0.18,
))
ledger.record(JobCost(
    job_id="churn-0422", model="churn-predictor", team="growth-ml",
    purpose="batch-inference", started_at=datetime.now(timezone.utc),
    usage=[Usage("cpu-8", 1.0)],
    predictions=1_500_000,
))
print("by model:", ledger.by_model())
print("unit costs:", ledger.unit_costs())
print("waste:", ledger.find_waste())

Feed this from job submission metadata rather than from manual entry, because manual tagging survives about two sprints. The unit-cost output is what turns cost conversations into engineering ones: once cost per thousand predictions is visible, a batching improvement has a number attached to it before anyone starts work.

Spot capacity that survives interruption

Spot or preemptible capacity typically costs thirty to seventy percent less, with one condition: it will be taken away. The bargain only works when jobs are designed for it, and that design has three parts — durable checkpoints at a fixed interval including optimizer state, a scheduler that relaunches on a new node, and a fallback to on-demand capacity when the interruption rate makes retries more expensive than the discount.

python
# spot_strategy.py
import random
from dataclasses import dataclass, field
from datetime import datetime, timedelta, timezone
from typing import Callable, Dict, List, Optional


@dataclass
class SpotOffer:
    instance: str
    gpu: str
    price_per_hour: float
    interruption_rate: float  # expected interruptions per hour
    availability_zone: str


@dataclass
class JobSpec:
    estimated_hours: float
    checkpoint_interval_minutes: int = 15
    max_intolerable_interruptions: int = 6


@dataclass
class SpotPolicy:
    max_interruption_rate: float = 0.12
    max_price_ratio_vs_ondemand: float = 0.6
    ondemand_price: Dict[str, float] = field(default_factory=lambda: {"A100": 3.20, "T4": 0.55})

    def expected_effective_cost(self, offer: SpotOffer, job: JobSpec) -> float:
        wasted = job.checkpoint_interval_minutes / 60 / 2
        restart_overhead = 0.15
        expected_loss = offer.interruption_rate * job.estimated_hours * (wasted + restart_overhead)
        effective_hours = job.estimated_hours + expected_loss
        return effective_hours * offer.price_per_hour

    def acceptable(self, offer: SpotOffer) -> bool:
        ondemand = self.ondemand_price.get(offer.gpu, 1.0)
        return (
            offer.interruption_rate <= self.max_interruption_rate
            and offer.price_per_hour <= ondemand * self.max_price_ratio_vs_ondemand
        )


def choose(offers: List[SpotOffer], job: JobSpec, policy: SpotPolicy) -> Optional[SpotOffer]:
    candidates = [o for o in offers if policy.acceptable(o)]
    if not candidates:
        return None
    scored = [(policy.expected_effective_cost(o, job), o) for o in candidates]
    return min(scored, key=lambda pair: pair[0])[1]


def interruptions_for(job: JobSpec) -> int:
    return random.randint(0, job.max_intolerable_interruptions)


offers = [
    SpotOffer("p4d.24xlarge", "A100", 11.0, 0.09, "us-east-1a"),
    SpotOffer("g5.12xlarge", "A100", 7.4, 0.21, "us-east-1b"),
    SpotOffer("g4dn.xlarge", "T4", 0.55, 0.04, "us-east-1c"),
]
policy = SpotPolicy()
job = JobSpec(estimated_hours=8.0)
best = choose(offers, job, policy)
print("selected:", best)
if best:
    print("expected effective cost:", round(policy.expected_effective_cost(best, job), 2))

Two habits make this safe in practice. Keep a hard budget guard so a retry loop cannot spend more than the job would have cost on demand, and record the number of resumes with the final metrics — a model trained across four interruptions is explainable only if that fact was captured at the time.

Right-sizing inference

Serving is usually the largest line item and the least tuned. Start from a latency SLO and work backwards: measure per-request compute cost, decide the batch size that meets p99, then derive replicas from peak arrival rate divided by per-replica throughput, plus headroom for failure. What most teams find is that their replicas were sized from a template — two or four copies of whatever the sample manifest contained — and that aggressive batching on fewer replicas cuts cost dramatically while adding only a few milliseconds.

Autoscaling policy matters as much as replica count. Scale on a service-level signal such as queue depth or per-replica concurrency rather than CPU alone, because inference on GPU is rarely CPU-bound and a CPU target will scale far too late. Scale up fast — a short stabilization window and a generous step — and scale down slowly, since aggressive scale-down during a traffic dip causes the load-shedding cascade that shows up as an availability incident rather than a cost saving.

Also worth auditing: replicas that cannot be drained cleanly tend to be kept at a floor that is far too high, because nobody trusts scale-to-zero. Fix the termination path — a preStop drain, a warm-up that passes readiness quickly, and a model already resident or cheaply mounted — and the minimum replica count can usually come down substantially. Most teams find their overnight bill drops by a third from that one change alone, with no effect on latency during business hours.

Habits that compound

Policies beat exhortations. Three that return quickly: scale idle development environments to zero outside working hours, expire intermediate training artifacts after a defined window while keeping registered models under retention policy, and require a cost estimate in the description of any job expected to run longer than an hour. None of these requires a platform team; all of them require someone to write the policy down and enforce it in a weekly report.

The last habit is reviewing unit costs on the same cadence as reliability. A monthly ten-minute review of cost per thousand predictions per model surfaces trends that totals hide — a batching regression, a sweep that grew, a replica count nobody revisited after a traffic change. Reliability gets dashboards and on-call attention by default; cost only improves when it is given the same standing agenda item.

💡Optimize the idle first

A GPU at 15% utilization is a cheaper fix than a 3% kernel optimization. Measure duty cycle across your fleet before anyone starts profiling training loops.

Common Mistakes

Starting with kernel-level optimization

Fix: Attribute spend first and reclaim idle or untagged resources — that usually beats micro-optimization.

Running spot instances without durable checkpoints

Fix: Checkpoint optimizer state on an interval shorter than your tolerance for lost work, and relaunch automatically.

Scaling inference on CPU utilization

Fix: Drive autoscaling from queue depth or per-replica concurrency, which actually reflects inference pressure.

Storing every intermediate artifact forever

Fix: Apply retention windows to intermediates while keeping registered models under an explicit policy.

Best Practices

  • Tag every job at submission; block untagged runs in CI
  • Track unit costs — per run and per thousand predictions — not just totals
  • Record resumes alongside metrics when training on preemptible capacity
  • Right-size serving from measured throughput against a latency SLO
  • Review cost metrics monthly with the same rigor as reliability metrics

Interview Questions

Q1: How do you attribute cloud cost to individual ML models?

Tag at job submission with model, team, and purpose, then join usage records against a price card to produce per-model and per-unit rollups.

Q2: When are spot instances a bad idea?

When jobs are short, checkpointing is impossible, or interruption rates make retries cost more than the discount — always compare effective cost including wasted work.

Q3: What is the first thing to optimize in an ML bill?

Unattributed and idle capacity. It is usually a large share, requires no model changes, and reveals who should own the rest.

Q4: Why scale on queue depth instead of CPU?

GPU inference is rarely CPU-bound, so CPU stays flat while requests queue; queue depth reflects real pressure and triggers scaling in time.

Key Takeaways

  • Attribution must precede optimization or nothing gets prioritized
  • Unit economics — cost per thousand predictions — survive changes in traffic
  • Spot capacity is a bargain only with checkpoints, relaunch, and a budget guard
  • Serving size should fall out of latency SLO and measured throughput
  • Idle and untagged resources are the cheapest reclaim in the whole bill
🔒

Premium Content

Cutting ML Infrastructure Cost Without Slowing Teams

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

đŸŽ¯End-to-end Projects
đŸ’ŧInterview Prep
📜Certificates
🤝Community Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Advertisement