Careers Post-AI
AI infrastructure and systems: all chapters

AI infrastructure and systemsPart 5: Production operations

Chapter 19Cost engineering and GPU economics

30 min read, 1 lab, Intermediate

Two rented H100s left running all month cost about $4,400, which can be four times what the same traffic would cost on a hosted API, or a quarter of it, depending on volume and utilization. This chapter teaches you to do that arithmetic properly: what each option really costs, where the money goes, who spent it, and which levers move the bill most.

After this chapter you can

  • Break the cost of an AI service into its stack and identify the dominant terms
  • Compare hosted API, rented GPU and owned hardware with a break-even model
  • Explain why utilization dominates self-hosted cost and how pricing models interact with it
  • Compute unit economics per request, per user and per million tokens
  • Attribute shared AI spend to teams and features with showback reports
  • Rank optimization levers by impact and estimate training costs from first principles

The cost stack

Performance and cost math gave you the core sums; this chapter applies them to running a business. Every AI request is paid for by a stack of costs, and which layer dominates depends on whether you call an API or run your own models.

With an API you pay per token and the provider absorbs idle time, hardware failures and upgrades. Self-hosted, you pay for GPU time whether or not it serves a token. Two items are routinely forgotten: idle capacity, which is often the largest line, and the engineers who keep the fleet running.

LayerTypical share, self-hostedNotes
GPU compute50 to 80%Rented hours or amortised purchase price
Idle and headroomHidden inside GPU computeA fleet at 30% average utilization wastes 70% of it
Platform and people10 to 30%One engineer is a large fraction of a small fleet's cost
Storage, network, observability5 to 15%Weights, logs, traces, cross-zone egress
Power and space5 to 15%, owned onlyFolded into the hourly rate when renting

Three ways to pay for inference

You can buy inference by the token, rent GPUs by the hour, or buy GPUs and run them for years. Prices below are approximate, checked in December 2026, and move often; treat them as orders of magnitude and get your own quotes.

Hosted API

  • Pay per token, roughly $1 in and $5 out per million for a small model tier
  • Zero idle cost, instant scale, no ops
  • Batch APIs often discount about 50% for work that can wait hours
  • Rate limits, data-handling terms, and no control over model updates

Rented GPU

  • Pay per GPU-hour: about $2 to $4 for an H100 at specialist clouds, near $7 at hyperscaler on-demand rates
  • You pay for idle hours
  • Full control of model, batching and quantization
  • You run the serving stack and its on-call

Owned GPU

  • About $250,000 to $320,000 for an 8-GPU H100 server, amortised over 3 to 4 years
  • Plus power, cooling, colocation and staff
  • Cheapest per GPU-hour at sustained high utilization
  • Long lead times, refresh risk as new generations arrive

Rented capacity itself comes in three pricing models. On-demand is pay-as-you-go at full price. Reserved or committed capacity trades a one- to three-year commitment for a discount, commonly in the range of 30 to 60%. Spot (preemptible) capacity uses spare hardware at discounts AWS advertises as up to 90%, but can be reclaimed with about two minutes' notice.

WorkloadBest fitWhy
Steady baseline inferenceReserved or ownedRuns all the time, so the commitment is fully used
Daily peaks above the baselineOn-demand or API overflowPay only for the hours you need
Batch scoring, embeddings backfill, evalsSpot or batch APIInterruptible and deadline-tolerant
Training with frequent checkpointsSpot or reservedSpot works if a restart loses minutes, not days

Utilization is the dominant lever

The cost of a self-hosted token is the GPU's hourly price divided by the tokens it actually produces in that hour. The hourly price is fixed; the tokens depend on how busy you keep it.

Cost per million output tokens, self-hosted
cost_per_M = usd_per_gpu_hour / (tokens_per_s_at_full_load x 3600 x utilization) x 1,000,000
 
H100 at $3.00/hour, 1,500 output tokens/s at full load:
  utilization 100%  ->  $0.56 per million
  utilization  50%  ->  $1.11 per million
  utilization  20%  ->  $2.78 per million
  utilization   5%  ->  $11.11 per million

