LLM Inference Engine Optimization: Cutting Time to First Token from 12 Seconds to Half a Second
This article explains how an LLM inference engine reduced P90 time to first token (TTFT) from about 12 seconds to 0.478 seconds in a 16-concurrency, multi-turn coding benchmark. It covers the prefill bottleneck, prefix caching, KV cache memory management, request scheduling, and cloud deployment practices.
When developers use AI for coding, they often run into a frustrating problem. You paste an error log and part of the source code into the chat window, add a simple request such as “move the login button a bit to the right,” and press Enter. Then you stare at a blank screen for more than ten seconds before the AI produces its first character. This idle waiting time breaks developers’ concentration. Recently, a joint research team studying whether agents can build agents found that aggressive optimization of an inference engine can reduce the time to first token (TTFT) of a large model from about 12 seconds to 0.48 seconds. This article analyzes the technical principles and engineering practices behind this optimization.
1. Measuring TTFT and Identifying the Pain Point
When evaluating LLM inference services, TTFT is one of the core metrics that determines user experience. It measures the time from when a user sends a request to when the model outputs the first valid character. In real-world high-concurrency scenarios, the industry usually uses P90 TTFT, the 90th percentile, to measure service stability. In other words, 90% of requests start receiving a response within this time.
In multi-turn coding sessions, developers often carry a large amount of conversation history. Test data shows that with 16 concurrent sessions, the median input for a single request can reach 89,000 tokens. With an input this large, an unoptimized inference engine can push P90 TTFT above 10 seconds. After 12 seconds, a user may have already switched back to the editor to look for other clues. A response in 0.5 seconds, by contrast, means feedback appears on screen the moment the user presses Enter.
2. Prefill Bottleneck: Where the Latency Comes From
LLM inference typically has two stages: prefill and decode.
- Prefill stage (compute-intensive): The model processes all input tokens, computes the self-attention mechanism, and generates the KV (key-value) cache for each layer. This stage involves large-scale matrix multiplication, and its computational complexity grows quadratically with the number of input tokens. For an input of 89,000 tokens, prefill consumes a large amount of compute and time. This is the root cause of high TTFT.
- Decode stage (memory-bandwidth-intensive): The model generates subsequent tokens one at a time, based on the KV cache already produced. Because each step computes only one token, the main bottleneck is GPU memory bandwidth.
Conventional inference engines recompute prefill for all input tokens in each new turn of a multi-turn conversation, even when most of the context is identical to the previous request. This wastes a large amount of computation.
3. The Core Fix: Prefix Caching
Cutting the ten-plus seconds of waiting for the AI’s first token depends mainly on optimizing the prefill stage. The key technique is prefix caching.
1. How prefix caching works
In a multi-turn conversation, the system prompt, the conversation history, and the source code provided earlier do not change in the current turn. If the model already computed the KV cache for these tokens during the previous request, the engine can reuse those cached results. In the current turn, it runs prefill only on the small number of new tokens, such as “move the login button a bit to the right.” This is prefix caching.
2. Computation saved
Suppose the history contains 89,000 tokens and the current request adds 10 new tokens. Without prefix caching, the engine must recompute attention over roughly 89,000 tokens. With prefix caching enabled, the engine reuses the historical KV cache and computes only the 10 new tokens and their interaction with the prefix. This reduces the prefill computation by thousands of times, which produces a sharp drop in TTFT.
4. Benchmark Results and Verification
In the benchmark, researchers gave agents a basic server codebase and multi-GPU high-performance computing resources. Within a time limit, the agents had to write an inference engine that receives requests, schedules compute, and returns results.
Internet access for looking up reference material was restricted, so the agents relied entirely on their own understanding of low-level technology. The researchers then replayed the same set of real 16-concurrency coding sessions to test each engine. The results were as follows:
- Conventional, mature open-source inference engine: Under the same hardware and model conditions, P90 TTFT was about 12.029 seconds.
- Agent-built optimized engine: P90 TTFT was only 0.478 seconds.
- Decoding speed: Once a response starts, both engines generate tokens at nearly the same speed. By median, the agent-built engine generated 124.2 tokens per second, while the conventional engine generated 125.0.
These results show that the optimized engine did not sacrifice output quality or generation speed after the response started. It removed about 11.5 seconds of wasted waiting in the prefill stage.
5. Engineering Practices for Efficient Prefix Caching
To reuse prefix caches within millisecond-level latency in production, an inference engine must solve several engineering problems.
1. Cache matching and hash indexing
To quickly determine whether a request hits the cache, the engine typically computes hashes over the input token sequence. It can hash the tokens block by block, for example every 16 tokens per block, and organize the hashes in a tree index. This lets the engine quickly find the longest common prefix.
# Pseudocode: prefix cache lookup logic based on token blocksdef find_prefix_cache(input_tokens, cache_tree):current_node = cache_tree.rootmatched_blocks = 0for i in range(0, len(input_tokens), BLOCK_SIZE):block = tuple(input_tokens[i:i+BLOCK_SIZE])block_hash = hash(block)if block_hash in current_node.children:current_node = current_node.children[block_hash]matched_blocks += 1else:breakreturn matched_blocks * BLOCK_SIZE
2. Memory management and LRU eviction
The KV cache takes up a large amount of GPU memory. When memory runs low, the engine must evict older cache entries using a policy such as LRU (least recently used). To avoid memory fragmentation, engines often use paged memory management, such as PagedAttention, which divides the KV cache into fixed-size blocks for allocation.
3. Cross-request scheduling
In a 16-concurrency setting, multiple requests may share part of their prefix, such as the same system prompt. A strong inference engine can share cache entries across requests. This reduces memory usage and improves overall throughput.
6. Deployment Considerations for Cloud Infrastructure
In enterprise deployments, optimizing a single-node inference engine also requires integration with cloud infrastructure. On Baidu AI Cloud, the container platform and GPU compute services can be used to build a highly available, elastic inference cluster.
- Memory-aware scheduling: Use the monitoring, alerting, and log services on Baidu AI Cloud to track GPU memory usage and cache hit rate on each inference node in real time. When high concurrency increases memory pressure, trigger horizontal pod autoscaling (HPA) to route requests to new nodes. This avoids performance fluctuations caused by frequent cache eviction.
- Affinity scheduling: For multi-turn conversations, consider session affinity at the load balancing layer. This ensures that consecutive requests from the same user reach the same inference node. It maximizes the prefix cache hit rate and reduces the network overhead of fetching cache across nodes.
7. Conclusion
Optimizing LLM inference is more than an algorithmic achievement. It also reflects strong low-level systems engineering. The drop from 12 seconds to 0.5 seconds comes from identifying and eliminating redundant prefill computation in long, multi-turn contexts. Mature prefix caching, paged memory management, and efficient concurrency scheduling, supported by elastic compute from cloud infrastructure such as Baidu AI Cloud, can help developers build real-time AI applications with millisecond-level response times and a smoother interaction experience.
