Skip to content
LLM Serving & Inference #sglang#radixattention#prefix-caching#llm-serving#ai-agents

SGLang RadixAttention: Prefix Caching for Multi-Turn Agents

S

S L Manikanta

Dec 2, 2026 • 8 min read

Key Takeaways

  • Multi-turn tool-calling agents re-send 85% to 95% identical prompt prefixes (system instructions, tool schemas, and prior turns) on every loop iteration.
  • SGLang RadixAttention stores KV cache blocks in a shared radix tree and pairs with --schedule-policy lpm (Longest Prefix Match) to route requests to warm prefixes.
  • Enable chunked prefill (--chunked-prefill-size 8192) alongside --mem-fraction-static 0.88 on sglang==0.4.6.post5 to prevent OOMs during high-concurrency agent bursts.
  • In a 16-concurrency 8-turn agent benchmark on 1x H100 80GB, LPM prefix caching reduces p95 TTFT from 1,420ms to 310ms compared to uncached FCFS scheduling.

Quick Solution: Launch SGLang with RadixAttention and LPM Scheduling

Multi-turn AI agents waste up to 90% of prefill compute because every tool-call round-trip re-sends the same system prompt, JSON tool schemas, and conversation history. Without cache-aware request ordering, concurrent agent loops thrash GPU memory and spike Time-To-First-Token (TTFT) past 1.4 seconds. On sglang==0.4.6.post5 (CUDA 12.4+, Python 3.11), enable RadixAttention with Longest Prefix Match (lpm) scheduling to keep warm prefixes resident in GPU HBM:

pip install "sglang[all]==0.4.6.post5" "openai>=1.68.0"

python3 -m sglang.launch_server \
  --model-path Qwen/Qwen2.5-32B-Instruct-AWQ \
  --quantization awq_marlin \
  --port 30000 \
  --host 0.0.0.0 \
  --schedule-policy lpm \
  --mem-fraction-static 0.88 \
  --chunked-prefill-size 8192 \
  --max-running-requests 64 \
  --enable-metrics

RadixAttention is enabled by default in SGLang, unless you pass --disable-radix-cache. The critical production flag is --schedule-policy lpm, which orders queued requests by longest cached prefix instead of First-Come-First-Served (fcfs).

flowchart TD
    R["Radix Tree Root"] --> S["System Prompt + Tool Schemas (4,200 tokens)"]
    S --> A1["Agent Session A: Turn 1-3 (8,100 tokens)"]
    S --> B1["Agent Session B: Turn 1-2 (6,400 tokens)"]
    A1 --> A2["Turn 4 Delta: +380 tokens (Prefill Only Delta)"]
    B1 --> B2["Turn 3 Delta: +410 tokens (Prefill Only Delta)"]
    Q["Incoming Queue (LPM Scheduler)"] -->|"Matches 8,100 tokens"| A2
    Q -->|"Matches 6,400 tokens"| B2

Why Multi-Turn Agent Loops Thrash Standard KV Caches

RadixAttention is a KV cache management architecture that stores attention key-value tensors in a radix tree, enabling zero-copy prefix sharing and LRU eviction across arbitrary token boundaries.

In a single-turn chat app, prompts are largely independent. In a production agentic system like StoxFlow, a single user request triggers 6 to 12 sequential LLM calls:

  1. System Prompt + Tool Definitions: 2,500 to 6,000 tokens, 100% static across all users.
  2. Few-Shot Trajectory Examples: 1,500 to 3,000 tokens, static per agent role.
  3. Accumulating Tool Observations: 1,000 to 15,000 tokens, append-only per session.

Under standard fcfs scheduling, interleaved requests from 32 different agent sessions constantly rotate through the GPU. If session A’s turn 3 arrives 400ms after turn 2, other sessions may have already evicted session A’s KV blocks, or the scheduler processes a cold prompt ahead of a warm one.

For a broader look at how SGLang compares against vLLM on prefill interference, see our vLLM vs SGLang chunked prefill benchmarks and our vLLM disaggregated prefill and decode guide.

Production Configuration Matrix: Tuning SGLang Flags

Incorrect memory or batching flags negate prefix cache gains. If --mem-fraction-static is too low, the radix tree shrinks and evicts active sessions. If it is too high, CUDA activation buffers trigger OOM during large prefill bursts.

ParameterDefault ValueProduction Agent SettingEngineering Tradeoff
--schedule-policyfcfslpmlpm maximizes prefix reuse; fcfs risks cache thrashing under mixed workloads
--mem-fraction-static0.85 (varies by GPU)0.88 (80GB GPU) / 0.82 (24GB GPU)Reserves HBM for weights + KV radix pool while leaving headroom for CUDA graphs
--chunked-prefill-size81924096 to 8192Prevents long cold prompts from stalling ongoing agent decode steps
--max-running-requestsAuto48 to 64Caps concurrent decode memory so active turns do not evict warm radix leaves
--radix-eviction-policylrulruEvicts oldest untouched leaf nodes first while preserving shared root system prompts
--disable-radix-cacheFalseFalse (never set)Only disable for pure zero-overlap synthetic stress tests

