Agent-Built Inference Engine Cuts P90 Time to First Token to Sub-Second
A public study had an agent build an inference engine from baseline serving code under a restricted 12-hour, four-accelerator setup, then evaluated it by replaying real coding sessions at 16-way concurrency. The agent-built engine reduced P90 time to first token from about 12.03 seconds to about 0.48 seconds while median generation speed stayed near 125 token/s, pointing to prefix caching, scheduling, and prefill-path optimization as the main levers for long-context multi-turn latency.
1. Time to First Token: Why the First Character of a Reply Matters
In intelligent coding tools, fixing a login error is often not a one-turn conversation: the user pastes source code, pastes logs, edits code, runs tests again, then pastes the new logs back into the chat and waits for the model to suggest the next troubleshooting step. What shapes the experience is not only how much content the model eventually generates, but how long the user waits after pressing Enter before seeing the first character of the reply. This wait is commonly called “time to first token” (TTFT) or first-token latency.
TTFT consists of multiple stages: request queueing, input preprocessing, model prefill, sampling, and network transfer back. In long-context scenarios, prefill is often the key cost. Multi-turn sessions send chat history, source snippets, and error logs to the server together, and the model must process this input before it can generate the first token. The longer the input and the higher the concurrency, the more pronounced the long tail of TTFT becomes.
A recent public study offered a notable validation approach: in a restricted network environment, using only baseline serving code and general-purpose acceleration resources, an agent automatically wrote an inference engine responsible for receiving requests, scheduling model execution, and returning generated results. The researchers then went beyond inspecting the code and used replay of real coding sessions to test its runtime behavior. In the test, under the same hardware and model conditions, the agent-built engine reduced P90 TTFT from about 12.03 seconds to about 0.48 seconds. In the generation stage, the two engines achieved median generation speeds of about 124.2 token/s and 125.0 token/s, respectively—essentially identical.
These results indicate that the large reduction in first-token wait came mainly from starting generation earlier, not from generating faster. For developers, 12 seconds may be enough to switch back to the editor and scan a few error lines; 0.5 seconds is close to an interaction where the first token appears almost as soon as Enter is pressed.
2. Experiment Abstraction: Letting an Agent Build an Inference Service
The core of this test was not for the agent to write an isolated code snippet, but to build a runnable inference service. Abstractly, the agent had to complete the following within a time limit:
- Receive user requests and parse session context and generation parameters.
- Schedule requests to model instances on general-purpose accelerators.
- Manage long-context input and caching, and complete prefill.
- Execute decoding and continuously return generated results.
- Ensure resource isolation, queue fairness, and stability under multiple concurrent requests.
The test conditions included baseline server code, four general-purpose accelerators, and a 12-hour build window, with no internet access for research. Final evaluation used real coding-session replay: two engines ran the same model, replayed the same batch of real sessions at 16-way concurrency, and measured P90 TTFT. P90 means sorting all waits from request dispatch to the model starting its reply and taking the 90th percentile; in other words, 90% of requests begin replying within that time. Compared with an average, P90 better reflects tail experience.
In this workload, median single input reached 89,000 tokens. In multi-turn sessions, the beginning of a new request often highly overlaps the previous turn: the system prompt, history, previously pasted source code, and logs may appear again. If the engine can reuse previously computed prefix results and process only the new content, it can significantly reduce prefill work. This is the value of prefix caching and KV cache reuse.
3. Where the Latency Gap Comes From: Prefill and Prefix Caching
Model generation usually has two phases: prefill and decode. The prefill phase processes input tokens one by one to build the key-value cache needed for attention; the decode phase generates new tokens step by step based on the cache. TTFT is mainly affected by prefill and queueing, while subsequent generation speed depends more on decode efficiency, batching strategy, and hardware utilization.
In multi-turn coding sessions, the user may only add “move the login button a little to the right,” but the server still faces the full history context. If every request recomputes the entire input from scratch, a large repeated prefix is processed again and again. The basic idea of prefix caching is to reuse an existing KV cache for requests with the same model version, tokenizer version, system prompt, and prefix token sequence; the new request only needs to process the new suffix. Illustrative logic:
prefix_key = fingerprint(model_version, tokenizer_version, tenant_id,system_prompt, prefix_tokens)if cache.has_exact_prefix(prefix_key):kv = cache.load(prefix_key)prefill(kv, new_suffix_tokens)else:kv = prefill(prefix_tokens + new_suffix_tokens)cache.store(prefix_key, kv)
In engineering practice, simple hashing is not enough; exact prefix matching should be used to avoid collisions that cause incorrect reuse. The cache key should also include tenant ID, model version, and tokenizer version to prevent cross-tenant leakage or version mismatch. Eviction can combine LRU, access frequency, and GPU memory pressure. When GPU memory is insufficient, some cache can be tiered to host memory or remote storage, but the load latency trade-off must be considered.
From the test results, the agent-built engine was far ahead on P90 TTFT while its generation speed was close to the mature approach. A reasonable explanation is that its optimization focused on the path before requests enter decoding, including more aggressive prefix reuse, shorter queueing time, scheduling better suited to long contexts, and less repeated prefill. There was no order-of-magnitude difference in the generation stage, so the overall experience improvement mainly came from “speaking earlier.”
4. Engineering Implementation Points: Caching, Scheduling, and Isolation
To make similar optimizations work reliably in production, teams need to focus on the following points.
First, cache hit rate is a core metric. Long contexts and multi-turn sessions are naturally suited to prefix caching, but hit rate is affected by session structure, system prompt changes, and user editing behavior. Teams should monitor cache hit rate, prefill time, cache eviction rate, and TTFT percentiles, not just average latency.
Second, scheduling must balance fairness and throughput. 16-way concurrency is only a test scale; real systems may face hundreds of sessions. Continuous batching, priority queues, and fair scheduling can reduce short requests being blocked by long ones. For very long inputs, quotas or sharding can prevent a single request from exhausting GPU memory.
Third, multi-tenant isolation cannot be ignored. Cache keys must include tenant dimensions, and cache cleanup must be auditable. Model updates, system prompt changes, and tokenizer upgrades should trigger cache invalidation. For sensitive sessions, support disabling cross-request reuse or setting a shorter cache lifetime.
Fourth, real workload replay is more convincing than synthetic requests. Inspecting code alone or running fixed-length benchmarks can easily hide tail problems. Replaying real coding sessions covers long context, repeated multi-turn prefixes, and high-concurrency queueing at the same time. Teams can also use a container platform in a general-purpose cloud environment for resource isolation, logging and monitoring/alerting to collect TTFT percentiles, cache hit rate, and queue time, and object storage to save replay samples. For example, in general-purpose cloud environments such as Baidu AI Cloud, these general-purpose capabilities can be used to build reproducible evaluation and observability pipelines.
Fifth, an agent-built engine still needs production-grade review. An automatically generated inference service can validate an agent’s ability to build runtime systems, but before launch it still needs code review, security testing, stress testing, fault injection, and capacity planning. It is better suited as a rapid prototyping and evaluation method than as a replacement for a mature inference system without engineering governance.
5. Implications for Engineering Teams
The test offers three lessons. First, when evaluating AI interaction experience, P90 TTFT should be placed on equal footing with generation speed. Averages hide the tail, while P90 is closer to what users actually feel. Second, in long-context multi-turn scenarios, prefix caching and scheduling optimization are high-leverage ways to reduce first-token wait. No matter how fast generation is, if a request cannot enter decoding for a long time, the experience remains poor. Third, agents can not only write business code but also participate in prototyping runtime systems; however, acceptance must rely on real workload replay and observable metrics.
In the future, as sessions grow longer and concurrency rises, inference service competitiveness will increasingly depend on whether caches are reused accurately, whether scheduling is fine-grained enough, and whether the tail is short enough. Reducing TTFT from more than ten seconds to sub-second is not just a numerical change; it is a key step from wait-style Q&A toward instant collaboration.
