FinOps for AI and LLMs: cost per token, model routing and spot instances for training and inference
How to measure and reduce the cost of AI workloads: input and output tokens, prompt caching, batch APIs, model routing, spot GPUs with checkpointing, and calculating cost per million tokens on your own infrastructure.
FinOps$ kubectl get nodepool gpu-training▍AI workloads have changed the cost curve of many companies within just a few months. A generative AI feature can cost more than the rest of the infrastructure combined — and, unlike a traditional API, the cost of each request varies widely depending on the size of the prompt and the response.
FinOps practices still apply, but the unit of measure changes: instead of instance hours, we start talking about tokens, GPU hours and cost per resolved task.
How the cost of an LLM via API is calculated
Model providers charge per million tokens, with different prices for:
- Input tokens (prompt, system instructions, conversation history, retrieved documents);
- Output tokens (the generated response) — usually several times more expensive than input tokens;
- Cached tokens — when the provider reuses an already-processed prompt prefix, charging much less for it.
The practical consequence: in applications with RAG or long histories, the prompt is usually the largest share of the cost, even though each output token is more expensive.
Step 1: measure cost per request (and per task)
The APIs return the token count for each call. Record it together with the business context:
# illustrative prices per million tokens — keep them in configuration, not in code
PRICES = {
"large-model": {"input": 3.00, "output": 15.00, "cache": 0.30},
"small-model": {"input": 0.25, "output": 1.25, "cache": 0.03},
}
def call_cost(model, usage):
p = PRICES[model]
return (
usage["input_tokens"] * p["input"]
+ usage["output_tokens"] * p["output"]
+ usage.get("cache_read_tokens", 0) * p["cache"]
) / 1_000_000
# alongside each call, emit a metric/log with:
# feature, customer, model, tokens and calculated cost
With this, you get to the metric that matters: cost per resolved task (a closed support conversation, a summarized document, a classified ticket). It’s the unit economics of AI — and it’s what tells you whether the feature has a margin.
Step 2: the optimization levers for APIs
Trim the prompt
- Send fewer chunks in RAG: retrieving 20 documents “just in case” multiplies the cost without necessarily improving the answer. Measure quality with 3, 5 and 10.
- Summarize the history of long conversations instead of resending everything on every turn.
- Review huge system instructions that have grown over time.
Take advantage of prompt caching
Put the stable content at the beginning of the prompt (instructions, examples, fixed documentation) and the variable content at the end. That way the prefix can be reused from the cache, which costs a fraction of the normal price.
Use batch APIs for anything that isn’t real-time
Classifying last night’s tickets, generating product descriptions, evaluating models: several providers offer batch processing APIs with a significant discount (often around 50%) in exchange for responses within a few hours.
Route between models
Not every task needs the most capable model. An effective pattern:
- A small, cheap model handles most simple requests (classification, extraction, short answers).
- Complex tasks, or cases where the small model signals low confidence, go to the larger model.
- Automated evaluations ensure quality hasn’t dropped.
Limit the output
Set a max_tokens value appropriate to the task and ask for concise formats (structured JSON, short lists). Since output tokens are the most expensive, verbose responses weigh on the bill.
Step 3: when the infrastructure is yours (your own GPUs)
When you host open models or train your own, the math shifts to GPU-hours — and the biggest waste is usually idle GPUs.
Calculate the cost per million tokens
To compare with APIs, convert the infrastructure into the same unit:
cost per 1M tokens = instance cost per hour / (tokens generated per hour / 1,000,000)
An illustrative example: a $4.00/hour instance generating 2,000 tokens/s at 60% average utilization produces 2,000 × 3,600 × 0.6 ≈ 4.3 million tokens per hour — about $0.93 per million tokens. At 15% utilization, the same server costs almost $3.70 per million. Utilization decides whether running your own infrastructure pays off.
To increase throughput per GPU:
- Use inference servers with continuous batching (such as vLLM or TGI);
- Evaluate quantization (8 or 4 bits) when the quality loss is acceptable;
- Choose the GPU based on model and context size, not the most powerful one available;
- Shut down or scale to zero environments that don’t serve real-time traffic.
Spot instances for training
Training and fine-tuning jobs are natural candidates for spot instances, which cost much less than on-demand ones — provided the job survives interruptions. On AWS, the interruption notice arrives about two minutes in advance; on other providers, the window can be even shorter. The secret is to save checkpoints frequently and when the termination signal arrives:
import signal
import torch
interrupted = False
def on_sigterm(signum, frame):
global interrupted
interrupted = True
signal.signal(signal.SIGTERM, on_sigterm)
for step, batch in enumerate(data, start=start_step):
train(batch)
if step % 500 == 0 or interrupted:
torch.save(
{"step": step, "model": model.state_dict(), "optimizer": optimizer.state_dict()},
"/checkpoints/latest.pt", # persistent volume or synced to S3/GCS
)
if interrupted:
break
When it restarts on another machine, the job loads the latest checkpoint and picks up where it left off.
Spot for inference (carefully)
Inference can also use spot, as long as:
- There are multiple replicas across different instance types and zones;
- There is an on-demand floor that guarantees the minimum traffic;
- The load balancer removes the replica as soon as the interruption notice arrives.
On Kubernetes with Karpenter, a NodePool for GPU nodes that accepts both spot and on-demand (preferring spot) looks like this:
apiVersion: karpenter.sh/v1
kind: NodePool
metadata:
name: gpu-training
spec:
template:
spec:
requirements:
- key: karpenter.sh/capacity-type
operator: In
values: ["spot", "on-demand"]
- key: karpenter.k8s.aws/instance-family
operator: In
values: ["g5", "g6", "p4d"]
nodeClassRef:
group: karpenter.k8s.aws
kind: EC2NodeClass
name: gpu
taints:
- key: nvidia.com/gpu
effect: NoSchedule
limits:
nvidia.com/gpu: 32
disruption:
consolidationPolicy: WhenEmpty
consolidateAfter: 5m
Accepting multiple instance families increases the chance of finding available spot capacity; limits prevents a misconfigured job from provisioning GPUs endlessly.
Governance: avoiding the surprise bill
- Budgets and alerts per API key or per project at the model provider.
- Per-customer limits in your product (tokens per day, requests per minute), especially on the free plan.
- Mandatory tags on GPU resources (team, project, experiment) — forgotten notebooks left running are a classic.
- Weekly review of cost per AI feature alongside quality metrics.
Checklist
- Cost calculated and recorded per call, with feature and customer
- Cost-per-resolved-task metric on a dashboard
- Prompts reviewed: less context, stable prefix for caching
- Non-urgent workloads moved to batch APIs
- Model routing evaluated with quality tests
- Spot training with a tested checkpoint (simulate an interruption!)
- GPU utilization monitored, with an alert for idle GPUs
In AI, the cheapest model is the one that solves the task at the required quality using the fewest tokens — not the one with the lowest list price.