Engineering Practices for Faster and Cheaper LLM Inference
This article presents a practical engineering methodology for speeding up large language model inference and reducing its cost without sacrificing quality. It defines measurable metrics such as TTFT, TPOT, throughput, cost per token, and task-level quality, then explains four stackable efficiency levers: sparse architectures like MoE, output length governance, prefix caching with continuous batching, and quantization with hardware-aware optimization. It also covers an integration pattern based on a unified gateway with three fallback tiers, the difference between open-sourcing model weights and open-sourcing inference frameworks, and how the same approach applies to edge and device-side deployment through device-edge-cloud collaboration. A final checklist helps teams turn these practices into measurable competitiveness.
Engineering Practices for Faster and Cheaper LLM Inference
1. The Problem: Three Trends Are Actually One Trend
Three kinds of progress have appeared in the industry recently: new-generation models that improve benchmark scores while shortening task runtime and output length; model weights and inference frameworks released under permissive licenses; and large-scale industrial capital entering the space with resource-sharing terms attached. Taken together, they point in the same direction: cheaper, faster, and easier to integrate into someone else’s product.
For developers, these three points map to three engineering metrics: cost per request, end-to-end latency, and integration effort. This article does not discuss any specific vendor’s models or pricing. Instead, it abstracts these observations into a reusable engineering methodology: how to make the inference path “thin,” resource utilization “full,” and integration cost “low” without sacrificing quality.
2. Turning “Fast” and “Cheap” into Measurable Metrics
Many teams talk about optimization without being able to say what they actually optimized. Define your metrics first, then start changing things.
- Latency: separate time to first token (TTFT) from time per output token (TPOT). Perceived responsiveness is driven mainly by these two.
- Throughput: output tokens per second, concurrent sessions, and average queue wait inside a batch.
- Cost: input and output price per million tokens, cache hit rate, and average output length.
- Quality: task-level pass rate, human spot-check scores, and regression on an evaluation set.
Illustrative metric collection logic:
# Pseudocode: instrumenting key metrics for a single requestt0 = now()first = stream.first_token_at() # TTFTtokens = 0for chunk in stream:tokens += chunk.token_counttpt = (now() - first) / max(tokens, 1) # approximate TPOTmetrics.record(ttft_ms=(first - t0) * 1000,tpot_ms=tpt * 1000,out_tokens=tokens,cache_hit=req.cache_hit, # whether the prefix cache was hit)
With clear definitions in place, you can tell whether an instant response came from a faster model, shorter output, or a cache hit.
3. Where Efficiency Comes From: Four Stackable Levers
3.1 Structural Sparsity
Sparse architectures such as Mixture of Experts (MoE) are built on one idea: a large total parameter count with few parameters activated per token. This has two engineering consequences. Memory footprint and bandwidth pressure go up, while compute per step goes down. Deployment therefore depends more on high-bandwidth memory and sensible expert-parallel partitioning than on raw compute.
3.2 Context and Output Length Governance
The experience of “thinking for a long time without producing text” is fundamentally an out-of-control output budget. Practical measures include: explicitly capping maximum output length; splitting long reasoning into two stages, conclusion first and details second; disabling deep reasoning for low-risk requests; and using structured prompts to compress redundancy. In practice, each step down in output length reduces both tail latency and cost.
3.3 Caching and Batch Scheduling
Prefix caching (reusing KV state for identical system prompts and document chunks) is highly sensitive to hit rate, and continuous batching significantly improves GPU utilization. Combined, they are the key to “more concurrency on the same hardware.”
request -> normalize (system prompt / template) -> prefix cache lookuphit -> continue computation directlymiss -> enqueue -> continuous batching scheduler -> stream response
3.4 Quantization and Hardware Adaptation
Weight quantization (such as INT8/INT4) and KV cache quantization reduce bandwidth and memory pressure. Inference-framework-level optimizations such as operator fusion and paged attention can raise throughput without changing the model. Note that quantization must be validated for quality regression on an evaluation set; benchmark numbers alone are not enough.
4. Making “Easier to Integrate” Real at the Integration Layer
No matter how capable a model is, large integration effort blocks scale. The recommended pattern is “one gateway plus three fallback tiers”:
- Unified gateway: authentication, rate limiting, metering, logging, and canary rollout all happen at the gateway, so business code faces a single internal interface.
- Three fallback tiers: on timeout, fall back to a smaller model or a cached answer; on overload, fall back to a queue with an estimated wait; on failure, fall back to rule-based handling.
- Observability loop: feed TTFT, TPOT, hit rate, and cost per request into logging and alerting, and maintain a daily dashboard.
Illustrative gateway policy:
gateway:rate_limit: {qps: 200, burst: 400}timeout_ms: 8000fallback:- cache_answer # check the semantic cache first- small_model # then fall back to a lightweight model- rule_based # finally fall back to rulesmetering: [input_tokens, output_tokens, cache_hit]
On the cloud, you can combine a container platform to host inference services, object storage for models and datasets, a message queue to smooth request spikes, and logging and monitoring services for observability. These are general capability categories and do not depend on any proprietary interface.
5. Open-Source Products vs. Open-Source Production Lines
Releasing open model weights is like handing over a finished product; releasing an open inference framework is like handing over the production line as well. The value of the latter is that a team can modify scheduling, caching strategy, and quantization schemes to match its own workload characteristics instead of being locked into a single implementation. For adopters, this means negotiating power and autonomy; for the ecosystem, it means more people can walk the path of using general intelligence more cheaply. Driving cost down and experience up is the precondition for general intelligence to become widespread.
6. Lessons from Retrofitting Old Appliances: The Same Method at the Edge
Adding LLM capability to existing hardware (old appliances, industrial control terminals) mirrors the cloud optimization logic: device-side compute is limited, so it relies more on small models, quantization, caching, and a cloud fallback. A typical path is wake-word detection and coarse filtering on the device, lightweight inference at the edge, and complex inference plus data flywheel training in the cloud, forming device-edge-cloud collaboration. The retrofit priorities are controlling power consumption and peak memory, guaranteeing offline availability, and minimizing user data uploaded.
7. Implementation Checklist
- Define your metrics before discussing optimization.
- Prioritize output length governance and cache hit rate; these show results fastest.
- Use continuous batching and quantization to raise single-machine throughput, and run quality regression.
- Unify access through a gateway with timeout, overload, and failure fallbacks in place.
- For device-side scenarios, adopt device-edge-cloud collaboration with a clear offline fallback strategy.
- Make the cost dashboard and alerting routine, not a one-off load test.
Following this path, teams can build a “low-latency, low-cost, easy-to-integrate” foundation for intelligent applications on general cloud infrastructure such as Baidu AI Cloud, turning the industry trend of “faster, cheaper, easier to integrate” into measurable competitiveness in their own products.
