ByteCosts
vllm-vs-sglang-prefix-caching.mdx

AI Coding Agents

vLLM vs SGLang prefix caching for self-hosted agents

vLLM Automatic Prefix Caching finds reusable key and value tensors by hashing full token blocks together with their preceding context. SGLang’s RadixAttention, as described in its paper, indexes token sequences in a radix tree and prioritizes requests with longer matched prefixes. Compare both using your branch patterns, tenant boundaries, and latency under memory pressure.

What each design preserves

The same coding agent can produce several patterns of shared input. Independent sessions may share the system prompt. Turns in a session may share the system prompt, the same initial user request, and the growing history. Forks may share a long run of tool results and diverge only at the decision point. In each pattern, the serving engine can save prefill work by retaining tensors for a prefix that another request can use. The KV cache internals guide covers how the tensor footprint grows with retained tokens.

Design choicevLLM Automatic Prefix CachingSGLang RadixAttention as described in the paper
LookupHash of each block’s tokens, parent hash, and extra keysRadix tree mapping token sequences to KV tensors
Match boundaryLongest cached run of full blocks at the beginningLongest matching path through retained token sequences
Reclaimable stateLeast recently used block at the head of the free queueLeast recently used eligible leaf
Active requestsBlock references keep in-use blocks out of the free queueNode references protect the paths in use
Branching workloadShared complete blocks match until the first unmatched blockCommon ancestors are shared and branch suffixes can be reclaimed as leaves
Scheduling interactionManager looks up blocks when allocating a request’s slotsPaper’s cache-aware policy prioritizes longer matches among waiting requests

These designs address both how an engine recognizes the same prefix and what it retains after a request finishes. Those are separate checks when diagnosing a miss. A shared prefix can be eligible for lookup, yet gone by the time its next branch comes through.

How vLLM identifies a reusable block

As of November 30, 2026, vLLM’s configuration documentation lists enable_prefix_caching as enabled by default. The Automatic Prefix Caching feature guide describes setting it to True. Check the effective setting when replaying a workload, especially when comparing runs made with different configurations. The design documentation specifies sha256 as the default and recommends sha256_cbor when hashes need to reproduce across environments.

A block’s lookup identity combines the parent hash, the exact token IDs in that block, and any extra keys needed to distinguish the state, such as a LoRA ID or hashes for multimodal inputs. The parent hash ties each block to all the preceding tokens. If an agent edits a token in the middle of the prompt, vLLM can reuse the earlier full blocks. The first affected block gets a different identity and so do the blocks that descend from it, even where the later tokens happen to be unchanged.

For a worked example, suppose a deployment uses a block size of four tokens, the size chosen for an example in vLLM’s design docs. Two requests have a ten-token common prefix and split on the next token. The first two full blocks, covering eight tokens, can match. The next block contains tokens common to both requests and also tokens after the fork. Its hash cannot match if the tokens in the block differ. Extending the shared portion to a complete third block would make that block a candidate as well. The actual block size and available cached entries determine the result in a live deployment.

vLLM’s block manager increments the reference count for blocks a request reuses. A matched block that was on the free queue comes off that queue while it is in use. When the last request using a block finishes, the block can return to the free queue and retain its cache identity until the manager needs its space. If an allocation takes a cached block from the queue head, the manager removes its cache mapping. Repeated exact inputs can therefore show different amounts of reuse as traffic changes.

How RadixAttention handles branches

In the SGLang paper, a radix tree represents common prefixes as paths whose edges can contain sequences of tokens. Suppose an agent explores separate fixes for a failing test. Each fork begins with the same repository instructions, the same test command, and the same test result. The first request can populate a shared path. The second request can follow that path to the fork, then add its own suffix. A later step within either branch can look up state past the original fork if that branch’s suffix is still present.

The paper describes least recently used leaf eviction. When memory runs short, the runtime first reclaims eligible leaves. An older branch tip can disappear while its common ancestor with another branch remains available. Shared ancestors can become leaves and get evicted in turn. Reference counts protect the nodes used by running requests. For agent traces with many branches, test how often fork points survive as finished branches accumulate and new requests compete for the same memory.

The paper also describes scheduling that gives priority to requests with longer cached prefixes. If several related branches are waiting alongside unrelated work, serving the related branches while their common path is resident can improve reuse. When evaluating that policy, include queue time in the latency measurement. A run with high token reuse can still have slow requests, and a single average can hide which prefix groups waited.

The SGLang authors reported up to 6.4× higher throughput in their open-weight model experiments against baselines that included Guidance, LMQL, and vLLM v0.2.5 with its default API server. The throughput result reflects KV reuse alongside other parts of the system, including parallel calls within a program and constrained decoding. The authors also reported cache hit rates of 50% to 99% across those benchmarks. To compare against current vLLM Automatic Prefix Caching, rerun the tests on matched models, workloads, and hardware.

