LLM Inference Enters the Era of the Token Factory
This article explains why effective tokens per unit cost, rather than training compute scale, is becoming the core metric for AI infrastructure. It presents a practical methodology for inference service design and optimization, covering a five-layer reference architecture, continuous batching, KV cache and prefix reuse, quantization and memory budgeting, elastic scaling, observability metrics, common anti-patterns, and a phased adoption roadmap.
Before discussing the next generation of large models, it helps to name a paradigm shift that is already underway: the core unit for measuring the value of AI infrastructure is moving from the scale of training compute to the number of effective tokens that can be reliably delivered per unit cost on the inference side. The industry abstracts this capability as the “token factory,” and calls the system built around token production, scheduling, and accounting the “token economy.” This article does not target any specific product. Instead, it offers a practical methodology for inference service design and optimization from a general engineering perspective.
1. Why Tokens Are the New Unit of Measurement
The capacity metric for traditional web services is QPS, because response sizes are relatively predictable. In LLM inference, output length is determined by both the application and the model. A single request may consume hundreds to thousands of tokens, and both the input context and the generated output contribute to billing and resource usage. This has three direct consequences:
- Per-request cost varies widely, so averages are meaningless and P50/P95/P99 percentiles are required.
- Resource usage scales roughly linearly with output length, so long-text scenarios quickly amplify memory and bandwidth pressure.
- User experience depends on both time to first token and overall generation speed, so a single metric cannot capture real quality.
Capacity planning should therefore use “tokens per second that can be reliably generated” as the base unit, while also setting limits on time to first token and maximum end-to-end latency per request.
2. Reference Architecture Layers of a Token Factory
An operable inference platform can usually be split into five layers, decoupled through explicit contracts:
- Access layer: authentication, rate limiting, request normalization, and structured output validation.
- Scheduling layer: queuing, prioritization, batch formation, and instance selection.
- Inference layer: model loading, memory management, KV cache, and decoding execution.
- Cache layer: prefix reuse, semantic caching, and result caching.
- Observability layer: metrics, logs, distributed tracing, and cost accounting.
The scheduling layer offers the largest efficiency lever. It aggregates discrete requests into batches that are friendlier to hardware and dynamically balances throughput against latency.
3. Key Engineering Techniques with Sample Implementation
3.1 Continuous Batching and Dynamic Batch Formation
Static batching waits until a batch is full, which often sacrifices latency. Continuous batching allows new requests to join at any point during decoding, and completed sequences leave immediately, significantly improving hardware utilization. Sample logic:
def schedule_step(running, waiting, max_batch_tokens):# 1) Let completed sequences exit first to free memory and slotsrunning = [r for r in running if not r.finished]# 2) Insert from the waiting queue within the remaining budget, prioritizing short requests to reduce average latencywaiting.sort(key=lambda r: r.estimated_tokens)budget = max_batch_tokens - sum(r.kv_tokens for r in running)for r in list(waiting):if r.estimated_tokens <= budget:running.append(r); waiting.remove(r); budget -= r.estimated_tokenselse:breakreturn running, waiting
In practice, you also need a maximum batch token budget, a per-request queue timeout, and a preemption policy to prevent long requests from occupying slots and causing head-of-line blocking.
3.2 KV Cache and Prefix Reuse
Multi-turn conversations, fixed system prompts, and RAG templates all contain large shared prefixes. Retaining and reusing the KV cache of a shared prefix turns repeated computation into a single computation with multiple cache hits. Key implementation points include: designing a stable prefix order (system prompt first, variables after), setting a cache capacity limit and eviction policy, and instrumenting hit metrics.
3.3 Quantization and Memory Budgeting
Using low-bit weights and KV cache compression within an acceptable accuracy loss is the most direct way to increase per-GPU concurrency. It is recommended to maintain a memory budget table that separately accounts for weights, KV cache, temporary activations, and fragmentation headroom, so capacity planning has a clear basis:
Memory budget ≈ weight footprint + max concurrent sequences × per-sequence KV size × safety factor + runtime headroom
3.4 Elastic Scaling and Cost Feedback Loop
Inference traffic has clear peaks and valleys. Triggering scale-out and scale-in based on composite metrics such as queue length and token throughput is closer to real pressure than relying on CPU utilization alone. At the same time, convert each request’s token consumption, cache hit rate, and instance duration into cost, and build a “cost per token” dashboard so optimization has a clear direction.
4. Observability Metrics
It is recommended to collect at least the following metrics with unified dimensions (model, version, tenant, scenario):
- Throughput: output tokens per second, total tokens per second.
- Latency: time to first token, inter-token interval, end-to-end latency percentiles.
- Quality: truncation rate, structured output parsing failure rate, retry rate.
- Efficiency: batch fill rate, cache hit rate, number of preemptions.
- Cost: cost per token, idle instance ratio.
5. Common Anti-Patterns
- Looking only at average latency and ignoring the long tail, leading to chronic under-provisioning.
- Increasing the maximum batch size without limit, so throughput rises but latency becomes unusable.
- Having no cache eviction policy, so hit rate decays over time without anyone noticing.
- Applying rate limiting only at the gateway while the scheduling layer has no priorities, so important workloads are crowded out by ordinary traffic.
- Lacking cost accounting, so cost reduction relies only on “gut feeling.”
6. Recommended Adoption Roadmap
Phase one: establish a baseline and observability, and define P95 latency and cost per token. Phase two: introduce continuous batching and prefix caching, which typically yields a clear throughput improvement. Phase three: optimize quantization and memory budgeting to increase per-instance concurrency. Phase four: complete elastic scaling and multi-priority queues to dynamically balance cost and experience. Each phase should be validated with metric regression to avoid local optimizations harming the overall experience.
Conclusion
The essence of the token factory is to move LLM inference from “it runs” to “measurable, schedulable, and accountable.” When teams describe capacity, latency, and cost using a unified token metric, optimization stops being a collection of scattered tricks and becomes a sustainable engineering system. With the general capabilities of cloud platforms such as Baidu AI Cloud, base components like container platforms, object storage, message queues, logging services, and monitoring and alerting can be composed into a complete inference foundation. What ultimately determines the efficiency ceiling is still the continuous refinement of batching, caching, and the cost feedback loop.
