Someone asks "is our self-hosted model cheaper than the API?" and the answer is usually a spreadsheet built from benchmark numbers. Benchmarks measure a full GPU. Production rarely runs full. The real cost per token depends on how many tokens you actually served per GPU-hour.
This post shows how to get that number from metrics you already have.
The formula
cost per 1M tokens = (GPU-hours used x hourly rate per GPU) / (tokens served / 1,000,000)
Three inputs:
| Input | Where it comes from |
|---|---|
| Tokens served | vLLM counters vllm:prompt_tokens_total and vllm:generation_tokens_total |
| GPU-hours used | Number of GPUs allocated to the model's pods x hours, from kube-state-metrics or your VM inventory |
| Hourly rate per GPU | Your cloud price sheet, reservation or internal chargeback rate. Check the current price; don't copy one from a blog |
Count GPUs that are allocated, not just busy. An idle GPU reserved for a model still costs money, and that idle time is exactly what benchmark numbers hide.
Step 1: confirm the token counters exist
Every vLLM OpenAI-compatible server exposes Prometheus metrics on /metrics on the serving port.
kubectl -n llm port-forward deploy/vllm-llama 8000:8000 &
curl -s localhost:8000/metrics | grep -E '^vllm:(prompt|generation)_tokens_total'
You should see one line per served model, labelled with model_name:
vllm:prompt_tokens_total{engine="0",model_name="llama-3.1-8b-instruct"} 1.8432e+08
vllm:generation_tokens_total{engine="0",model_name="llama-3.1-8b-instruct"} 2.91e+07
Metric labels vary by vLLM version; check your build's output and adjust the queries below. If the grep is empty, make sure Prometheus is scraping the pod (ServiceMonitor, PodMonitor or scrape annotations) and that the port is the serving port, not a sidecar.
Step 2: tokens served per hour
Counters only go up, so use increase() over a window. In Prometheus or Grafana:
# Input tokens per hour, per model
sum by (model_name) (increase(vllm:prompt_tokens_total[1h]))
# Output tokens per hour, per model
sum by (model_name) (increase(vllm:generation_tokens_total[1h]))
Keep input and output separate. Most API price lists charge output tokens at a higher rate than input tokens, so a single "total tokens" number makes self-hosting look better or worse than it is depending on your mix.
For a daily figure use [24h], or set the Grafana panel's interval to one day.
Step 3: GPU-hours allocated
On Kubernetes, kube-state-metrics exports the resource requests of every container. The NVIDIA resource name is sanitised in the label, usually to nvidia_com_gpu:
# GPUs requested by vLLM pods right now
sum(kube_pod_container_resource_requests{namespace="llm", resource="nvidia_com_gpu"})
Check the exact label value with:
curl -s http://kube-state-metrics.kube-system:8080/metrics \
| grep kube_pod_container_resource_requests | grep -i gpu | head -3
To turn allocated GPUs into GPU-hours over a day, average them over the window and multiply by 24:
avg_over_time(sum(kube_pod_container_resource_requests{namespace="llm", resource="nvidia_com_gpu"})[24h:5m]) * 24
If one namespace hosts several models, add a pod label selector or join on a model label from kube_pod_labels. If you run vLLM on plain VMs, GPU-hours is simply GPUs per VM x hours the VM was running.
Tip
If your node pools have GPU nodes that sit empty (warm spares, failed scale-down), count the whole node, not the pod request. Use your cloud bill or node count instead of pod requests when the gap between the two is large.
Step 4: put the numbers together
A short Python script pulls the three values from the Prometheus HTTP API and prints cost per million tokens per day. Set your own rates.
import requests
PROM = "http://prometheus.monitoring:9090/api/v1/query"
GPU_RATE_PER_HOUR = 0.0 # set from your price sheet or chargeback rate
NS = "llm"
def q(expr: str) -> dict:
r = requests.get(PROM, params={"query": expr}, timeout=30)
r.raise_for_status()
return {
s["metric"].get("model_name", "all"): float(s["value"][1])
for s in r.json()["data"]["result"]
}
prompt = q('sum by (model_name) (increase(vllm:prompt_tokens_total[24h]))')
output = q('sum by (model_name) (increase(vllm:generation_tokens_total[24h]))')
gpu_hours = q(
f'avg_over_time(sum(kube_pod_container_resource_requests{{namespace="{NS}",'
f'resource="nvidia_com_gpu"}})[24h:5m]) * 24'
)["all"]
total_tokens = sum(prompt.values()) + sum(output.values())
cost = gpu_hours * GPU_RATE_PER_HOUR
print(f"GPU-hours: {gpu_hours:.1f} cost: {cost:.2f}")
for model in prompt:
m_in, m_out = prompt[model], output.get(model, 0.0)
share = (m_in + m_out) / total_tokens if total_tokens else 0
m_cost = cost * share
per_m = m_cost / ((m_in + m_out) / 1e6) if (m_in + m_out) else float("nan")
print(f"{model}: in={m_in/1e6:.1f}M out={m_out/1e6:.1f}M cost/1M tokens={per_m:.4f}")
This splits GPU cost across models by token share. That's fine when models share the same GPUs. If each model has its own pods, compute GPU-hours per model instead (filter by pod label) so a busy model doesn't subsidise an idle one.
Step 5: compare with an API fairly
To compare with a hosted API, price the same token mix:
API cost = (input tokens / 1M x input price) + (output tokens / 1M x output price)
Take the prices from the provider's current price page for the model you would actually use. Then add the costs that self-hosting has and the GPU number doesn't show:
| Hidden cost | How to estimate |
|---|---|
| Idle and spare capacity | Already in GPU-hours if you count allocated GPUs |
| Engineers' time for upgrades, on-call and incidents | Hours per month x loaded rate |
| Storage and egress for model weights and images | Cloud bill line items |
| Load balancers, monitoring, logging | Cloud bill line items |
| Evaluation runs when you change model or vLLM version | GPU-hours of the eval jobs |
Warning
Don't decide on one day of data. Use at least two full weeks so weekends, month-end peaks and batch jobs are included. A model that is cheap at peak can be expensive across a quiet weekend if the GPUs stay allocated.
Reading the result
| What you see | What it usually means | What to try |
|---|---|---|
| Cost per 1M tokens drops sharply at peak hours | Throughput is fine; you pay for idle off-peak | Scale replicas to demand, or move batch work into off-peak |
| Cost is high even at peak | Low throughput per GPU | Check batching limits, prefix caching, quantization; see vLLM throughput tuning |
| One model dominates GPU-hours with little traffic | Over-provisioned or a forgotten deployment | Scale it down or consolidate it with another model |
| Output tokens far exceed input | Long answers or reasoning output | Cap max_tokens, ask for concise answers |
Prevent it next time
- Add a Grafana panel with tokens per GPU-hour and cost per 1M tokens per model, and review it in the weekly ops meeting.
- Alert when tokens per GPU-hour falls below an agreed floor for a full day; it usually means idle capacity or a stuck scale-down.
- Label every GPU workload with a
modelandteamlabel so cost can be split without guesswork. - Recalculate after every vLLM upgrade, model change or quantization change, since throughput and therefore cost move with each.
Get the weekly HubDatAI email
One email a week with everything new: posts, learning sessions and videos. Free, no spam, unsubscribe in one click. What you get