How an AI Agent Built an Inference Engine That Cut Time-to-First-Token from 12s to 0.48s

    A recent experiment had an AI agent build an inference engine from scratch under constrained conditions. When tested with real multi-session coding replays on identical hardware and models, the agent-built engine achieved a P90 time-to-first-token of about 0.48 seconds, compared to roughly 12 seconds for a mature inference engine, while decoding throughput stayed nearly identical. This article breaks down where that gap comes from—prefill, caching, and scheduling—and explains the key engineering designs behind cache-aware inference engines, along with evaluation methods, boundaries, and risks.

    1. The Real Cost of Waiting for the First Token

    In real-world coding assistance, user interaction with AI is rarely a single question-and-answer exchange. It is typically multi-turn debugging: paste an error, modify code, re-run, then paste new logs. Each request may carry the system prompt, tool descriptions, conversation history, source code snippets, and the latest logs. When the context reaches tens of thousands of tokens, the model must finish processing the entire input before it can emit the first token. What users actually perceive is not backend throughput, but the wait between pressing Enter and seeing the first character appear.

    If P90 first-token latency reaches about 12 seconds, it means roughly one in ten requests waits more than 12 seconds before a reply even begins. For high-frequency interaction, this is enough to push users back to their editor to re-read logs, clearly breaking the interaction rhythm. Related research using real coding session replays found that under multi-session concurrency, the median single input reached approximately 89,000 tokens. At that scale, waiting for the first token becomes a critical experience metric.

    2. Experimental Design: Letting an Agent Build and Validate an Inference Engine

    A research team had an AI agent build an inference engine in a restricted environment: it was given basic server code and multiple accelerator cards, limited access to online references, and required to complete, within a set time, an engine capable of receiving user requests, scheduling accelerators to run the model, and returning generated responses. Validation was not based on code completeness, but on measuring performance directly against real coding session replays.

    The test used identical hardware and the same model, running both engines against the same batch of concurrent real coding sessions. The core metric was P90 time-to-first-token (TTFT): the wait time from request submission to the model starting its reply, sorted across all requests, with the 90th percentile marking the point where 90% of requests begin responding within that time. The results showed the mature inference engine at roughly 12 seconds, while the agent-built engine achieved about 0.48 seconds. Once generation started, however, median decoding speeds were nearly identical: about 124.2 token/s versus 125.0 token/s. This indicates the gap occurs almost entirely “before the first word,” not in the decoding stage.

    3. Breaking Down First-Token Latency: Prefill, Caching, and Scheduling

    First-token latency typically consists of request queuing, prefix processing and prefill, scheduling, first-step decoding, and network return. Among these, prefill computation grows with input length, so long contexts significantly extend this step. A defining characteristic of multi-turn coding sessions is heavy prefix repetition: system prompts, tool descriptions, historical messages, and prior source code have usually appeared in previous turns, and a new turn only adds something like “move the login button a bit to the right.”

    This is where prefix caching delivers value. The engine can store previously computed intermediate states; when a new request’s prefix matches the cached history, it reuses existing results and computes only the new tokens. Hit conditions are usually strict: system prompts, tool descriptions, message history, model versions, and similar elements must remain consistent; any prefix change may invalidate the cache. A custom-built engine can combine cache-aware routing, tiered caching, continuous batching, chunked prefill, and prefill-decode resource isolation to improve hit rates and reduce queuing time.

    The roughly 11.5-second gap, therefore, is not a single-point “magic trick” but the combined result of multiple engineering efforts: cache hits eliminate redundant prefill, scheduling strategies reduce queuing, memory management reduces jitter, and multi-card parallelism increases effective compute. It is equally important to recognize that on a cache miss, full prefill is still required—so the benefit of any single optimization should not be overstated.

    4. Engineering Implementation: Key Designs of a Cache-Aware Inference Engine

    4.1 Request Normalization and Session Affinity

    Normalize the system prompt, tool definitions, and message history to generate a stable prefix key; route requests from the same session to nodes that already hold the corresponding cache, reducing cache fragmentation and cross-node redundant computation. In multi-tenant scenarios, tenant isolation and permission checks must also be added to prevent cache cross-contamination.

    4.2 Tiered Caching and Incremental Prefill

    Cache can be segmented by system prompt, tool descriptions, historical turns, and source code snippets, with capacity limits, eviction policies, and version-based invalidation. When the model version or prompt template changes, related cache entries should be actively invalidated. Only new content needs incremental computation, avoiding repeated prefill of the entire context.

    4.3 Continuous Batching and Chunked Prefill

    Long prefill requests can block short ones. Splitting prefill into multiple chunks and interleaving them with decode requests reduces queuing time for short requests. Priority, quota, and timeout policies should also be configured to prevent hot sessions from monopolizing resources.

    4.4 Prefill and Decode Resource Isolation

    Prefill and decoding have different compute and memory requirements. Allocating separate resource pools or time slices for each reduces decode jitter and keeps requests already in the generation phase producing output stably.

    4.5 Multi-Card Parallelism and Topology Awareness

    Cache sharding strategies should match parallelism strategies to reduce cross-card communication overhead. Hot prefixes can be replicated across replicas, but memory footprint and consistency costs must be weighed.

    4.6 Observability and Degradation

    Collect P50/P90/P99 first-token latency, cache hit rate, queue time, prefill duration, decode throughput, and error rates. When caches invalidate or the system is overloaded, degrade to conservative scheduling, prioritizing correctness and availability. Illustrative pseudocode:

    1. def handle(req):
    2. prefix = normalize(req.system, req.tools, req.history)
    3. key = stable_hash(prefix)
    4. state = cache.get(key)
    5. if state is None:
    6. state = prefill(prefix)
    7. cache.put(key, state)
    8. state = prefill(req.new_tokens, state)
    9. return decode(state)

    In production implementations, version numbers, tenant isolation, permission checks, timeout handling, and cache eviction policies must also be added.

    5. Evaluation and Validation: Real Session Replays over Single Microbenchmarks

    First-token latency optimization cannot be judged by microbenchmarks on single requests. A more reliable approach is replaying real sessions while distinguishing cold starts from warm caches, and reporting cache hit rates, concurrency levels, and input length distributions. Acceptance testing should run A/B comparisons on identical hardware and models, while observing P90/P99 first-token latency, generation throughput, output consistency, error rates, and resource utilization.

    Fairness also deserves attention: cache-aware routing can create hotspots, requiring tenant quotas and global scheduling; long-context caches consume substantial memory, requiring tiered storage and eviction mechanisms; multi-tenant caches must be properly isolated to prevent cross-permission reuse. Establishing a closed loop of logging and monitoring alerts is essential to determine whether optimizations truly improve end-to-end experience, rather than merely shifting overhead elsewhere.

    6. Boundaries and Risks

    While prefix caching brings benefits, it also introduces consistency and security boundary issues: caches must be invalidated when model versions, system prompts, or tool descriptions change; multi-tenant scenarios must not reuse caches across permission boundaries; long-context caches may create memory pressure; and hot sessions may affect overall fairness. Agent-built inference engines are better suited to scenarios with well-characterized workloads, high session repetition, and controllable deployment and replay. Mature general-purpose inference engines still hold advantages in ecosystem, stability, and feature coverage—the two are not a simple substitution relationship.

    7. Conclusion

    First-token latency is an end-to-end engineering problem involving prefill, caching, scheduling, resources, and observability. The case of reducing latency from roughly 12 seconds to about 0.48 seconds shows that cache-aware and scheduling optimizations targeting real session workloads can dramatically shorten the wait for the first token while keeping generation throughput stable. For production deployment, enterprises should first establish a reproducible replay benchmark, then identify bottlenecks, and gradually introduce prefix caching, continuous batching, resource isolation, and monitoring/alerting—ultimately balancing experience, cost, and correctness.