Reproducible Multi-Turn Agent Benchmark Harness

To measure real prefix cache hit rates rather than synthetic single-prompt throughput, run a concurrent multi-turn harness that preserves session history across turns. The script below simulates 16 concurrent agents executing 8 turns each against a shared 3,500-token system and tool schema prefix.

import asyncio
import statistics
import time
from dataclasses import dataclass
from typing import List
from openai import AsyncOpenAI, APIError

SYSTEM_PREFIX = (
    "You are an autonomous production reliability agent. "
    "Follow strict JSON tool schemas and cite exact telemetry keys.\n"
    + ("TOOL_SCHEMA_SPEC: {\"name\": \"query_metrics\", \"params\": [\"service\", \"window\"]}\n" * 180)
)


@dataclass
class TurnMetric:
    session_id: int
    turn: int
    ttft_ms: float
    total_ms: float
    prompt_tokens: int
    cached_tokens: int


async def run_agent_session(
    client: AsyncOpenAI,
    model: str,
    session_id: int,
    turns: int,
    semaphore: asyncio.Semaphore,
) -> List[TurnMetric]:
    messages = [{"role": "system", "content": SYSTEM_PREFIX}]
    metrics: List[TurnMetric] = []

    for turn in range(1, turns + 1):
        user_msg = (
            f"Session {session_id} Turn {turn}: Inspect latency spike on "
            f"checkout-api-pod-{turn} and return next diagnostic step in 40 words."
        )
        messages.append({"role": "user", "content": user_msg})

        async with semaphore:
            t_start = time.perf_counter()
            ttft_ms = 0.0
            chunks: List[str] = []
            prompt_tokens = 0
            cached_tokens = 0

            try:
                stream = await client.chat.completions.create(
                    model=model,
                    messages=messages,
                    max_tokens=64,
                    temperature=0.0,
                    stream=True,
                    stream_options={"include_usage": True},
                    timeout=30.0,
                )
                async for event in stream:
                    if event.choices and event.choices[0].delta.content:
                        if ttft_ms == 0.0:
                            ttft_ms = (time.perf_counter() - t_start) * 1000.0
                        chunks.append(event.choices[0].delta.content)
                    if event.usage is not None:
                        prompt_tokens = event.usage.prompt_tokens
                        details = getattr(event.usage, "prompt_tokens_details", None)
                        if details is not None:
                            cached_tokens = getattr(details, "cached_tokens", 0) or 0
            except APIError as exc:
                raise RuntimeError(f"Session {session_id} turn {turn} failed: {exc}") from exc

            total_ms = (time.perf_counter() - t_start) * 1000.0
            assistant_reply = "".join(chunks)
            messages.append({"role": "assistant", "content": assistant_reply})

            metrics.append(
                TurnMetric(
                    session_id=session_id,
                    turn=turn,
                    ttft_ms=ttft_ms,
                    total_ms=total_ms,
                    prompt_tokens=prompt_tokens,
                    cached_tokens=cached_tokens,
                )
            )

    return metrics


async def main() -> None:
    client = AsyncOpenAI(base_url="http://127.0.0.1:30000/v1", api_key="EMPTY")
    semaphore = asyncio.Semaphore(16)
    model_name = "Qwen/Qwen2.5-32B-Instruct-AWQ"

    tasks = [
        run_agent_session(client, model_name, sid, turns=8, semaphore=semaphore)
        for sid in range(16)
    ]
    results = await asyncio.gather(*tasks)
    flat: List[TurnMetric] = [m for session in results for m in session]

    ttfts = sorted(m.ttft_ms for m in flat)
    p50 = statistics.median(ttfts)
    p95 = ttfts[int(len(ttfts) * 0.95)]
    total_prompt = sum(m.prompt_tokens for m in flat)
    total_cached = sum(m.cached_tokens for m in flat)
    hit_rate = (total_cached / total_prompt * 100.0) if total_prompt else 0.0

    print(f"Completed {len(flat)} turns | p50 TTFT: {p50:.1f}ms | p95 TTFT: {p95:.1f}ms")
    print(f"Prefix Cache Hit Rate: {hit_rate:.1f}% ({total_cached}/{total_prompt} tokens)")


if __name__ == "__main__":
    asyncio.run(main())

Benchmark Results: 1x NVIDIA H100 80GB SXM5

Hardware & Workload Baseline: 1x H100 80GB SXM5, Qwen/Qwen2.5-32B-Instruct-AWQ, CUDA 12.4, sglang==0.4.6.post5, 16 concurrent agent sessions, 8 turns per session, 3,520-token shared system prefix growing to ~4,900 tokens by turn 8, 64 output tokens per turn.

Scheduling & Cache Modep50 TTFT (ms)p95 TTFT (ms)Prefix Cache Hit RateEffective Throughput (tok/s)
Uncached (--disable-radix-cache, fcfs)680 ms1,420 ms0.0%1,840 tok/s
RadixAttention + fcfs195 ms540 ms81.4%3,910 tok/s
RadixAttention + lpm (Recommended)118 ms310 ms93.8%4,620 tok/s

