ELLMEngineering Large
Language Models
Download PDF

Chapter 26

Serving Engines and Cache Backends in Practice

On this page

A serving engine decides which tokens to compute next, where their state lives, and how the result reaches the caller. Learn those boundaries before comparing framework names or launch flags.

Consider a multi-tenant generation service using the running configuration. Its first deployment works, but p99 first-token latency degrades as more tenants arrive. A team proposes switching to SGLang; another proposes adding a remote cache to vLLM. Both could help, and neither proposal identifies the bottleneck. A cold-prefix workload, a CPU scheduling gap, and an overloaded decode pool require different interventions.

The implementation notes reflect primary documentation checked September 13, 2026. Pin the engine release and backend; current documentation and older blog posts may describe different architectures.

Place each component at the right layer

A representative engine path, not a required process layout. Left-hand arrows show forward dispatch; result and stream-return paths are omitted. Iteration scheduling and state management drive execution. An optional connector exchanges remote state without bypassing admission or granting execution ownership.
Open full diagram ↗

A representative engine path, not a required process layout. Left-hand arrows show forward dispatch; result and stream-return paths are omitted. Iteration scheduling and state management drive execution. An optional connector exchanges remote state without bypassing admission or granting execution ownership.

An engine such as vLLM or SGLang owns iteration-level request execution. A kernel library such as FlashInfer implements operations that an engine can call. A cache system extends where reusable state can live. A fleet layer places replicas, routes requests, and may coordinate disaggregated pools. These responsibilities can coexist in one project, but they are not interchangeable.

For example, replacing an attention kernel does not supply tenant admission, and adding remote KV storage does not choose a legal destination sharding plan. Trace the API, scheduler, cache manager, model runner, and output path separately. For every boundary, record the input identity, state owner, completion signal, and cleanup behavior.

vLLM: follow an iteration through the engine core

vLLM's V1 architecture separates request/API processing, an engine core responsible for scheduling and KV management, and workers that execute the model. CPU allocation therefore matters even when the model runs on GPUs. The exact process count depends on the deployment; do not infer it from GPU count alone. Start with the vLLM architecture overview.

At the beginning of an iteration, the engine knows each request's computed positions and remaining work. The scheduler chooses a bounded amount of work and obtains space for the resulting state. The model runner translates that decision into tensors, attention metadata, and execution calls. Results advance request state, feed token selection and output handling, and eventually allow finished or cancelled requests to release resources. This is a useful reading model, not a promise that all stages execute synchronously or in one process.

The V1 scheduler interface makes the schedule/update boundary explicit. When investigating a regression, save the scheduled token counts and request IDs along with the model-runner timing. A fast forward pass cannot explain a long queue without this context.

vLLM's automatic prefix cache uses block identities that include prior-prefix identity, tokens, and relevant extra identity such as adapters or multimodal inputs. Full reusable blocks are looked up and referenced through the KV manager. The important distinction is between an unused block that still contains reusable content and a block that is safe to overwrite. Reference counts and allocation transitions decide that, not merely a successful hash lookup. See the prefix-caching design.

Suppose two 2000-token prompts share the first 500 tokens, and a simplified cache reuses only complete 16-token blocks. The reusable prefix is 496 tokens, leaving 1504 positions to process in the second prompt. The remaining four shared tokens do not form a complete reusable block in this example. This saves prompt work; it does not remove the new request's decode steps or its attention reads over the prefix. Real engines may impose additional alignment and last-token-logit requirements, so measure usable cached positions rather than string-prefix length.

SGLang: radix reuse and overlapped execution

SGLang's RadixAttention organizes reusable token prefixes as a radix tree: common paths share prefix state, and divergent suffixes branch. Tree matching, active-reference protection, eviction, and scheduling must agree about which state can be reused. This makes branching conversations and repeated prompt prefixes useful cases to study, but does not establish a performance advantage over every hash-based cache. See the SGLang paper.

