LLM TTFT Optimization: How We Cut Time to First Token from 12s to 0.5s

    This article examines a real-world benchmark where an AI-built inference engine reduced P90 Time to First Token (TTFT) from about 12 seconds to 0.48 seconds under 16-way concurrent coding traffic, roughly a 25x improvement. It breaks down why prefill, not decoding, is the bottleneck for long-context chat workloads, and explains the key techniques behind the gain: prefix caching (KV cache reuse), chunked prefill, continuous batching and scheduling, tensor parallelism, and monitoring. Developers will find practical guidance on enabling prefix caching, structuring context for higher cache hit rates, balancing latency and throughput, and tracking tail latency.

    LLM TTFT Optimization in Practice: Cutting Time to First Token from 12s to 0.5s (25x Faster)

    1. Why “Instant Response” Has Become a Hidden Requirement for AI Apps

    AI coding tools are now deeply embedded in the daily workflow of developers. A typical scenario: you paste an error log into the chat box, hit Enter, and stare at the screen waiting for the AI’s next debugging suggestion. If that wait lasts 12 seconds, your attention has likely already drifted back to the code in your editor. But when the delay drops to 0.5 seconds, the conversation feels continuous in a qualitatively different way—the first character of the reply appears just as you finish pressing Enter.

    This difference may look small, but it directly affects the efficiency and flow state of developer-AI collaboration.

    The core metric for this “speed to first word” is Time to First Token (TTFT): the wait between sending a request and the model starting to output its first token. The industry typically uses the P90 percentile to describe the overall experience—the time within which 90% of requests begin responding.

    Why P90 instead of the average? Because the average gets pulled up by a small number of extremely slow requests, while P90 better reflects the “stall degree” felt by the vast majority of users.

    2. Background: A Benchmark for an AI-Built Inference Engine

    A recent agent benchmark, released jointly by an academic institution and industry partners, drew widespread attention. Its central question: can an AI agent build infrastructure that serves other agents?

    In one task focused on building an inference engine, the testers provided a basic server codebase, 4 high-end GPUs, and a 12-hour development window. The AI had to use an AI coding tool to write a complete inference engine from scratch. The engine needed three basic capabilities: accept user requests, schedule GPU resources to run a large model, and stream generated responses back to the client.

    The environment deliberately restricted external network access, forcing the AI to rely only on its own knowledge for system design.

    After the engine was built, the researchers went beyond code review and ran an end-to-end real workload replay. Two inference engines—one mature mainstream engine and the AI-built one—processed the same batch of 16-way concurrent real coding-session traffic on identical hardware (4 high-end GPUs) and the same model, and their core performance metrics were compared.

    3. Benchmark Results: Where the 25x Latency Gap Comes From

    The data showed a striking contrast. On the mature mainstream inference engine, P90 TTFT was about 12 seconds. The AI-built engine, under the same load, achieved a P90 TTFT of just 0.48 seconds—roughly a 25x difference.

    Even more notable: once generation began, the two engines decoded at nearly the same speed. By median, the self-built engine generated 124.2 tokens per second versus 125.0 tokens per second for the mainstream engine.

    The key takeaway: the gap is not in the “generation phase” but in the prefill phase—the wait before generation starts. In other words, the mainstream engine is not incapable of computing; rather, when a flood of concurrent requests arrives, the first token of new requests gets queued behind others, causing the long blank wait users perceive. The self-built engine’s advantage lies in efficient scheduling and resource utilization during prefill.

    4. Root Cause: Why Prefill Becomes the Latency Bottleneck

    To understand where those extra 11.5 seconds go, we need to look at the two-phase mechanism of LLM inference.

    4.1 The Essential Difference Between Prefill and Decode

    LLM text generation has two phases:

    • Prefill processes all input tokens, computes the Key/Value vectors for each position, and writes them into the GPU memory cache. This phase is compute-bound and highly parallelizable.
    • Decode generates output tokens one by one, where each step depends on the previous one. It is memory-bound, with latency constrained by memory bandwidth.

    In coding sessions, the model must re-understand the full context every turn before generating a reply, so the burden on the prefill phase is dramatically amplified.

    4.2 Input Characteristics of Real Coding Sessions

    The replayed coding sessions had a pronounced long-context profile. As the conversation progresses, historical code, error logs, and prior solutions accumulate in the input. Statistics showed that with 16-way concurrency, the median input length per request reached about 89,000 tokens.

    Such long inputs mean each request must perform nearly 90,000 forward computations to produce the first output token. Without an effective cache-reuse mechanism, this repeated computation wastes enormous compute and time.

    4.3 Prefix Caching: The Overlooked Reuse Opportunity

    Observing multi-turn conversations reveals that the first half of a new request (system prompt, prior messages, earlier code snippets) is highly identical to the previous turn; usually only a small amount of newly appended content at the end changes. For example, the user only adds “move the login button a bit to the right” at the end, while everything before it stays the same.

    The core idea of Prefix Caching (KV Cache Reuse) is exactly this: if the beginning of a new request matches a previous turn, the engine can directly reuse the already-computed Key/Value vectors, skip recomputing the shared prefix, and only run prefill on the new tokens. This mechanism sharply reduces wasted computation and is the key lever for lowering TTFT.

    5. Optimization Strategies: From Theory to Engineering Practice

    Building a low-latency inference service can be approached systematically across the following dimensions.

    5.1 Putting Prefix Caching into Practice

    Prefix caching relies on accurate matching and efficient access to the KV Cache. Engineering implementation requires attention to three points:

    1. Matching granularity: compare token-sequence prefixes segment by segment to ensure cache-hit correctness.
    2. Memory management: in long-context scenarios, KV cache usage is huge, so paged management (e.g., PagedAttention-style schemes) is needed to reduce fragmentation.
    3. Eviction policy: when memory is insufficient, evict the least-recently-used cache blocks first to protect hot prefixes.

    A simplified cache-lookup logic looks like this:

    1. def find_cached_prefix(new_tokens, cache_index):
    2. # Find the longest prefix in the cache index matching new_tokens
    3. matched_len, kv_blocks = longest_prefix_match(new_tokens, cache_index)
    4. return matched_len, kv_blocks # Only run prefill on the remaining tokens

    5.2 Chunked Prefill

    Prefilling a long input all at once causes prolonged compute occupation that blocks subsequent requests. Chunked prefill splits a long sequence into smaller chunks and completes them progressively across multiple scheduling cycles, allowing the engine to insert decode tasks or other requests’ prefill between chunks. This improves overall throughput and smooths the TTFT distribution—a classic approach to balancing latency and throughput.

    5.3 Request Scheduling and Batching Strategy

    Under concurrency, the scheduler determines the waiting experience. Common strategies include:

    • Continuous Batching to dynamically combine arriving requests and avoid waiting for a full batch.
    • Setting priorities for short or incremental requests to prevent long requests from monopolizing compute.
    • Load balancing based on input-length prediction to avoid a single very long request dragging down overall P90.

    The scheduling layer can also add timeout degradation and queue limits to keep the service stable under traffic spikes.

    5.4 Tensor Parallelism and Memory Optimization

    With a 4-GPU parallel configuration, Tensor Parallelism splits a single layer’s computation across multiple cards, shortening the compute path per token. Combined with operator fusion and quantization (e.g., weight quantization to reduce memory-access overhead), prefill time can be compressed further. In addition, properly setting max batch size and max sequence length to avoid OOM-induced request failures and retries is fundamental to meeting P90 targets.

    5.5 Monitoring and Continuous Tuning

    After launch, a solid metrics monitoring system is needed to continuously track P50/P90/P99 TTFT, decode throughput, cache hit rate, and memory usage. Combined with logging and alerting, teams can quickly spot anomalies such as dropping cache hit rates or increasing memory fragmentation, providing data support for capacity planning and parameter tuning.

    6. Practical Recommendations for Developers

    1. Enable prefix caching first. It delivers the biggest gains in multi-turn conversations, fixed system prompts, and shared codebases, typically improving TTFT by several times.
    2. Design context structure thoughtfully. Place stable, unchanging content at the front of the input and dynamic content at the end to maximize the cache-hit range.
    3. Balance latency and throughput goals. Online interactive scenarios should prioritize low latency, while offline batch processing should prioritize high throughput; set scheduling strategies accordingly.
    4. Establish a baseline and keep load testing. Use session replays that resemble real traffic for benchmarking, rather than evaluating performance with synthetic short requests alone.
    5. Watch tail latency. P90 and P99 often expose real bottlenecks, while averages easily hide long-tail problems.

    7. Conclusion

    The practice of an AI-built inference engine compressing TTFT from 12 seconds to 0.5 seconds shows that the performance bottleneck of LLM inference services usually lies not in peak compute, but in scheduling efficiency and cache reuse during the prefill phase. By reusing shared context via prefix caching, smoothing long inputs with chunked prefill, and optimizing concurrent scheduling with continuous batching—alongside quantization and a monitoring system—developers can achieve order-of-magnitude latency improvements on existing hardware.

    As agent applications demand ever more real-time interaction, low-latency inference is shifting from a “nice-to-have” to a “must-have” piece of infrastructure, and it deserves deep investment from every team building AI applications.