Agent-Built Inference Engine Cuts P90 Time to First Token from 12 Seconds to 0.5 Seconds

    This article examines why time to first token (TTFT) often dominates perceived LLM latency in long-context, multi-turn agent workloads. It describes an experiment in which an AI agent wrote a task-specific inference engine and reduced P90 TTFT for concurrent coding sessions from about 12 seconds to roughly 0.5 seconds on the same hardware and model, while generation speed stayed largely unchanged. The article explains prefill versus decode, prefix caching, cache-management pitfalls, stage-aware scheduling, continuous batching, cache granularity, input normalization, GPU memory budgeting, and how to evaluate inference engines with P50/P90/P95/P99 latency, cache hit rate, and stage-level timing. It concludes with engineering lessons for coordinating application-layer context design with inference-layer optimization.

    In AI-assisted coding, customer service, and enterprise knowledge Q&A, users often encounter what looks like a “slower model”: after a question is submitted, the interface gives no feedback for a long time, and output begins only after ten or more seconds. Once generation starts, however, subsequent token output is not necessarily slow.

    This is usually not a sign that the model lacks generation capability. Instead, the inference system is spending a large amount of time processing the input before the request enters the generation stage. For requests that contain multi-turn dialogue, code files, build logs, and tool-call records, the factor that most affects perceived experience is often time to first token (TTFT), not tokens generated per second.

    A recent experiment on agent systems showed that when an agent does not merely call an off-the-shelf inference service but can autonomously write an inference engine for the task, the system has an opportunity to greatly reduce waiting time in long-context scenarios. Under the same hardware and model conditions, a targeted optimized engine reduced the P90 TTFT for concurrent coding sessions from about 12 seconds to around 0.5 seconds, while generation-stage speed remained basically unchanged.

    The core value of this phenomenon is not a particular system’s performance number. It demonstrates a fact: the bottleneck of an inference service may not be the model itself, but input processing, cache reuse, and scheduling strategy.

    1. Why TTFT Affects Experience More Than Total Response Time

    An LLM request can be roughly divided into two stages.

    The first stage is prefill, in which the model reads and computes the input context. The input includes system instructions, historical dialogue, code snippets, tool-call results, and the new question in the current turn. The model must perform a complete forward computation over this content before it can determine what to generate next.

    The second stage is token-by-token generation. Each time the model generates a token, it continues computing the next token based on the existing context until the answer ends.

    End-to-end latency can be approximated as follows:

    1. Total latency = queueing wait time
    2. + input prefill time
    3. + first-token generation time
    4. + subsequent-token generation time

    In short-question scenarios, input processing time is usually not noticeable. In AI coding scenarios, however, a user may submit requests over multiple consecutive turns, and each turn carries a large amount of historical context. Suppose a request contains tens of thousands or even nearly one hundred thousand tokens. Even if the user only adds a sentence such as “move the login button a little to the right,” the server may still need to reprocess a large amount of previous content.

    If this step takes more than ten seconds, users will believe the system is unresponsive, and they may click submit repeatedly, switch windows, or actively interrupt the request. By contrast, if the system can return the first token within a few hundred milliseconds, users will clearly feel that the system is “alive,” even if the complete answer still takes a long time. The continuity of interaction improves significantly.

    Therefore, when measuring LLM application performance, at least the following metrics should be considered together:

    • TTFT: the time from request submission to the return of the first token;
    • P50 latency: the median performance of typical requests;
    • P90 or P95 latency: the experience most users receive under high load;
    • Generation throughput: the number of tokens generated per second after the model starts outputting;
    • End-to-end request latency: the total time from submission to the end of the final answer;
    • Concurrency stability: whether latency deteriorates significantly as the number of requests increases.

    Among these, P90 TTFT is particularly suitable for measuring real interaction experience. It indicates that about 90% of requests can start outputting within that time, and it reflects the impact of high-latency requests on users better than simply observing the average.

    2. The Real Bottleneck: Repeatedly Computing the Same Prefix

    Multi-turn dialogue has a notable characteristic: the beginning of each turn’s request is usually highly similar.

    For example, previous turns may contain:

    1. System instructions
    2. Project directory description
    3. Historical dialogue
    4. Source code files
    5. Previous error logs
    6. Tool-call results
    7. New question for the current turn

    The next request usually adds only a small amount of content:

    1. Previous full context
    2. +
    3. New error log
    4. +
    5. New user question

    If the inference engine computes the entire input from scratch every time, it repeatedly processes a large number of unchanged tokens. This not only wastes compute resources but also causes concurrent requests to compete for GPU memory and compute capacity.

    The basic idea of prefix caching is to save the intermediate states corresponding to a common prefix that has already been computed. When the next request arrives, if its beginning is found to match a historical request, the repeated part can be skipped, and computation can continue from the changed position.

    From an abstract perspective, the computation process after a cache hit is as follows:

    1. First request:
    2. common prefix + new content
    3. -> full computation and save cache
    4. Subsequent request:
    5. common prefix + updated content
    6. -> reuse common prefix cache and compute only updated content

    What is cached here is not the final text, nor a simple string result. It is intermediate data such as key-value states produced while the model processes the context. These states are closely related to the number of model layers, the attention structure, sequence length, and data precision, so they consume a large amount of GPU memory.

    This also explains why “enabling caching” does not equal “automatic performance improvement.” If cache management is unreasonable, the following problems may occur:

    1. The cache occupies too much GPU memory, squeezing the space available for requests that are generating;
    2. Cache blocks are too small, increasing management overhead and fragmentation;
    3. A slight change in the request prefix prevents a cache hit;
    4. Concurrent requests create caches at the same time, causing GPU memory spikes;
    5. The eviction policy is unreasonable, and hot contexts are frequently invalidated.

    3. Why Agents Can Write Effective Inference Engines

    Traditional optimization is usually performed by engineers who adjust items based on experience, such as modifying batching strategy, tuning cache size, optimizing the memory allocator, or changing the request queue. When an agent participates in inference engine development, it can form a closed loop of “analyze code, run tests, locate bottlenecks, modify implementation, and verify again.”

    This type of task usually includes several steps.

    1. Read the existing server code

    The agent first needs to understand the basic structure of the server, including the request entry point, model loading, input processing, generation loop, streaming output, and exception handling. Only after clarifying the data flow and control flow can subsequent optimization avoid remaining superficial.

    2. Analyze hardware and resource limits

    The inference engine must know the number of available accelerators, GPU memory size, inter-device communication method, and concurrency limit. Different stages have different resource requirements: prefill is more oriented toward compute throughput, while token-by-token generation depends more on memory bandwidth and cache access efficiency.

    3. Build a minimal usable version

    The agent usually first implements a basic version that can receive requests, execute the model, and return streaming output, then gradually adds caching, batching, and scheduling mechanisms. The benefit of this approach is that each step has a verifiable intermediate result, avoiding problems that are difficult to locate after an overly large one-time change.

    4. Validate with real workloads

    Testing only with short questions makes it difficult to expose bottlenecks in long-context scenarios. A more effective method is to replay real coding sessions, run multiple requests concurrently, and preserve the original dialogue length, prefix similarity, and submission intervals.

    5. Iterate repeatedly based on metrics

    The system needs to record queueing time, prefill time, cache hit rate, TTFT, generation speed, and GPU memory usage. The agent can use these metrics to determine whether the performance problem comes from insufficient compute, improper scheduling, or cache misses.

    4. Key Optimization Directions for Reducing TTFT

    1. Use stage-aware request scheduling

    Prefill and token-by-token generation have different resource characteristics. If the system uses only a simple first-in, first-out queue, long-input requests may occupy compute resources for a long time, preventing short requests that are generating from being scheduled in time.

    A more reasonable approach is to divide requests into a prefill queue and a generation queue, and perform dynamic scheduling based on remaining work, waiting time, and resource usage. For interactive requests, reasonable priorities can also be set to prevent a single very long request from slowing down all users.

    2. Use continuous batching

    Traditional static batching waits for a whole batch of requests to be ready before executing them together. When request lengths differ, short requests often need to wait for long requests, and resource utilization is also affected.

    Continuous batching allows requests to enter and exit a batch at different times. When a request completes, the system can immediately add a new request, thereby improving accelerator utilization and reducing queueing wait.

    3. Optimize prefix cache granularity

    The cache can be divided into multiple blocks of fixed length. If blocks are too large, a slight prefix change can invalidate a large range; if blocks are too small, indexing, management, and metadata overhead increase.

    In actual design, a balance must be struck among cache hit rate, management cost, and GPU memory fragmentation. For highly repetitive content such as system instructions, project structure, and stable code, cache stability can be prioritized; for frequently changing logs and temporary output, they should not be retained indefinitely.

    4. Normalize input formats

    Seemingly identical contexts may fail to hit the cache if their serialization formats differ. For example, changes in field order, whitespace differences, timestamps, random identifiers, or meaningless tool states can all break the common prefix.

    Therefore, the application layer should try to:

    • Fix the system prompt structure;
    • Fix field order;
    • Place dynamic information at the end of the context;
    • Avoid inserting timestamps and random values into stable content;
    • Normalize tool output;
    • Control how historical messages are trimmed.

    5. Avoid GPU memory overcommitment

    More cache is not always better. An inference service needs to reserve space simultaneously for cache, model weights, temporary activations, and requests that are generating.

    If the system uses all GPU memory for cache, burst requests may be unable to create new generation states, ultimately causing latency jitter or even request failures. A safer approach is to set budgets for different resources and actively evict low-value cache when memory pressure rises.

    5. How to Properly Evaluate an Inference Engine

    Performance testing cannot report only “average response time,” because averages easily hide a small number of high-latency requests. It is advisable to establish a consistent testing process.

    Keep test conditions consistent

    The model, input content, hardware count, precision settings, concurrency scale, and output length should all remain consistent. Otherwise, results from different engines cannot be compared directly.

    Test both short and long contexts

    Short contexts mainly reflect basic inference capability, while long contexts better test caching and scheduling capability. Real applications also often exhibit a “long history plus short increment” request pattern, and such scenarios should be tested separately.

    Observe stage-level timing

    It is advisable to break a request into:

    1. Queue time
    2. Cache lookup time
    3. Remaining prefill time after cache hit
    4. First-token generation time
    5. Subsequent generation time

    If only end-to-end latency is observed, it is difficult to determine where an optimization actually takes effect.

    Watch tail latency

    P90, P95, and even P99 can reflect system stability under high concurrency and resource pressure. For enterprise applications, reducing the extreme waiting time of a small number of requests is often more valuable than further improving average throughput.

    6. Engineering Lessons from the Experimental Results

    First, model serving performance is not a single measure of “tokens generated per second.” In long-context, multi-turn interaction, and high-concurrency scenarios, input processing and scheduling are equally important.

    Second, agents can participate in infrastructure development, but they cannot replace complete engineering validation. They can quickly read code, propose modifications, write tests, and analyze logs, but strict correctness, stability, security, and resource isolation testing are still required in the end.

    Third, real workloads are more valuable than synthetic short text. Only by incorporating real dialogue length, context reuse rate, concurrency patterns, and tool-call processes into testing can key bottlenecks in production environments be found.

    Finally, TTFT optimization should be coordinated between the application layer and the inference layer. The application layer is responsible for reducing invalid context and keeping prefixes stable; the inference layer is responsible for caching, batching, scheduling, and GPU memory management; the monitoring system is responsible for continuously observing hit rate, latency percentiles, and resource utilization.

    For teams planning to deploy LLM applications in cloud environments, a practical starting point is logs and metrics: first confirm whether latency is mainly consumed by queueing, prefill, or generation, and then choose options such as cache optimization, request scheduling, context compression, or resource scaling. Only by establishing an observable, reproducible, and comparable testing system can TTFT optimization move beyond occasional demo effects and become a stable user experience.