The project also describes an overlap scheduler that prepares the next batch while device computation is in flight. Dependencies on not-yet-returned tokens are represented and resolved through the execution pipeline. The mechanism hides eligible CPU work; it does not make scheduling free or remove synchronization requirements. The SGLang overlap-scheduler explanation is a useful historical design reference, not a current cross-engine benchmark.

For an illustrative steady-state pipeline with 2 ms of preparable CPU work and 5 ms of GPU work, serialized execution costs 7 ms per iteration. Ideal overlap approaches 5 ms after filling the pipeline, a 1.4x improvement, before accounting for dependencies and communication. If the GPU work instead takes 20 ms, the same saved 2 ms matters much less. Inspect the timeline; do not borrow a release blog's speedup for a different model.

SGLang's HiCache adds a hierarchy spanning device cache, host memory, and external storage. Its design exposes prefetch and write-back choices, including selective write-through and eviction-time write-back. Those policies trade saved future computation against bandwidth and storage pressure. A high storage-hit rate can still lose if fetching delays the critical path. Read the HiCache design with the earlier transfer-versus-recompute model beside it.

TensorRT LLM: qualify the backend before following a tutorial

TensorRT LLM is another engine candidate for NVIDIA deployments. Its name is not sufficient to identify the execution path. The current migration guide states that the TensorRT engine backend has been removed and PyTorch is the sole execution backend, with AutoDeploy built on it. Older tutorials that convert a checkpoint and run trtllm-build describe an earlier path. See the backend-removal migration guide.

The PyTorch architecture overview identifies a scheduler, a model engine for a forward step, and a decoder for token generation. Use those roles to compare with vLLM and SGLang rather than assuming identical class boundaries. The same model name can take a different attention, quantization, or collective path depending on hardware and enabled features. Require evidence for the feature combination, not just a check mark for each feature separately.

Kernel libraries, cache systems, and fleet layers

FlashInfer supplies inference kernels and attention interfaces; its KV-layout tutorial explains how page tables and ragged metadata describe noncontiguous state. An engine remains responsible for allocating pages and supplying valid metadata. Planning and running a kernel are not substitutes for request scheduling or safe eviction.

The cache ecosystem is best read by responsibility:

Project Useful implementation focus Boundary to investigate
LMCache Reuse and movement across KV storage tiers Connector semantics, cache identity, and load/store completion
Mooncake KV-centric serving and a transfer/storage substrate Registration, transfer lifecycle, failure, and placement
Dynamo Distributed serving, KV-aware routing, and phase pools Worker events, routing staleness, and destination admission
llm-d Kubernetes-oriented distributed inference composition Scheduling, cache indexing, worker compatibility, and operations

These are overlapping projects, not four interchangeable plugins. Use the LMCache repository, Mooncake repository, Dynamo repository, and llm-d repository to find their supported integrations. For a first deployment, introduce one additional boundary at a time. A local engine baseline should work before remote caching or phase disaggregation is credited with improving it.

A comparison that can change the decision

The candidate set changes for a local or edge product. llama.cpp provides a C/C++ inference stack with CPU execution, Apple Metal, and other accelerator backends, including mixed CPU/GPU placement. It belongs in a laptop or constrained-device investigation even when a datacenter comparison centers on vLLM and SGLang. Backend availability does not imply identical model, operator, or quantization support.

For a local documentation assistant, measure first load, sustained token cadence, memory pressure, power/thermal behavior, and offline retrieval alongside answer quality. Moving work to the user's device changes the privacy and connectivity boundary, but does not automatically secure downloaded weights, local indexes, or outbound tools. Keep this experiment separate from a multi-tenant server benchmark; their concurrency and failure requirements differ.

Select candidates that support the service's actual checkpoint, attention variants, precision, hardware, and API behavior. Start with two engines, not every combination of engine, transport, quantization, and cache tier. Keep weights, tokenizer, chat template, stop rules, output limits, sampling policy, and offered request trace fixed. Equal-looking API requests can otherwise become different token sequences or different tasks.