Halving the GPU price saves 50%. Raising utilization from 20% to 60% saves 67% and costs nothing but engineering. Utilization moves cost more than price, which is why batching, right-sizing and autoscaling matter more than negotiating your hourly rate.

Utilization has a ceiling you choose. If your busiest hour carries 2.5 times the average traffic and you keep 20% headroom above that peak, average utilization cannot exceed about 1 divided by 3, or 33%. Smoothing the peak (deferring batch work to nights, sharing a pool across time zones or products) raises that ceiling more than any single optimization.

A break-even analysis

Here is the comparison the lab builds, for one traffic shape: 1,000 input and 300 output tokens per request, a peak-to-average ratio of 2.5, and 20% headroom. API prices are $1 and $5 per million tokens. Self-hosting assumes an 8B-class model sustaining 1,500 output tokens per second per H100 at the latency SLO, at least 2 GPUs for redundancy, $3 per GPU-hour rented, and for owned hardware a $300,000 8-GPU server over 3 years with power, colocation and a $6,000 monthly ops share.

Requests per dayGPUsAvg utilizationAPI per monthRented per monthOwned per month
10,00021%$760$4,380$16,995
100,000212%$7,600$4,380$16,995
1,000,000733%$76,000$15,330$16,995
3,000,0002133%$228,000$45,990$38,985
10,000,0007033%$760,000$153,300$104,954

At this shape, rented GPUs beat the API above roughly 58,000 requests a day and owned hardware wins once you fill whole servers, around 20 or more GPUs. The API costs $0.0025 per request whatever the volume, while self-hosting has a floor of two idle GPUs.

The single most sensitive input is per-GPU throughput at your SLO. Double it and every self-hosted column halves; measure it with your real prompts, model and latency target before trusting any break-even.

Unit economics

Unit economics express cost per unit of value delivered, so you can compare it with revenue per unit. Pick units that match how the product earns money.

UnitFormulaUse it for
Cost per requesttotal AI cost divided by requestsComparing models and prompt designs
Cost per million tokenstotal cost divided by tokens, times 1,000,000Comparing self-hosted with API pricing
Cost per active user per monthmonthly AI cost divided by monthly active usersPricing plans, free-tier limits
Cost per successful taskcost of all attempts divided by tasks completedAgents, where retries and failed runs add up
AI gross marginrevenue minus AI cost, divided by revenueWhether a feature is a business

Averages hide the tail. In most products a few percent of users generate a large share of tokens, so look at the distribution of cost per user, not just its mean. A heavy user on a flat-rate plan with long-context agent runs can cost more than they pay, which is why many AI products meter usage or cap context.

Attribution and showback

Attribution assigns each dollar of AI spend to the team, feature or customer that caused it. Showback reports that cost to the owner; chargeback goes further and bills it to their budget. Without attribution, AI spend becomes a shared pool that grows with nobody accountable.

API spend is easy to attribute: log tokens per request at the gateway (covered in LLM gateways, routing and caching) and multiply by price. Shared GPU pools are harder because the bill arrives per GPU-hour, not per request. You need an allocation rule.

Allocation ruleHowTrade-off
By tokensPool cost times the team's share of tokensSimple; ignores that long prompts and long outputs load the GPU differently
By busy timePool cost times share of request-seconds on the serverCloser to real load; needs latency per request
Reserved slicesEach team pays for a fixed share, used or notPredictable; teams hoard capacity
Idle as platform costAllocate used capacity, report idle separatelyMakes waste visible to the platform team

Choose a rule, write it down and keep it stable, because teams will optimise against it. Showing idle cost as its own line is often the most useful choice: it tells the platform team exactly how much money right-sizing would save.

Optimization levers, ranked

Optimize in order of impact per unit of effort. The ranges below are typical, not guaranteed; measure each on your own workload and confirm quality with your evals.