Distinguish a shared system prompt from a shared fork point when measuring those conditions. In a cohort of independent sessions, reuse of the system prompt may be sufficient even when every later token differs. In a cohort of forked sessions, the valuable match may extend through a large tool result and several earlier decisions. Group requests by their expected shared span so you can see which pattern drives an improvement. Also record how much text each workload generates. The SGLang paper notes that its multi-turn chat speedup was more noticeable for short outputs, since decoding can dominate when outputs are long and there is little sharing between sessions. vLLM’s feature guide likewise limits the savings from Automatic Prefix Caching to prefill. Decode still generates every new token.

Keep cache sharing inside the intended trust group

vLLM documents an optional per-request cache_salt. Unsalted requests can share eligible blocks with other unsalted requests on the same cache. vLLM’s design guide identifies a timing side-channel risk when tenants share cached state. vLLM incorporates a supplied salt into the first block’s hash, which affects every descendant hash through the parent chain. Salted requests can reuse blocks within the same salt group when their other hash inputs match. If an application chooses one stable salt per tenant, two sessions in the same tenant can share an eligible prefix. A session for another tenant with a different salt cannot reuse those salted blocks.

Choose salt groups at the boundary where the service allows sharing. A new salt on each request prevents later turns from matching earlier cached blocks even for one agent. A shared salt across tenants allows reuse of matching state across those tenants. Test the policy with same-group and different-group requests that otherwise have the same prompt. The hash algorithm helps distinguish entries. The salt determines the intended sharing group. When evaluating SGLang, verify equivalent isolation requirements against the deployment’s controls. The RadixAttention paper establishes the tree and scheduling design.

Where LMCache and Mooncake fit

The local lookup design answers whether previously computed tensors match. A storage or transfer layer addresses where those tensors can live and how a worker retrieves them. LMCache describes moving KV state from GPU memory into CPU memory, local storage, or remote backends. Mooncake covers both the movement of KV state between prefill and decode workers and distributed storage across a memory and storage hierarchy. Mooncake’s documentation describes integrations with vLLM and SGLang. LMCache also lists Mooncake as a supported backend.

Test local reuse first. If you see hits at low concurrency followed by losses under pressure, estimate the working set using the VRAM guide and compare that with available cache capacity. When you try an offload tier, time retrieval and compare it with the prefill it replaces. Long prefixes and repeated branches can have different retrieval tradeoffs from short prompts. Track local hits and offloaded hits separately where possible so the next capacity decision reflects their latency as well as their token counts.

For a rented deployment, divide the compute cost of each replay by the number of completed workflows. Set the same completion criteria for both engines and record requests that miss your service target. This avoids picking a configuration from cached token counts alone when the goal is to finish more coding tasks within the same budget.

Run a trace that separates lookup, eviction, and queueing

Start with vLLM if you need documented per-tenant cache isolation through cache_salt, prefix caching enabled by default, and built-in hit-rate counters. If your agents create many forks from long shared histories, benchmark SGLang first. The paper’s leaf-first eviction and longest-prefix-first scheduling are designed to retain and reuse the common paths in that workload. Check the release you plan to run for the scheduling policy it actually uses.

  1. Start with a repeatable trace. Record shared instructions, independent sessions, and branches that start at several points in the history. Hold model, hardware, input construction, and output limits fixed. Verify the prompt serialization before using an engine comparison to explain divergent results.
  2. Establish a warm baseline. Run the common prefix, then replay a request that reuses it. Test an early edit and a late fork separately. Compare the observed reusable length with the matching boundary you expect from each design.
  3. Add branch traffic and measure pressure. Replay the same fork sequence with unrelated work interleaved. On vLLM, divide the increase in vllm:prefix_cache_hits by the increase in vllm:prefix_cache_queries, or record per-request cached_tokens on chat and completion endpoints with --enable-prompt-tokens-details. On SGLang, use the equivalent token counts exposed by your build for the same request set. Record time to first token and end-to-end latency, including the slower requests. Use the cache hit rate guide for a consistent denominator.
  4. Verify the sharing policy. Check that independent trust groups do not reuse each other’s state. If results depend on how agents build their child requests, apply the cache-safe forking guide and replay the trace. Compare throughput and latency at the same memory budget.

Sources

How this note was produced

Drafted with AI assistance from committed ByteCosts pricing snapshots and deterministic cost formulas. Figures are grounded in the linked sources (last updated 2026-11-30). Read our editorial & automation policy, inspect the methodology, or report a discrepancy.

vLLM vs SGLang prefix caching for self-hosted agents. ByteCosts. Updated 2026-11-30. https://bytecosts.com/blog/vllm-vs-sglang-prefix-caching/

Sources