Run two kinds of comparison. A controlled comparison holds the relevant resource and semantic choices fixed to isolate a mechanism. A deployment comparison lets each engine use its best supported configuration under the same hardware budget, quality limits, and service objectives. Report which you ran. One measures an intervention; the other chooses a system.

For this service, include at least cold prefixes, repeated system prefixes, diverse tenant namespaces, long prompts mixed with short requests, and cancellation under load. Record offered, admitted, failed, cancelled, and completed requests. Sweep arrival rate until the p99 first-token and token-gap targets fail; report goodput and failure reserve, not just peak output tokens per second. Rerun the best configurations with one worker group unavailable and with cold replacements joining.

A result table should identify why a candidate wins or fails:

Observation Next check Possible conclusion
High cache hits, unchanged TTFT Queue, usable hit tokens, transfer wait Cache is not the controlling bottleneck
Faster model steps, slower responses CPU/output path, batching, network flush Kernel gain is lost outside the model runner
Better warm throughput, poor scale-out Compilation, loading, graph warm-up Recovery or readiness costs need mitigation
Good averages, one tenant regresses Shape mix, priority, cache locality Aggregate throughput hides unfair allocation

Read the implementation with a question

Choose one short request and follow five events: admission, prefix lookup, slot allocation, one execution step, and release. Then repeat with cancellation after dispatch and with an allocator miss. Keep a small trace of request state, page ownership, and pending operations. This exposes more than reading the repository top to bottom.

For vLLM, start at the architecture overview, then the scheduler interface and prefix-cache design linked above. For SGLang, pair the RadixAttention paper with the overlap and HiCache explanations. For TensorRT LLM, start with the current migration guide before the executor architecture. Once the engine path is clear, inspect the chosen kernel library or connector. Read source from the release actually deployed; a current design document can be ahead of a stable package.

Design Exercises

  1. A benchmark reports an 80 percent prefix hit rate but no TTFT gain. Which measurements are missing?
  2. Two engines return different outputs with temperature zero. Does that prove one is incorrect?
  3. An engine reports faster GPU steps after enabling overlap, but cancellation leaks KV pages. What boundary is broken?
  4. When should the service add a remote cache rather than switch engines?

Worked Solutions

1. Count saved work, not only matches

Ask whether the rate counts requests, blocks, or tokens and whether those hits are usable under the actual layout. Split TTFT into queue, lookup/fetch, uncached prefill, sampling, and output delay. A warm 500-token prefix in a long request can be a hit while saving little work; a remote hit can arrive too late to help. Compare with recomputation under the same offered load.

2. Establish the same task first

Compare tokenized inputs, templates, stop behavior, precision, and logits on controlled prompts. Greedy decoding can diverge at a nearly tied logit because floating-point reduction order differs. Use numerical tolerances and task-level quality evidence rather than require every continuation to match. Large logit discrepancies, mask errors, or different serialized prompts need investigation before performance claims are accepted.

3. Separate cancellation from physical reuse

The request can stop producing output before all device work that references its pages has completed. Mark it cancelled, prevent further scheduling, and release physical resources only after the relevant completion/fence and references are resolved. Test cancellation at each pipeline stage. Overlap expands the set of in-flight owners; it does not weaken the allocator's lifetime contract.

4. Test the reuse hypothesis

First show that reusable prefixes are being recomputed and that recomputation materially contributes to the service bottleneck. Measure their reuse distance, byte volume, and transfer path. If the working set fits locally, improve local allocation or routing first. If useful state exceeds local capacity and retrieval beats recomputation within the SLO, evaluate a compatible remote cache. If the bottleneck is scheduling or an unsupported kernel, remote storage addresses the wrong problem.

The output of this chapter is a reproducible engine decision, including the losing configurations and the reason they lost. Part IV opens the next boundary: how the model runner's operations become a schedule over accelerator memory and execution resources.