RankLeverTypical savingMain risk
1Use the smallest model that passes evals, or route easy requests to it3 to 20 times on routed trafficQuality on hard cases
2Prompt and prefix cachingLarge on input cost; cached reads are often priced at 10% of normal input or lessCache-unfriendly prompt layouts
3Trim tokens: shorter prompts, fewer retrieved chunks, output caps20 to 50%Losing needed context
4Batch or offline APIs for work that can waitAbout 50%Hours of latency
5Raise utilization: continuous batching, right-sizing, autoscaling2 to 3 times self-hostedLatency under load
6Quantization, for example FP8 or INT4 weights1.5 to 3 times throughputSmall quality loss, measure it
7Better pricing: reserved, spot, negotiated rates30 to 60%Commitment and preemption

Model choice sits at the top because the price gap between model tiers is often 10 times or more, larger than any infrastructure trick. Model optimization covered quantization and speculative decoding in depth; here the point is to apply them after the cheaper levers.

Estimating training cost

Training cost follows from a well-known approximation: training a dense transformer takes about 6 x N x D floating-point operations, where N is the parameter count and D the number of training tokens. Divide by the throughput your cluster actually achieves, which is peak FLOPS times model FLOPs utilization (MFU), the fraction of peak spent on useful math.

Pretraining an 8B model on 1 trillion tokens
FLOPs          = 6 x 8e9 x 1e12             = 4.8e22
H100 peak      ~ 989 TFLOPS dense BF16
Achieved at 40% MFU                          = 3.96e14 FLOP/s per GPU
GPU-seconds    = 4.8e22 / 3.96e14           = 1.21e8
GPU-hours      = 1.21e8 / 3600              ~ 33,700
Cost at $3/GPU-hour                         ~ $101,000
Plus 20-30% for restarts, failed runs, evals ~ $125,000

Fine-tuning is far cheaper. A LoRA run on 50 million tokens for the same model needs roughly an hour of one H100, a few dollars of compute, as covered in Fine-tuning systems. There, data preparation, evaluation runs and engineer time dominate the bill.

Budgeting and forecasting

A forecast turns product plans into a monthly AI bill. Build it from drivers, not from last month's invoice: expected users, requests per user, tokens per request, model mix and price. Then you can answer "what if usage doubles" or "what if we move support to the small model" in minutes.

  1. Model the drivers

    Monthly cost equals users times requests per user times tokens per request times price per token, per model. Keep each driver as a separate cell.

  2. Add self-hosted capacity

    Convert peak traffic into GPUs with measured throughput and headroom, then into hours and dollars. Remember the minimum fleet.

  3. Set budgets and alerts

    Give each team a monthly budget from the forecast. Alert at 50%, 80% and 100% of budget, and on any day whose spend exceeds twice the trailing average.

  4. Review monthly

    Compare actuals with the forecast, explain the variance by driver, and update the drivers. Most variance comes from token growth per request, not from user growth.

Runaway spend has real causes: a retry loop, an agent stuck calling a tool, a prompt change that doubled context. Daily anomaly alerts on cost per team catch these within a day instead of at month end.

Key terms

Break-even point
The volume at which two cost options are equal; beyond it the option with lower marginal cost wins.
Utilization
The share of paid capacity that does useful work; idle capacity is paid for but produces nothing.
Reserved capacity
GPU or instance capacity committed for one to three years in exchange for a discount.
Spot instance
Spare cloud capacity sold at a deep discount that the provider can reclaim at short notice.
Unit economics
Cost and revenue expressed per unit of value, such as per request, per user or per task.
Showback
Reporting the cost a team or feature caused, without billing it to their budget.
Chargeback
Billing attributed costs to the budget of the team that caused them.
MFU
Model FLOPs utilization: achieved useful FLOPs as a fraction of the hardware's peak.
Lab

Build a break-even model and a cost attribution report

Intermediate, 60 min

Goal: build a break-even model comparing a hosted API, rented GPUs and owned GPUs for a traffic profile, then produce a showback report from a month of request logs. Both scripts are worth keeping in a public repo.

You need: Python 3.10 or newer and pandas (python3 -m venv .venv && . .venv/bin/activate && pip install pandas). No GPU is required.

  1. Create the break-even model. Every price is a named constant you can replace with your own quotes:
breakeven.py
"""Break-even model: hosted API vs rented cloud GPU vs owned GPU servers.
All prices are approximate (checked December 2026). Replace them with your quotes."""
import math
from dataclasses import dataclass
 
HOURS_PER_MONTH = 730
DAYS_PER_MONTH = 30.4
 
@dataclass
class Profile:
    requests_per_day: float
    input_tokens: int = 1000      # average prompt tokens per request
    output_tokens: int = 300      # average completion tokens per request
    peak_to_avg: float = 2.5      # busiest hour divided by average hour
    cached_share: float = 0.0     # share of input tokens served from a prompt cache
 
# Hosted API, USD per million tokens (small-model tier, approximate list price)
API = {"in": 1.00, "out": 5.00, "cache_read_mult": 0.10}
# Self-hosted serving assumption: an 8B-class model on one H100 at your latency SLO.
# MEASURE THIS on your own workload; it is the most sensitive input in the model.
SERVE = {"out_tok_s_per_gpu": 1500, "min_gpus": 2, "headroom": 1.2}
CLOUD = {"usd_per_gpu_hour": 3.00}   # specialist cloud; hyperscaler on-demand is closer to 7
OWNED = {
    "server_usd": 300_000, "gpus_per_server": 8, "years": 3,
    "kw_per_server": 10.2, "pue": 1.3, "usd_per_kwh": 0.12,
    "colo_usd_month_per_server": 1_500, "ops_usd_month": 6_000,
}
 
def api_month(p: Profile) -> float:
    reqs = p.requests_per_day * DAYS_PER_MONTH
    tin, tout = reqs * p.input_tokens, reqs * p.output_tokens
    cached = tin * p.cached_share
    usd = (tin - cached) * API["in"] + cached * API["in"] * API["cache_read_mult"] + tout * API["out"]
    return usd / 1e6
 
def gpus_needed(p: Profile) -> int:
    avg_out_tok_s = p.requests_per_day * p.output_tokens / 86_400
    peak = avg_out_tok_s * p.peak_to_avg * SERVE["headroom"]
    return max(SERVE["min_gpus"], math.ceil(peak / SERVE["out_tok_s_per_gpu"]))
 
def cloud_month(p: Profile) -> float:
    return gpus_needed(p) * CLOUD["usd_per_gpu_hour"] * HOURS_PER_MONTH
 
def owned_month(p: Profile) -> float:
    servers = math.ceil(gpus_needed(p) / OWNED["gpus_per_server"])
    capex = servers * OWNED["server_usd"] / (OWNED["years"] * 12)
    power = servers * OWNED["kw_per_server"] * OWNED["pue"] * HOURS_PER_MONTH * OWNED["usd_per_kwh"]
    colo = servers * OWNED["colo_usd_month_per_server"]
    return capex + power + colo + OWNED["ops_usd_month"]
 
def utilization(p: Profile) -> float:
    avg_out_tok_s = p.requests_per_day * p.output_tokens / 86_400
    return avg_out_tok_s / (gpus_needed(p) * SERVE["out_tok_s_per_gpu"])
 
def break_even(cost_fn, lo=1_000, hi=50_000_000) -> float:
    """Smallest requests/day where cost_fn beats the API (bisection on a step function)."""
    if cost_fn(Profile(hi)) >= api_month(Profile(hi)):
        return float("nan")
    for _ in range(60):
        mid = (lo + hi) / 2
        if cost_fn(Profile(mid)) < api_month(Profile(mid)):
            hi = mid
        else:
            lo = mid
    return hi
 
if __name__ == "__main__":
    print(f"{'req/day':>10} {'GPUs':>5} {'util':>6} {'API $/mo':>11} {'cloud $/mo':>11} {'owned $/mo':>11}  cheapest")
    for rpd in [10_000, 50_000, 100_000, 300_000, 1_000_000, 3_000_000, 10_000_000]:
        p = Profile(rpd)
        costs = {"API": api_month(p), "cloud": cloud_month(p), "owned": owned_month(p)}
        print(f"{rpd:>10,} {gpus_needed(p):>5} {utilization(p):>6.0%} {costs['API']:>11,.0f} "
              f"{costs['cloud']:>11,.0f} {costs['owned']:>11,.0f}  {min(costs, key=costs.get)}")
    print(f"\nCloud GPU beats API above ~{break_even(cloud_month):,.0f} requests/day")
    print(f"Owned GPU beats API above ~{break_even(owned_month):,.0f} requests/day")
    p = Profile(1_000_000)
    print(f"API cost per request at this shape: ${api_month(p) / (p.requests_per_day * DAYS_PER_MONTH):.5f}")
  1. Run it. You should see the table from this chapter and two break-even lines:
Cloud GPU beats API above ~57,632 requests/day
Owned GPU beats API above ~223,617 requests/day
API cost per request at this shape: $0.00250
  1. Run sensitivity experiments by editing one constant at a time and rerunning: set cached_share to 0.6 in Profile, set out_tok_s_per_gpu to 3000, set peak_to_avg to 1.5, and set usd_per_gpu_hour to 6.9. Write down how far each moves the cloud break-even point. Throughput and caching usually move it most.

  2. Generate a month of synthetic gateway logs (sampled 1 in 10, like many real gateways):

gen_logs.py
"""Generate 30 days of synthetic gateway request logs as JSON lines."""
import json, random
from datetime import datetime, timedelta, timezone
 
random.seed(7)
TEAMS = {  # team: (feature, model mix, requests per day, avg input, avg output, cache share)
    "support": ("support-bot", {"small-api": 0.7, "large-api": 0.3}, 6000, 2500, 250, 0.6),
    "search": ("answer-box", {"self-hosted-8b": 1.0}, 20000, 1200, 150, 0.0),
    "sales": ("email-drafts", {"large-api": 1.0}, 800, 1800, 600, 0.2),
    "internal": ("code-review", {"large-api": 0.5, "small-api": 0.5}, 400, 6000, 400, 0.4),
}
start = datetime(2026, 11, 1, tzinfo=timezone.utc)
with open("requests.jsonl", "w") as f:
    for day in range(30):
        for team, (feature, mix, per_day, tin, tout, cache) in TEAMS.items():
            for _ in range(int(per_day * random.uniform(0.8, 1.2) / 10)):  # 1 in 10 sample
                model = random.choices(list(mix), weights=mix.values())[0]
                i = max(50, int(random.gauss(tin, tin * 0.3)))
                o = max(5, int(random.expovariate(1 / tout)))
                ts = start + timedelta(days=day, seconds=random.randint(0, 86_399))
                f.write(json.dumps({
                    "ts": ts.isoformat(), "team": team, "feature": feature, "model": model,
                    "user": f"u{random.randint(1, 3000)}", "input_tokens": i,
                    "cached_tokens": int(i * cache * random.uniform(0.8, 1.0)),
                    "output_tokens": o, "latency_ms": int(300 + o * 25 * random.uniform(0.8, 1.3)),
                    "status": "ok" if random.random() > 0.01 else "error", "sample_rate": 10,
                }) + "\n")
print("wrote requests.jsonl")
  1. Write the showback report. API calls are priced per token; the self-hosted pool's monthly cost is allocated by busy slot-seconds, and idle capacity is reported:
attribution.py
"""Showback report: monthly AI cost per team and feature from gateway logs."""
import pandas as pd
 
PRICES = {  # USD per million tokens: input, cached input, output (approximate, Dec 2026)
    "small-api": (1.00, 0.10, 5.00),
    "large-api": (2.00, 0.10, 10.00),   # mid-tier model
}
SELF_HOSTED_FLEET_USD = 4_380   # 2 rented GPUs x $3/hour x 730 hours, serving self-hosted-8b
FLEET_CAPACITY_SLOT_S = 2 * 30 * 86_400 * 16   # 2 GPUs x seconds x 16 concurrent slots each
 
df = pd.read_json("requests.jsonl", lines=True)
w = df["sample_rate"]                                    # undo 1-in-10 sampling
 
def api_cost(r):
    if r.model not in PRICES:
        return 0.0
    p_in, p_cache, p_out = PRICES[r.model]
    fresh = r.input_tokens - r.cached_tokens
    return (fresh * p_in + r.cached_tokens * p_cache + r.output_tokens * p_out) / 1e6
 
