LLM Inference Cost per Token: How to Calculate It and How to Bring It Down
This article explains how to calculate LLM inference cost per token, where that cost actually comes from, and how to reduce it. It covers why Prefill and Decode must be measured separately, how to define MFU correctly and avoid denominator mistakes, and why KV cache capacity sets the serving ceiling. It then maps this onto a control plane / data plane architecture with portable inference backends, compares the main optimization techniques (continuous batching, paged KV management, Prefill/Decode disaggregation, prefix and semantic caching, quantization, speculative decoding and model routing), and shows how to apply multi-hardware and multi-cloud routing plus FinOps practices such as cost tagging, budget alerts, unit-economics checks and idempotent metering. Readers will find the formulas, worked examples, reference tables and code snippets they need to turn LLM inference cost management into a measurable, attributable and repeatable engineering practice.
Start with the conclusion: capital markets price the company, engineering teams drive the cost down
When a leading model company enters its pre-IPO valuation stage, what the market actually debates is rarely the structure of a single transaction. It is the business assumptions behind the valuation: can revenue keep growing, can gross margin hold, and can compute cost stay under control? For engineering teams, the takeaway is direct: capital markets price the company as a whole, commercial products price intelligent services, and what underpins all of that pricing is the cost of every single token inside the inference stack.
LLM inference cost analysis therefore cannot stop at “the bill got bigger.” Break the problem into three layers:
- Capital pricing: growth, gross margin and the long-term cost curve;
- Commercial pricing: revenue per million tokens, plan design and margin headroom;
- Engineering pricing: cost per million tokens, resource utilization and optimization headroom.
The three layers have to close the loop: capital pricing demands a sustainable margin, commercial pricing has to cover cost and leave profit, and engineering pricing must be measurable, attributable and optimizable. This article answers three questions: how to calculate the cost per token, where the cost actually sits, and how to bring the cost per token down.
1. Cost breakdown: separate Prefill from Decode before talking about cost per token
Autoregressive LLM inference typically runs in two phases: Prefill and Decode.
- Prefill processes the input prompt in parallel and produces the first token. It is compute-intensive and drives time to first token (TTFT).
- Decode generates tokens one at a time. Each step is mostly vector and matrix math that repeatedly reads weights and the KV cache, which makes it memory-bandwidth-intensive and drives time per output token (TPOT).
Many cost problems come down to not separating these two phases. Prefill consumes compute; Decode consumes memory bandwidth. Measuring inference efficiency on peak FLOPS alone is therefore misleading — you also need effective compute utilization. The industry commonly uses MFU (Model FLOPs Utilization), the share of a GPU’s peak compute that the model actually turns into useful floating-point work during inference.
Be explicit about the denominator in the MFU formula:
MFU = effective compute ÷ (number of GPUs × peak compute per GPU)
Here, “number of GPUs × peak compute per GPU” is the aggregate peak compute of the cluster. If you are evaluating a single instance, the denominator should instead be the number of GPUs that instance occupies times the peak compute per GPU.
An example shows why the denominator definition matters. Suppose a 7-billion-parameter model is deployed as 8 independent replicas, each replica on 1 GPU, with a TPOT of 30 ms per replica. Tokens generated per second by one replica:
1000 ÷ 30 ≈ 33 tokens/s
Aggregate throughput across the 8 replicas:
8 × 33 ≈ 267 tokens/s
Estimate effective compute as “2 × parameter count × generated tokens”:
2 × 7×10⁹ × 267 ≈ 3.74 TFLOPS
If a single GPU has 300 TFLOPS peak in BF16, the 8-GPU cluster peak is:
300 × 8 = 2400 TFLOPS
So MFU is:
3.74 ÷ 2400 ≈ 0.16%
If a document reports roughly 1.2%, it usually mistook 300 TFLOPS for the aggregate cluster peak. The incorrect version looks like this:
3.74 ÷ 300 ≈ 1.25%
That is not “another definition” — it is writing the denominator as per-GPU peak instead of aggregate cluster peak. MFU calculations must state clearly whether the denominator is per-GPU peak or aggregate cluster peak.
One more distinction: 8-way tensor parallelism and 8 independent replicas are not the same throughput basis. If one 7-billion-parameter instance is served by 8 GPUs with tensor parallelism, tensor parallelism changes how much a single instance can carry and how efficiently it runs in parallel. You cannot simply multiply single-instance throughput by 8. On a per-instance basis, assuming TPOT of 30 ms:
per-instance throughput ≈ 1000 ÷ 30 ≈ 33 tokens/s
per-instance effective compute ≈ 2 × 7×10⁹ × 33 ≈ 0.47 TFLOPS
per-instance MFU ≈ 0.47 ÷ (8 × 300) ≈ 0.02%
This example shows that compute utilization in the Decode phase is typically low. The key to raising throughput is to increase the concurrent batch size within memory limits, so that each batched matrix operation amortizes the cost of reading weights.
2. Memory budget: KV cache determines serving capacity
The capacity ceiling of an inference service is usually not set by “can it run at all,” but by how many concurrent requests fit in GPU memory. Memory usage can be roughly broken into four parts:
Memory usage ≈ weights + KV cache + activations and temporary buffers + framework overhead
Weight footprint depends on parameter count and precision. For a 7-billion-parameter model:
| Precision | Approximate weight footprint |
|---|---|
| FP16 / BF16 | ~13.1 GiB |
| INT8 / FP8 | ~6.5 GiB |
| INT4 | ~3.3 GiB |
The KV cache grows with sequence length, concurrency, layer count, number of KV heads and head dimension, and it is the main variable in long-context scenarios. Per-token KV cache can be estimated as:
Per-token KV cache = 2 × layers × KV heads × head dimension × bytes per element
The “2” accounts for the K and V parts.
Assume 80 GiB of GPU memory, 5 GiB reserved, and a 32-layer model with 8 KV heads and head dimension 128 whose weights take 13.1 GiB. Available memory is:
80 − 5 − 13.1 = 61.9 GiB
The KV cache per token is:
2 × 32 × 8 × 128 × 2 = 131072 bytes, i.e. 128 KiB
So the total number of tokens that fit is roughly:
61.9 GiB ÷ 128 KiB ≈ 507,000 tokens
If each request has a 4096-token context, the theoretical concurrency is about:
507000 ÷ 4096 ≈ 123 requests
That is the throughput ceiling. Beyond it, the system either queues requests or triggers preemption and recomputation — both raise cost.
Context length effects on cost should not be treated as absolute either:
- In Prefill and attention computation, long contexts can bring close-to-quadratic growth in computation;
- In Decode, they mainly show up as extra overhead from KV cache reads, generation length and concurrency pressure.
KV cache capacity planning therefore has to account for the business scenario, average input and output lengths, and SLO targets — not a single peak number.
3. Architecture mapping: control plane, data plane and portability
Capital markets solve governance with equity, voting rights and long-term commitments. Technical systems face similar questions: who decides the model version, traffic routing and rate-limit quotas? Who owns incidents and cost? Who keeps the business running when hardware changes?
Engineering answers come in three parts.
3.1 Separate the control plane from the data plane
The control plane owns policy decisions such as model versions, routing rules, rate-limit quotas and canary releases; it optimizes for consistency and rollback. The data plane handles request processing, batch scheduling and token generation; it optimizes for throughput and latency.
Control plane changes should go through validation, canary rollout and one-click rollback. When the control plane is briefly unavailable, the data plane should keep serving under the last known policy.
3.2 Turn supply-chain relationships into a single abstraction
The inference backend should not be bound to one chip vendor or one cloud environment. A unified protocol should hide the underlying differences. Business code depends on standard interfaces for request submission, status queries and usage reporting; the actual backend can be a self-built engine, a cloud service or serverless inference.
The point of the abstraction is not to forcibly erase every difference, but to make sure upper-layer business logic is not locked into a particular implementation.
3.3 Long-termism must be measurable
SLOs, error budgets, a technical-debt ledger, model and hardware evaluations, and cost attribution mechanisms should all run continuously, like a CI pipeline. Without measurement, long-term optimization easily becomes a slogan.
4. The cost-reduction toolbox: which techniques actually lower cost per token
Cost reduction is not about stacking buzzwords; it is about making trade-offs against the actual cost structure. Here is how common inference optimization techniques compare:
| Technique | Main benefit | Main risk | Best fit |
|---|---|---|---|
| Continuous batching | Raises GPU utilization, cuts idle waiting | Complex scheduling, possible latency jitter | High concurrency, mixed request lengths |
| Paged KV management | Improves memory utilization, enables prefix sharing | Requires engine support for block tables | Long context, multi-turn conversations |
| Prefix caching | Cuts repeated Prefill cost | Complex cache key design; hit rate depends on traffic distribution | Fixed system prompts, shared long documents |
| Quantization | Reduces weight and KV memory footprint | May affect quality; needs evaluation guardrails | Tight memory, when quality has a fallback |
| Speculative decoding | Lowers Decode-stage generation latency | Unstable acceptance rate; may crowd out batch capacity | Low concurrency or latency-sensitive scenarios |
| Model routing | Lowers cost for simple tasks | Routing errors hurt user experience | Multiple model sizes coexisting |
4.1 Continuous batching: from whole-batch waiting to per-token scheduling
Static batching requires a batch of requests to start and finish together. Long requests make short ones wait, and finished short requests still occupy resources, so utilization stays low. Continuous batching schedules at iteration level: when a request finishes, its KV cache is released immediately and a new request is pulled in from the waiting queue.
In production, also pay attention to admission control, fair scheduling and preemption policy. When KV cache is scarce, prefer queueing rather than blindly admitting requests and then preempting. Interactive and batch traffic should be pooled separately. When preemption is unavoidable, prefer swapping to host memory and back rather than dropping and recomputing.
4.2 Paged KV management
Traditional KV caches pre-allocate contiguous memory for the maximum length, which wastes space when generation never fills it. Paged KV management splits the KV cache into fixed-size blocks, allocates on demand and maps logical sequences to physical blocks through a block table.
Its value is mainly threefold:
- higher memory utilization;
- support for prefix sharing;
- less memory fragmentation.
For scenarios with identical system prompts or a shared long-document prefix, prefix block sharing can substantially reduce repeated Prefill cost.
4.3 Separate Prefill and Decode deployments
Prefill is compute-intensive and Decode is memory-bandwidth-intensive, so co-locating them invites interference. A long prompt’s Prefill can block other requests’ Decode and make TPOT jittery. Deploying the two phases on separate instance groups, scaling each independently and passing KV cache over a high-speed network, lets you tune batching and parallelism strategies separately.
Whether to separate them should be decided by load testing. If long prompts are common, or the SLA demands strict TPOT stability, the benefit can be significant. If requests are generally short, KV transfer overhead may cancel out the gains.
4.4 Prefix caching and semantic caching
For “same system prompt + different user inputs,” you can cache the KV of the shared prefix and skip re-Prefill on a hit. For similar questions, a semantic cache can return historical results above a similarity threshold directly.
The cache key must combine the model version, the full context and key sampling parameters, with TTL and invalidation policies. A drop in cache hit rate usually means the cache key design or the traffic distribution has changed.
4.5 Quantization, speculative decoding and model routing
Quantization trades precision for memory and bandwidth. Moving weights from FP16 down to INT8, FP8 or INT4 reduces memory footprint and memory reads; quantizing the KV cache also increases the number of tokens that fit. Quantization, however, must be paired with quality guardrails: compare key metrics on a fixed evaluation set, pay particular attention to precision-sensitive tasks such as long text, code and math, and keep the ability to roll back quickly.
Speculative decoding has a lightweight draft model propose candidate tokens, which the target model then verifies in parallel; accepted tokens are kept as-is and rejected ones are re-sampled from the point of divergence. Correctness comes from the verification step, but the speedup depends on balancing the acceptance rate against the extra overhead. Gains are usually more visible at low concurrency; at high concurrency it may eat into batching capacity, so decide via load testing.
Model routing sends requests to different model sizes: simple tasks to small models, medium tasks to mid-size models, complex tasks to large models. The key to a cascade is designing the escalation condition — for example, escalating to a larger model for review when confidence falls below a threshold or the result fails validation rules. Routing quality sets the ceiling on cost savings; escalation conditions set the floor on quality.
5. Multi-hardware and multi-cloud: build supply-chain resilience into the architecture
Compute supply is cyclical: advanced process nodes, high-bandwidth memory and packaging capacity all affect delivery schedules. For teams running inference services long term, relying on a single hardware platform or a single cloud is itself a risk. Engineering can address this in three layers:
- Portable layer: hides hardware differences;
- Switchable layer: connects to different resource pools;
- Degradable layer: falls back to backup resources or a smaller model when primary resources are unavailable.
Control-plane-driven weighted routing can shift traffic dynamically based on cost, latency and availability. Weights must be normalized, and zero and all-zero weight cases must be handled to avoid routing anomalies.
import randomclass WeightedRouter:"""Weighted routing driven by the control plane; business code only sees the protocol, not the resource pools."""def __init__(self, backends):# backends: {name: (backend instance, weight)}self.backends = {}for name, (backend, weight) in backends.items():self.backends[name] = (backend, max(float(weight), 0.0))def pick(self):items = [(n, b, w) for n, (b, w) in self.backends.items() if w > 0]if not items:raise RuntimeError("no backend with positive weight available")total = sum(w for _, _, w in items)r = random.random() * totalfor name, backend, weight in items:r -= weightif r <= 0:return backendreturn items[-1][1]def update_weight(self, name, weight):if name not in self.backends:raise KeyError(name)backend = self.backends[name][0]self.backends[name] = (backend, max(float(weight), 0.0))
After weights are updated, they should take effect at once through a control-plane configuration snapshot, rather than letting each instance make its own random decision. A multi-cloud strategy is not simply “deploy everywhere” — keep the core portable and avoid duplicating non-core work. Before migrating, prepare a migration drill and a rollback drill checklist: can images and dependencies be built, can configuration be injected, can data be re-imported, are monitoring definitions consistent, have load tests passed, and is the rollback path clear?
6. FinOps: make cost visible, attributable and reducible
Once compute spend reaches a substantial level, cost management has to move from “check the bill at month end” to an engineered closed loop.
6.1 Tagging and allocation
The request entry point should automatically attach tags for business line, model, tenant, environment and cost center. Dedicated resources are attributed directly; shared resources are allocated by token usage or memory-occupancy duration; idle cost must also be attributed clearly.
6.2 Budgets and alerts
Set budget thresholds per project, tenant and model, and trigger tiered alerts when unit cost or spend rate goes abnormal. A sudden jump in spend rate may mean traffic growth, or it may mean a collapse in cache hit rate, abnormal calls or a change in billing definition — the responses are completely different.
6.3 A unit-economics checklist
Total bill alone cannot guide optimization; it has to be converted into comparable metrics. Use a checklist like this:
| Check item | Key question |
|---|---|
| Total cost | Does it include idle resources, cross-period charges and shared resources? |
| Effective tokens | Does it separate input, output, cache hits and failed retries? |
| Cache hit rate | Is it broken down by model version, context and sampling parameters? |
| Failed retries | Are they double-billed? Are they counted as effective tokens? |
| Billing period and tenant | Can it be decomposed by period, tenant and model? |
The core formula is:
Cost per million tokens = total monthly cost × 1,000,000 ÷ effective tokens in the month
For example, if total cost for the month is $1,000,000 and effective tokens are 20 billion (20,000,000,000), then cost per million tokens is:
1,000,000 × 1,000,000 ÷ 20,000,000,000 = $50
If effective tokens are only 2 billion (2,000,000,000), cost per million tokens becomes:
1,000,000 × 1,000,000 ÷ 2,000,000,000 = $500
Unit economics therefore has to consider total cost and effective token volume together — you cannot watch just one number.
6.4 Correctness of metering and billing
The metering layer should record each call as an immutable usage event, with billing and cost accounting sharing the same source of truth. The idempotency key should not be the request_id alone; it should include at least the request ID and the billing period, and where necessary the tenant and model, so that retries or cross-period calls do not get billed twice.
Note that you should not check whether a record exists and then write it. That “exists-then-put” pattern can race under high concurrency and bill the same request twice. A safer approach is a unique key, a transaction, or an atomic insert.
Here is an example:
import timeidempotency_key = f"{request_id}|{billing_period}|{tenant}|{model}"event = {"ts": time.time(),"request_id": request_id,"billing_period": billing_period,"tenant": tenant,"model": model,"prompt_tokens": usage["prompt_tokens"],"completion_tokens": usage["completion_tokens"],"cache_hit_tokens": usage.get("cache_hit_tokens", 0),}with db.transaction():inserted, row = db.insert_unique_or_ignore(table="usage_events",unique_key=idempotency_key,data=event,)if inserted:ledger.append(row)else:return row
The key idea: events are immutable, billing is recomputable. When pricing rules change, recompute from historical events instead of retroactively editing raw data. The official billing definition needs sign-off from finance, legal and audit to avoid invoice disputes.
7. Observability and capacity planning: decide with data, not intuition
The golden metrics for an inference service are:
- TTFT: time to first token;
- TPOT: time per output token;
- Throughput: tokens per second;
- Queue wait time;
- GPU memory usage;
- KV block utilization;
- Cache hit rate;
- Cost per request.
Interactive traffic is sensitive to TTFT and TPOT, while batch traffic cares more about total throughput and cost. When the two are co-located, large batch jobs can crowd interactive requests out of memory and compute, worsening tail latency. Pooling by SLO is therefore a prerequisite for cost optimization.
The goal of capacity planning is not to push utilization to 100% but to find the balance point between throughput and latency. Inference latency usually grows non-linearly as utilization rises: latency stays flat at low utilization, then queues stretch out rapidly near saturation. In practice, run stepped load tests and plot utilization, throughput and tail-latency curves; capacity is commonly kept around 70%–80% peak utilization, with the exact figure depending on the business SLA.
Autoscaling should not rely on CPU utilization alone. Better signals include:
| Signal | Example threshold |
|---|---|
| Queue depth | Scale out when it exceeds 2× target concurrency |
| KV cache utilization | Scale out when it stays above 80% |
| Pending tokens | Scale out while the count keeps rising |
| TTFT P95 | Investigate when above 800 ms for interactive scenarios |
| TPOT P95 | Investigate when above 50 ms for interactive scenarios |
| Cache hit rate | Alert when it drops 20% below baseline |
Also keep a warm pool, support graceful degradation, and prefer cache-aware routing that sends requests to instances with higher KV cache hit rates to avoid repeated Prefill.
8. Roadmap: from observability to governance
Stage 1: Observability
Unify request tags, collect golden metrics such as TTFT, TPOT, throughput and memory usage, and build a metering event ledger so that any request can be traced back to its cost attribution.
Stage 2: Attribution
Finish the tag allocation rules and publish dashboards for cost per million tokens and gross margin per request, so the monthly bill can be broken down by business, model and tenant.
Stage 3: Optimization
Roll out continuous batching, paged KV, prefix caching, model routing and quantization first. Introduce only one optimization at a time and measure its incremental gain, otherwise stacking changes makes attribution impossible.
Stage 4: Governance
Establish budget alerts, quota limits, multi-cloud switching and architecture decision records so that cost anomalies can be detected and localized within minutes.
9. FAQ: calculating cost per token and estimating KV cache
9.1 How do you calculate cost per token?
The basic formula is:
Cost per token = total cost ÷ effective tokens
To convert to cost per million tokens, multiply by 1,000,000. The important part is having a clear definition for both “total cost” and “effective tokens”: whether idle resources, failed retries, shared resources and cross-period charges are included, and whether input tokens, output tokens and cache-hit tokens are distinguished.
9.2 How do you estimate the KV cache?
Start with per-token KV cache:
2 × layers × KV heads × head dimension × bytes per element
Then multiply by the number of concurrent tokens and compare against available memory. A larger KV cache means fewer concurrent requests; long contexts amplify memory pressure significantly.
9.3 When should you use continuous batching?
When request lengths vary widely, concurrency is high and GPUs sit idle waiting, continuous batching usually raises throughput. But if traffic consists of short requests with extremely tight latency requirements, evaluate scheduling overhead and tail latency carefully.
9.4 What are the common billing mistakes?
Common mistakes include:
- Using only
request_idas the idempotency key and ignoring the billing period and tenant; - Retries causing duplicate charges;
- Not distinguishing cache-hit tokens from regular tokens;
- Counting failed requests as effective tokens;
- Including a large amount of idle resources in total cost, which distorts unit cost.
Conclusion: pricing ends at engineering
Capital markets price the future; engineering teams price the present. Whether it is a trillion-scale valuation or an ordinary application’s cost sheet, everything comes down to the same number: cost per million tokens.
Make LLM inference cost measurement solid, make KV cache capacity planning clear, and turn continuous batching, quantization, routing, FinOps and billing idempotency into standard mechanisms. That is how a team can actually calculate, manage and reduce cost per token.