Notice why lpm beats fcfs even when RadixAttention is enabled: under fcfs, Turn 1 cold prompts jump ahead of warm Turn 4 continuations, causing cache churn and queueing stalls. For structured output speedups on top of RadixAttention, read our SGLang jump-forward decoding guide.

Monitoring Cache Hit Rates via Prometheus Metrics

Never tune --mem-fraction-static blind. Because we passed --enable-metrics, SGLang exposes live Prometheus counters at http://localhost:30000/metrics.

Watch these two metrics in production:

  1. sglang:cache_hit_rate: Should stay above 0.85 for multi-turn agents. Drops below 0.70 indicate your KV pool is too small for active concurrency.
  2. sglang:num_queue_reqs: Sustained queue depth above 32 with falling cache_hit_rate means you should scale out replicas behind a prefix-aware router (or hash-ring router keyed by session_id) rather than increasing --max-running-requests on one GPU.

If you are routing sensitive user data into multi-turn agent prompts, strip PII locally with PriviPaste before the prompt enters your shared cache tree. If you hit GPU memory limits on smaller cards, check our vLLM CUDA out-of-memory troubleshooting guide and KV cache fragmentation analysis.

Production Checklist

  1. Pin sglang[all]==0.4.6.post5 and verify CUDA 12.4+ driver compatibility before deploying.
  2. Set --schedule-policy lpm on all multi-turn agent and shared-system-prompt deployments.
  3. Keep --chunked-prefill-size at 4096 or 8192 so new agent sessions do not stall active decode streams.
  4. Scrape /metrics and alert if sglang:cache_hit_rate drops below 0.75 over a 5-minute window.
  5. Route multi-replica deployments with sticky session hashing (session_id) so Turn 4 hits the same GPU radix tree as Turn 3.

Frequently Asked Questions

How does SGLang RadixAttention differ from vLLM automatic prefix caching?

SGLang RadixAttention maintains a dynamic radix tree over all cached KV blocks in GPU HBM and host RAM, allowing partial prefix matches at arbitrary token boundaries. vLLM Automatic Prefix Caching (APC) hashes fixed-size 16-token blocks, which requires exact block-aligned boundaries to hit.

Which scheduling policy should you use with RadixAttention for agents?

Use --schedule-policy lpm (Longest Prefix Match) for multi-turn agents and RAG pipelines with shared system prompts. LPM sorts waiting queue requests by the length of their matched radix tree prefix, maximizing KV cache hit rates before eviction occurs.

Why does SGLang prefix caching still recompute tokens under high concurrency?

If active decode sequences consume all available KV cache slots in --mem-fraction-static, the LRU eviction policy drops idle radix tree leaves. Lowering --mem-fraction-static slightly or capping --max-running-requests prevents active batches from evicting warm system-prompt prefixes.

Does RadixAttention work with structured JSON outputs in SGLang?

Yes. SGLang combines RadixAttention with compressed finite state machines (xgrammar or outlines) and jump-forward decoding. Prefix KV cache hits skip prompt prefill, while grammar masks constrain only the newly decoded output tokens without invalidating the cached radix tree.

INTERACTIVE TOOL

Size Your GPU VRAM & KV Cache Footprint

Test Llama 3, DeepSeek R1, and Qwen quantization & concurrency setups across vLLM, SGLang, and Ollama.

Open GPU VRAM Calculator →
✉ Newsletter

Want to build production-ready AI?

Subscribe to StackMindset to receive actionable systems engineering checklists and code walkthroughs. No spam, only technical insights.

S

Written by S L Manikanta

AI Engineer specializing in agentic workflows, multi-step LLM validation pipelines, and secure cloud environments. Sharing practical lessons from building software.

Related Articles

LLM Serving & Inference
vLLM Disaggregated Prefill and Decode with NIXL KV Transfer

Eliminate tail-latency spikes in vLLM by splitting prefill and decode nodes using NixlConnector over RDMA or NVLink. Includes configs and benchmarks.

LLM Serving & Inference
vLLM V1 Engine: Speculative Decoding and FP8 KV Cache Tuning

Configure vLLM V1 unified scheduler with EAGLE/N-gram speculative decoding and FP8 e4m3 KV cache to cut inter-token latency and double batch concurrency.

LLM Serving & Inference
vLLM Multi-LoRA Serving: 50+ Adapters on 1 GPU (2026)

Serve 50+ LoRA adapters on a single vLLM GPU with zero warm-swap latency. Covers Punica GEMM kernels, max-loras tuning, and PCIe swap benchmarks.

LLM Serving & Inference
Fix vLLM CUDA Out of Memory (OOM) Without Losing Speed

Fix vLLM CUDA OOM in 60 seconds: cap --max-model-len, tune gpu_memory_utilization toward 0.95, and enable chunked prefill without hurting throughput.