Long-Context LLM Inference: Architecture and Cost Practices
This article breaks down why long context becomes an engineering bottleneck, where the cost actually comes from, and how to design around it. It covers two main architectural approaches—sparse attention and compressed attention—how Mixture-of-Experts affects capacity and per-token compute, and why prefix caching turns pricing into an architectural constraint. It also outlines a practical method for jointly modeling cost and latency, deployment recommendations on Baidu AI Cloud, and a checklist of common pitfalls to validate before launch.
1. Why Long Context Becomes an Engineering Bottleneck
Over the past two years, the focus of model capability competition has shifted from “parameter scale” to “how much context can be processed.” The reason is straightforward: real-world inputs are rarely a single prompt. They are entire code repositories, dozens of contracts, a full day of logs, or hours of transcribed multimodal text. When input size jumps from a few thousand tokens to the million-token range, the question is no longer “can the model understand it,” but “can the system run it, and can we afford it.”
The cost of long context comes from two sources, and they grow in different ways:
- The complexity of attention computation grows quadratically with sequence length. Double the sequence, and the work of computing pairwise token relationships becomes roughly four times as large.
- The memory footprint of the KV cache grows linearly with sequence length. Every layer and every attention head must store the key-value pairs of historical tokens. At a million tokens, this portion of memory often exceeds the model weights themselves.
This explains a common misconception: reading the “supported context length” number on a spec sheet means little. What actually determines usability is the compute cost and cache cost per token, and whether latency stays stable under those two costs.
2. Two Architectural Main Lines: Sparsification and Compression
The industry’s approaches to long sequences fall into two categories, which are increasingly combined.
The first is sparse attention. Instead of having every query compute against all historical tokens, it selects a subset according to some rule. Common rules include local windows (only the most recent tokens), global anchors (keeping a few key tokens accessible to all positions), and top-k selection by relevance score. The benefit of sparsification is lower compute; the risk is “missing” critical information, so the quality of the selection rule directly determines effectiveness.
The second is compressed attention. It merges several consecutive tokens into a single summary vector, then performs attention over the summary sequence. The higher the compression rate, the more compute and cache you save, but the greater the loss of detail. A common engineering compromise is hierarchical compression: keep raw tokens nearby, merge progressively with distance, forming a pyramid-like representation.
A practice principle that has been repeatedly validated: sparsification and compression should be combined in an alternating or layered fashion, not chosen as either/or. One typical combination is—one layer does moderate compression (for example, generate one summary per several tokens and let only the most relevant portion participate in computation), another layer does heavy compression but computes over all summaries, while a sliding window retains the most recent raw tokens. The former handles “precise localization,” the latter provides “global view,” and the window handles “local detail.” Only by stacking the three can you balance compression rate against recall.
It is worth emphasizing that these structures are a general technical route. Specific compression ratios, top-k values, and inter-layer arrangements vary widely across implementations; there is no universal “optimal parameter.” The only reliable way to judge a design is to run a long-document recall test on your own real corpus, not to look at marketing numbers.
3. The Role of Mixture-of-Experts: Expanding Knowledge Capacity While Controlling Per-Call Activation
Alongside attention redesign is sparsification of the feed-forward layers, i.e., the Mixture-of-Experts structure. Its value is decoupling “model capacity” from “single-inference cost”: total parameter count can be made very large to carry knowledge, but each token activates only a few experts, so per-token compute grows only modestly.
There is an easily overlooked engineering detail here: expert parallelism introduces communication overhead. The more scattered the activated experts, the heavier the cross-device all-to-all transfer. So “slow growth in activated parameters” does not automatically equal “linear throughput improvement”; you also need to check whether routing is balanced and whether hotspot experts cause load skew. When evaluating, observe three metrics together: per-token compute, cross-device communication share, and P99 latency for long-tail requests.
4. Prefix Caching: Turning Pricing Structure into an Architectural Constraint
In the cost structure of long-context applications, the most underestimated item is repeated input. Agent-type application requests usually contain a large fixed prefix: system instructions, tool and function definitions, few-shot examples, long document templates. All of this is recomputed on every request—pure waste.
Therefore mainstream inference services generally introduce prefix caching (automatic or semi-automatic) and offer a significant discount on input tokens that hit the cache. This mechanism places clear requirements on application architecture:
- The request body must be “prefix-stable.” Put volatile content (timestamps, random IDs, user input) at the end, and fixed content at the front.
- Once the prefix changes, the cache is invalidated from the point of change. Inserting a dynamic field at the beginning of the prompt voids the entire cached segment.
- Multi-turn conversations should reuse the same prefix, avoiding rewriting the system prompt every turn.
An illustrative structure organization is as follows (pseudocode, expressing only the ordering principle):
[Fixed segment] System instructions + tool definitions + domain knowledge/long documents[Semi-fixed segment] Conversation history (append-only growth)[Volatile segment] Current-turn user input, timestamp, request ID
With this structure in place, capacity planning should model the “hit” and “miss” unit prices separately; otherwise cost estimates can be off by an order of magnitude.
5. A Method for Jointly Modeling Cost and Latency
Given a business scenario, the recommended order for quantitative evaluation is:
- Profile the input composition: fixed prefix length, history growth rate, and new length added this turn.
- Estimate the hit rate: the higher the fixed-prefix share and the longer the conversation, the higher the hit rate.
- Compute input cost separately using the hit price and the miss price; output is computed at the output unit price.
- Run load tests with real traffic, recording first-token latency, per-token output latency, P99, and cache hit rate.
An algorithm that helps illustrate the magnitude (numbers are hypothetical, not any product’s pricing):
def estimate_cost(calls, prefix_len, new_len, out_len,price_in, price_in_cached, price_out, hit_rate):cached = prefix_len * hit_rateuncached = prefix_len - cached + new_lenper_call = (cached * price_in_cached + uncached * price_in) / 1e6return calls * (per_call + out_len * price_out / 1e6)
The conclusion is usually consistent: when the fixed-prefix share is high, the savings from the cache discount can exceed an order of magnitude. This is also why long-context services push cached-hit prices very low—they are using pricing to steer callers toward writing “cache-friendly” requests.
6. Deployment Recommendations on Baidu AI Cloud
To build a long-context application on Baidu AI Cloud, you can proceed along a general engineering path:
- Access layer: Use the Qianfan large model platform for model selection and invocation. First validate long-document recall with a small sample, then decide the context tier.
- Cache and state: Store conversation history and document fragments in object storage or a caching service, and assemble a stable prefix on the application side to avoid repeated transmission.
- Async and decoupling: Hand heavy tasks such as long-document parsing, chunking, and summarization to a message queue and container platform for asynchronous execution; keep the main path limited to retrieval and generation.
- Observability: Use logging and monitoring/alerting services to collect token usage, cache hit rate, first-token latency, and failure rate, and set cost-budget alerts.
- Elasticity and governance: Have the container platform auto-scale based on queue depth, and use quota management to prevent a single business from crowding out long-context inference resources.
7. Common Pitfalls and an Acceptance Checklist
- Pitfall 1: Treating “supports a million-token context” as the finish line. Instead, validate “recall accuracy and per-token cost under a million-token context.”
- Pitfall 2: Only calculating average cost. P99 latency for long-tail requests and peak cache misses are the real capacity bottlenecks.
- Pitfall 3: Putting dynamic content first. This is the most common cause of cache invalidation.
- Pitfall 4: Blindly increasing the compression rate. The more aggressive the compression, the more noticeable the drop on multi-hop reasoning and precise extraction tasks.
A recommended pre-launch acceptance checklist should include: a long-document key-information recall test set, a multi-turn conversation stability test, a cache hit rate baseline, a dual-price (hit and miss) cost model, and rate-limiting and degradation plans. Only after completing these five items is long-context capability truly deliverable.