df["api_usd"] = df.apply(api_cost, axis=1) * w
hosted = df["model"] == "self-hosted-8b"
df["slot_s"] = (df["latency_ms"] / 1000) * w * hosted    # busy slot-seconds on the shared pool
used = df["slot_s"].sum()
df["gpu_usd"] = df["slot_s"] / used * SELF_HOSTED_FLEET_USD if used else 0.0
df["usd"] = df["api_usd"] + df["gpu_usd"]
df["requests"] = w
df["tokens"] = (df["input_tokens"] + df["output_tokens"]) * w
 
report = df.groupby(["team", "feature"]).agg(
    requests=("requests", "sum"), tokens=("tokens", "sum"),
    api_usd=("api_usd", "sum"), gpu_usd=("gpu_usd", "sum"), usd=("usd", "sum"),
    users=("user", "nunique"))
report["usd_per_1k_req"] = report["usd"] / report["requests"] * 1000
report["usd_per_user"] = report["usd"] / report["users"]
report["share"] = report["usd"] / report["usd"].sum()
pd.set_option("display.float_format", "{:,.2f}".format)
print(report.sort_values("usd", ascending=False).to_string())
print(f"\nTotal monthly AI spend: ${report['usd'].sum():,.0f}")
print(f"Self-hosted pool utilization: {used / FLEET_CAPACITY_SLOT_S:.0%} of slot capacity "
      f"(idle cost is spread across users of the pool)")
cache_savings = sum(
    (df.loc[df.model == m, "cached_tokens"] * w * (p[0] - p[1]) / 1e6).sum() for m, p in PRICES.items())
print(f"Prompt caching saved about ${cache_savings:,.0f} this month")
p_in, _, p_out = PRICES["small-api"]
what_if = ((df.loc[hosted, "input_tokens"] * p_in + df.loc[hosted, "output_tokens"] * p_out)
           * w[hosted] / 1e6).sum()
print(f"What-if: self-hosted traffic on small-api would cost ${what_if:,.0f} vs ${SELF_HOSTED_FLEET_USD:,} for the pool")
  1. Run both:
python3 gen_logs.py && python3 attribution.py

Expect the search team at the top with about $4,380 and roughly 82% of spend, support next at about $610, total about $5,300, pool utilization around 3%, caching savings around $350, and a what-if line showing the search traffic would cost about $1,150 on the small API.

Check your work: you can state, with numbers from your own runs, the request volume where rented GPUs beat the API, which single assumption moves it most, and which team's spend is mostly idle GPU capacity. The report should make the recommendation obvious: at 20,000 requests a day, the search team's dedicated pool costs nearly four times the API.

Stretch: add a column for cost per successful request (excluding errors from the denominator), a daily cost series per team with an alert when any day exceeds twice its trailing 7-day mean, and a fourth option to the break-even model that serves the baseline on reserved GPUs and sends peaks to the API.

Check yourself

A self-hosted model runs on 4 rented GPUs at 15% average utilization. Which change most reduces cost per million tokens?

Your break-even model says self-hosting wins above 60,000 requests per day. Which input should you verify first before acting?

Traffic peaks at 3 times the daily average and you keep 25% headroom above peak. Roughly what is the best average utilization a fixed-size fleet can reach?

Finance asks why AI spend doubled while active users grew 10%. What is the most likely driver to check first?

Recap

  • Self-hosted cost is mostly GPU time, and idle capacity is the biggest hidden line; APIs push idle cost to the provider.
  • Cost per token equals price divided by useful throughput, so utilization moves cost more than the hourly rate.
  • Break-even depends most on measured per-GPU throughput at your SLO, the minimum fleet size and the peak-to-average ratio.
  • Track unit economics per request, per user and per successful task, and watch the tail of heavy users.
  • Attribute every dollar with gateway metadata and a written allocation rule, and show idle capacity as its own line.
  • Optimise in order: model choice, caching, token trimming, batch APIs, utilization, quantization, then pricing.

Go deeper