vLLM vs SGLang vs Ollama: LLM Serving Benchmarks (2026)
Compare vLLM, SGLang, and Ollama across throughput, TTFT, PagedAttention, RadixAttention, Docker serving configs, and KV-cache OOM fixes in 2026.
Evaluating vLLM vs SGLang vs Ollama comes down to concurrency and memory scheduling: vLLM leads high-concurrency production APIs and multi-LoRA fleets, SGLang leads prefix-heavy multi-turn agents and strict JSON decoding, and Ollama leads local single-user development on laptops and Apple Silicon.
On data-center GPUs serving 32 to 128 concurrent requests, vLLM and SGLang sustain 100% request completion and 20x to 29x higher aggregate throughput than Ollama. Ollama trades continuous batching for zero-config ergonomics, which makes it fast to start locally yet prone to queue starvation above roughly 10 simultaneous users.
Key Takeaways
- vLLM uses PagedAttention, continuous batching, and its unified V1 scheduler to sustain high aggregate tokens per second across broad model architectures, FP8/NVFP4 quantization, and dynamic multi-LoRA adapters.
- SGLang pairs RadixAttention prefix-tree KV caching with XGrammar compressed finite state machines, outperforming vLLM by 10% to 17% on prefix-heavy multi-turn agents and reaching 96% to 98.2%+ JSON schema compliance.
- Ollama wraps llama.cpp GGUF weights and a native Apple Silicon MLX runner inside a single background daemon, making it the default choice for consumer hardware, MacBooks, and single-user workstations.
- Concurrency boundary: vLLM and SGLang maintain sub-second Time to First Token (TTFT) at 32 to 128 concurrent users, while Ollama degrades to 48 to 120+ second TTFT and 13% to 30% timeout rates past its parallel slot ceiling.
- Memory stability: Fixing KV-cache out-of-memory crashes requires tuning
--gpu-memory-utilizationin vLLM,--mem-fraction-staticin SGLang, orOLLAMA_KV_CACHE_TYPE=q8_0with Flash Attention in Ollama.
How vLLM, SGLang, and Ollama Differ Under the Hood
vLLM, SGLang, and Ollama solve fundamentally different memory-scheduling problems for self-hosted LLM serving. vLLM virtualizes KV-cache pages for multi-tenant GPU clusters, SGLang indexes reusable prompt prefixes inside a live radix tree, and Ollama packages quantized local runtimes behind a lightweight developer daemon.
Figure 1: Under-the-hood KV-cache and scheduling architectures in vLLM PagedAttention, SGLang RadixAttention, and Ollama.
Understanding the architectural split between PagedAttention vs RadixAttention and llama.cpp GGUF execution explains why single-user benchmarks rarely predict production behavior. Each engine makes explicit trade-offs across KV-cache fragmentation, prefill scheduling, and hardware portability.
| Architectural Dimension | vLLM (V1 Engine) | SGLang Runtime | Ollama Daemon |
|---|---|---|---|
| Core KV-Cache Strategy | PagedAttention virtual blocks + hash-based APC | RadixAttention live prefix tree + LRU eviction | Contiguous per-slot KV buffers (f16, q8_0, q4_0) |
| Batching Scheduler | Continuous batching + unified chunked prefill | Continuous batching + zero-overhead overlap | Bounded parallel slots (OLLAMA_NUM_PARALLEL) + FIFO queue |
| Constrained Decoding | Guided decoding backends (XGrammar, Outlines) | Native XGrammar compressed FSM (default) | GBNF grammar / JSON schema via llama.cpp |
| Primary Weight Formats | Safetensors, FP8, AWQ, GPTQ, NVFP4 | Safetensors, FP8, AWQ, GPTQ | GGUF (Q4_K_M, Q5_K_M, Q8_0), Apple MLX |
| Multi-LoRA Multiplexing | Native dynamic CUDA Punica/SGMV kernels | Native dynamic CUDA SGMV kernels | Not supported per request (separate Modelfiles) |
| Primary Hardware Target | NVIDIA CUDA, AMD ROCm data-center GPUs | NVIDIA CUDA, AMD ROCm data-center GPUs | Apple Silicon (Metal/MLX), consumer GPUs, CPUs |
vLLM V1 Engine: PagedAttention and Automatic Prefix Caching
vLLM introduced PagedAttention in the PagedAttention Paper on arXiv to eliminate the 60% to 80% KV-cache memory waste caused by contiguous pre-allocation in legacy serving stacks. Instead of reserving one unbroken VRAM slab per request, vLLM splits each sequence’s keys and values into fixed-size physical blocks mapped through a logical block table.
In the newer vLLM V1 engine, Automatic Prefix Caching (APC) is built directly into the core KVCacheManager rather than bolted onto an older block manager. Once a KV block fills, V1 assigns a token-chained block_hash and retains evicted blocks under an LRU policy so subsequent requests with matching prompts reuse cached states with near-zero CPU overhead.
The V1 scheduler also removes rigid barriers between prefill and decode steps by using unified chunked prefill. As documented in the vLLM Official GitHub Repository, V1 extends prefix hashing to multimodal inputs by combining token hashes with image hashes through a dedicated encoder cache.
SGLang Runtime: RadixAttention Prefix Trees and XGrammar FSMs
SGLang approaches KV-cache reuse from a program-execution perspective rather than treating every HTTP call as an isolated prompt. Detailed in the SGLang RadixAttention Paper on arXiv, RadixAttention stores cached KV tensors as edges in a radix tree that persists across turns, branches, and parallel agent rollouts.
When a new request arrives, SGLang traverses the radix tree to match the longest shared prefix, whether that prefix is a 12,000-token RAG system prompt, few-shot examples, or prior tool-call outputs. Unreferenced leaf nodes remain in GPU memory until VRAM pressure triggers LRU eviction, keeping cache hit rates high during multi-turn workflows.
For structured outputs, SGLang pairs RadixAttention with XGrammar as its default constrained decoding engine. As shown in the XGrammar Structured Generation Paper on arXiv, XGrammar compiles JSON schemas into a compressed finite state machine and overlaps bitmask generation with the GPU forward pass, avoiding the exponential state blowup seen in naive pushdown automata.
Ollama Daemon: llama.cpp GGUF Weights and Apple Silicon MLX
Ollama is a Go-managed service layer built primarily on the C/C++ inference kernels of the llama.cpp Official GitHub Repository. It abstracts model downloads, chat templates, and GPU layer offloading behind a persistent daemon running on port 11434.
Instead of loading unquantized safetensors into data-center GPUs, Ollama defaults to portable GGUF containers quantized at 4-bit to 8-bit integer precision. On macOS M-series hardware, Ollama also ships a native Apple MLX runner for MLX-formatted weights alongside its Metal backend, accelerating prompt prefill across unified memory.
Teams deciding between raw C++ flags and managed local daemons can review our llama.cpp vs Ollama architectural breakdown for single-machine benchmarks and layer offloading trade-offs.
Engine-by-Engine Verdict: vLLM vs SGLang vs Ollama
Choosing among these three open source LLM serving engines starts with matching each runtime’s architecture to your traffic shape and hardware footprint. The self-contained blocks below summarize the exact verdict, strengths, trade-offs, and cost profile for vLLM, SGLang, and Ollama.
vLLM: Production Multi-Tenant Serving and Multi-LoRA
- Verdict: The default production LLM inference server for multi-tenant APIs, diverse open-weight model catalogs, and multi-LoRA GPU fleets.
- Best for: Engineering teams operating NVIDIA or AMD GPU clusters that serve 20 to 1,000+ concurrent requests across mixed prompt distributions, enterprise SLAs, or dozens of fine-tuned LoRA adapters on a single base model.
- Strengths: Broadest day-zero model support (including Llama 4, Qwen 2.5 Coder 32B, DeepSeek-V4.1, and Gemma 4), mature V1 continuous batching with Automatic Prefix Caching, hardware-specific quantization such as FP8 and Blackwell NVFP4, and battle-tested Kubernetes and Prometheus telemetry integrations.
- Trade-offs: Primarily targets Linux with NVIDIA CUDA or AMD ROCm; Apple Silicon support relies on community plugins such as
vllm-metal, and static KV-cache pre-allocation requires deliberate--gpu-memory-utilizationtuning to prevent CUDA graph OOM crashes. - Pricing: Free and open source under the Apache 2.0 license; production costs consist solely of GPU compute infrastructure (cloud instances or on-premise servers).
SGLang: Prefix-Heavy Agents and Constrained JSON Decoding
- Verdict: The highest-efficiency serving engine for multi-turn AI agents, RAG pipelines with long shared system prompts, and strict structured JSON generation.
- Best for: Agentic applications executing tree-of-thought rollouts, recursive tool loops, or heavy Pydantic schema extraction where prefix reuse and low-overhead logit masking directly control latency.
- Strengths: RadixAttention automatic prefix-tree caching minimizes redundant prefill compute, native XGrammar compressed finite state machines push JSON schema compliance to 96% to 98.2%+ with minimal throughput loss, and multi-request sweeps on shared prefixes frequently beat vLLM by 10% to 17%.
- Trade-offs: Under extreme concurrency with completely disjoint prompts (zero cache reuse), SGLang’s scheduler can hit single-core CPU bottlenecks faster than vLLM’s C++ paths, and its model ecosystem adopts niche vision or audio architectures slightly behind vLLM.
- Pricing: Free and open source under the Apache 2.0 license; infrastructure costs are limited to underlying CUDA or ROCm GPU hosting.
When building strict agent tool contracts, pair SGLang’s XGrammar runtime with the schema design patterns in our structured outputs and JSON mode guide to avoid nested regex traps.
Ollama: Local Developer Ergonomics and Consumer Hardware
- Verdict: The fastest, lowest-friction runtime for individual developers, local prototyping, offline workstations, and Apple Silicon Macs.
- Best for: Local IDE copilots, single-user desktop agents, air-gapped developer laptops, and quick proof-of-concept scripts running quantized 7B to 70B models on consumer GPUs or unified memory.
- Strengths: One-command installation and model pulling, automatic GPU/CPU hybrid layer offloading across CUDA, Metal, ROCm, and CPU SIMD, native Apple MLX acceleration on macOS, and clean Modelfile packaging with an OpenAI-compatible API out of the box.
- Trade-offs: Lacks continuous PagedAttention or RadixAttention batching, caps concurrency through static
OLLAMA_NUM_PARALLELslots that multiply KV-cache memory linearly, drops traffic with HTTP 503 onceOLLAMA_MAX_QUEUEfills, and has no dynamic per-request multi-LoRA routing. - Pricing: Free and open source under the MIT license; runs at zero marginal API cost on existing laptops, workstations, or single-GPU boxes.
LLM Serving Benchmarks: Concurrency, TTFT, and Throughput Matrices
In head-to-head LLM serving benchmarks on data-center GPUs, single-user latency looks deceptively close across all three engines, while high concurrency exposes a 20x to 29x throughput chasm. vLLM and SGLang scale aggregate tokens per second smoothly up to 128+ active users, whereas Ollama saturates its sequential queue and times out.
Evaluating LLM inference engines comparison data requires separating single-stream interactive speed (C=1) from realistic production concurrency (C=32 and C=128). The metrics below synthesize published multi-engine benchmark sweeps on server-grade NVIDIA GPUs (L4/A100/H100 class) running 7B to 8B instruction models alongside consumer hardware baselines.
Single-User Latency vs High-Concurrency Throughput Scaling
At concurrency 1 (C=1), token generation speed is governed almost entirely by GPU memory bandwidth rather than request scheduling. Both vLLM and SGLang record Time to First Token (TTFT) around 10 ms to 15 ms on quantized 4-bit or FP8 weights, while Ollama’s daemon overhead typically lands near 65 ms+ on short prompts.
Once concurrency reaches 32 to 128 simultaneous users, continuous batching LLM throughput completely reshapes the leaderboard. vLLM and SGLang interleave prefill chunks and decode steps inside shared GPU matrix multiplications, keeping p95 latency predictable while Ollama serializes requests behind its parallel slot cap.
| Benchmark Metric | vLLM (V1 + PagedAttention) | SGLang (RadixAttention) | Ollama (llama.cpp Daemon) |
|---|---|---|---|
Baseline TTFT (C=1) |
10 ms to 15 ms | 10 ms to 15 ms | 65 ms+ (scales steeply with prompt) |
TTFT Under Load (C=32 to C=128) |
Sub-second (< 500 ms p50 typical) | Sub-second (lowest on shared prefixes) | 48 s to 120 s+ (severe queue starvation) |
Aggregate Throughput (C=32 to C=128) |
20x to 29x higher than Ollama | Up to 10% to 17% above vLLM on prefix sweeps | Flattens or collapses past ~10 users |
Request Success Rate (C=128 Stress) |
100% | 100% | 70% to 87% (13% to 30%+ timeouts) |
| Time Per Output Token (TPOT) Stability | Stable via chunked prefill | Stable via overlapped scheduling | Erratic spikes during concurrent prefill |
| Primary Scaling Bottleneck | KV-cache VRAM blocks & PCIe/NVLink | Disjoint-prompt CPU scheduler overhead | OLLAMA_NUM_PARALLEL slots & FIFO queue |
[!NOTE] Absolute tokens-per-second figures depend heavily on model parameter count, quantization format (FP8 vs INT4 vs Q4_K_M), prompt-to-output length ratio, and GPU memory bandwidth. Always reproduce latency curves with your own prompt distribution using the Python benchmark script in this guide before locking production capacity.
Prefix-Cache Hit Rate and Structured Output Overhead
Comparing a vLLM vs SGLang prefix caching benchmark highlights why workload structure matters as much as raw FLOPs. When 60% to 90% of prompt tokens repeat across turns (such as an agent carrying a 6,000-token tool manifest and conversation history), KV cache hit rate directly determines effective TTFT.
SGLang’s RadixAttention maintains an in-memory radix tree across all active and recently evicted sessions, allowing branching agent trajectories to reuse intermediate KV states automatically. vLLM V1 narrows the gap substantially with native hash-based Automatic Prefix Caching, though SGLang still holds an edge on complex multi-branch prefix trees and strict grammar masking.
| Workload Pattern | vLLM Performance Profile | SGLang Performance Profile | Practical Takeaway |
|---|---|---|---|
| Disjoint Multi-Tenant Prompts | Leads or ties; lower CPU scheduler overhead at extreme concurrency | Strong, though radix tree lookups add minor overhead when hit rate is 0% | Prefer vLLM for general-purpose public APIs |
| Shared System Prompts & RAG | Fast with V1 APC enabled (--enable-prefix-caching) |
Up to 10% to 17% higher throughput via persistent radix tree reuse | Prefer SGLang for high-overlap RAG and chat |
| Strict JSON Schema / Tool Calls | High throughput with XGrammar backend enabled | Default XGrammar compressed FSM overlaps bitmask compute (96% to 98.2%+ compliance) | Prefer SGLang for strict agent tool loops |
| Hardware FP8 / Blackwell NVFP4 | Rapid kernel adoption; frequently takes lead on NVFP4 hardware | Fast FP8 support; closely tracks vLLM on Hopper/Blackwell | Benchmark both on target GPU generation |
For a deeper look at how KV reuse cuts prefill compute and API spend across both cloud and self-hosted stacks, read our prompt caching architecture guide.
Hardware and Quantization Efficiency Across GPUs and Unified Memory
Hardware topology often settles the engine choice before benchmarks even begin. vLLM and SGLang assume discrete data-center accelerators with high-bandwidth HBM (NVIDIA L40S, A100, H100, H200, B200, or AMD MI300X) and tensor parallelism across NVLink.
Ollama dominates consumer silicon where VRAM is scarce or unified. On an Apple MacBook Pro or Mac Studio with 64 GB to 128 GB of unified memory, Ollama’s llama.cpp Metal and native MLX runners execute 32B to 70B quantized models cleanly with zero CUDA dependency.
Where Each Engine Wins (And When to Avoid It)
No single serving engine wins every deployment tier. Selecting the right runtime means aligning batching mechanics, prefix reuse, and hardware support with your actual traffic ceiling rather than chasing peak single-metric charts.
Where vLLM Wins
vLLM is the strongest choice when operational breadth, multi-tenant stability, and enterprise GPU utilization matter most:
- High-Concurrency Multi-Tenant APIs: Serving hundreds of independent users with unrelated prompts where PagedAttention, unified chunked prefill, and low CPU scheduling overhead keep p95 latency flat.
- Dynamic Multi-LoRA Serving: Hosting one shared base model (such as Llama 4 or Qwen 2.5 Coder 32B) while dynamically routing per-request traffic to dozens of customer-specific LoRA adapters via CUDA Punica/SGMV kernels.
- Broad Model & Quantization Coverage: Running newly released open-weight architectures, multimodal vision-language models, or hardware-native quantization formats like Blackwell NVFP4 without waiting for third-party ports.
When to avoid vLLM: Skip vLLM on developer laptops, Windows desktops without WSL2/Docker CUDA pipelines, or Apple Silicon workstations where native Metal and MLX ergonomics outweigh continuous batching.
Where SGLang Wins
SGLang wins whenever prompt prefixes repeat across calls or output structure must satisfy strict machine-readable schemas:
- Multi-Turn Agentic Loops and Tool Calling: Autonomous coding agents, ReAct loops, and tree-search planners that append new tool outputs onto a shared multi-thousand-token history every turn benefit directly from RadixAttention’s persistent prefix tree.
- High-Throughput Structured JSON Extraction: Pipelines enforcing complex nested Pydantic schemas or regex grammars achieve 96% to 98.2%+ schema compliance with minimal TPOT slowdown thanks to XGrammar’s overlapped compressed FSM bitmasks.
- Prefix-Heavy RAG and Batch Classification: Workloads that evaluate dozens of queries against the same retrieved document context or few-shot rubric see substantial TTFT drops and 10% to 17% throughput gains over non-tree schedulers.
When to avoid SGLang: Avoid SGLang for single-user desktop prototyping on consumer macOS/Windows hardware, or when your production fleet relies heavily on niche model architectures not yet prioritized in the SGLang Official GitHub Repository.
Where Ollama Wins
Ollama wins every scenario where developer velocity, cross-platform hardware portability, and zero-ops simplicity beat data-center concurrency:
- Apple Silicon and Consumer Workstations: Running local coding assistants (Continue.dev, Cursor, Claude Code local bridges) on MacBooks or single RTX desktop cards using GGUF or native Apple MLX weights.
- Rapid Prototyping and Reproducible Local Prompts: Packaging system instructions, context limits, and temperature defaults inside version-controlled Modelfiles that any teammate can launch with one command.
- Air-Gapped Single-User Tools and Edge Boxes: Operating private document summarizers or offline CLI helpers on CPU-only machines or modest 8 GB to 24 GB GPUs without configuring PyTorch, CUDA toolkits, or Kubernetes pods.
When to avoid Ollama: Do not deploy a single Ollama daemon behind a customer-facing API serving more than 10 concurrent users. For complete single-workstation tuning, Modelfile syntax, and Open WebUI setup, follow our complete Ollama local AI guide.
| Deployment Scenario | Recommended Engine | Runner-Up | Why It Wins |
|---|---|---|---|
| Enterprise Public API (50 to 500+ users) | vLLM | SGLang | Lowest CPU overhead on disjoint prompts + mature ops tooling |
| Multi-Turn Coding / RAG Agent Fleet | SGLang | vLLM (V1 APC) | RadixAttention prefix tree + overlapped XGrammar JSON decoding |
| Multi-Tenant Fine-Tuned LoRA SaaS | vLLM | SGLang | Battle-tested dynamic Punica/SGMV multi-LoRA adapter routing |
| MacBook Pro / Apple Silicon Dev Machine | Ollama | llama.cpp | First-class Metal + native MLX runner with zero setup friction |
| Single-GPU Internal Tool (< 8 users) | Ollama (tuned) | vLLM | Fast deployment with OLLAMA_NUM_PARALLEL=4 and q8_0 KV cache |
Production Deployment: Docker, CLI Commands, and Python Benchmark Script
All three engines expose an OpenAI-compatible HTTP endpoint (/v1/chat/completions), which lets engineering teams benchmark vLLM, SGLang, and Ollama with identical client code and migrate between local and production backends by changing one base URL.
The commands below launch a 7B to 8B instruction model on each engine with production-safe memory flags, followed by a typed async Python benchmark script that measures TTFT, TPOT, aggregate tokens per second, and error rate under configurable concurrency.
Production Docker and CLI Launch Commands for vLLM, SGLang, and Ollama
Launch vLLM with the V1 engine, Automatic Prefix Caching, and chunked prefill enabled on port 8000. Pin --gpu-memory-utilization to 0.85 and cap --max-model-len to your real application context budget so CUDA graph capture has breathing room:
# vLLM V1 production server via Docker (NVIDIA CUDA)
docker run --rm --gpus all \
-p 8000:8000 \
-v ~/.cache/huggingface:/root/.cache/huggingface \
-e VLLM_USE_V1=1 \
-e PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
vllm/vllm-openai:latest \
--model Qwen/Qwen2.5-7B-Instruct \
--host 0.0.0.0 \
--port 8000 \
--gpu-memory-utilization 0.85 \
--max-model-len 8192 \
--max-num-seqs 128 \
--enable-prefix-caching \
--enable-chunked-prefill
Key flags to verify: --enable-prefix-caching activates V1’s block-hash KV reuse, --max-num-seqs 128 bounds active batch memory, and PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True mitigates CUDA allocator fragmentation during bursty traffic. For an example of deploying a 1.1T sparse MoE model with SGLang MegaMoE, DSpark speculative decoding, and tuned --swa-full-tokens-ratio flags, inspect our Amazon Ergo deployment guide.
Launch SGLang on port 30000 with RadixAttention (enabled by default), XGrammar constrained decoding, and an explicit --mem-fraction-static ceiling:
# SGLang runtime server via Docker (NVIDIA CUDA)
docker run --rm --gpus all \
-p 30000:30000 \
-v ~/.cache/huggingface:/root/.cache/huggingface \
-e PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
lmsysorg/sglang:latest \
python3 -m sglang.launch_server \
--model-path Qwen/Qwen2.5-7B-Instruct \
--host 0.0.0.0 \
--port 30000 \
--mem-fraction-static 0.80 \
--context-length 8192 \
--grammar-backend xgrammar
Key flags to verify: --mem-fraction-static 0.80 reserves 80% of total VRAM for model weights plus the radix KV cache pool while leaving 20% headroom for activations and communication buffers, and --grammar-backend xgrammar enforces compressed FSM structured outputs.
Launch Ollama on port 11434 with bounded concurrency, Flash Attention, and 8-bit KV-cache quantization so parallel slots do not exhaust VRAM:
# Ollama server with concurrency and KV-cache tuning via Docker
docker run -d --gpus all \
-p 11434:11434 \
-v ollama_data:/root/.ollama \
-e OLLAMA_NUM_PARALLEL=4 \
-e OLLAMA_MAX_QUEUE=512 \
-e OLLAMA_FLASH_ATTENTION=1 \
-e OLLAMA_KV_CACHE_TYPE=q8_0 \
-e OLLAMA_KEEP_ALIVE=24h \
--name ollama-bench \
ollama/ollama:latest
# Pull the matching GGUF model tag inside the container
docker exec ollama-bench ollama pull qwen2.5:7b-instruct
Key environment variables to verify: OLLAMA_NUM_PARALLEL=4 enables four simultaneous request slots, OLLAMA_FLASH_ATTENTION=1 activates Flash Attention, and OLLAMA_KV_CACHE_TYPE=q8_0 cuts KV-cache VRAM consumption roughly in half compared to f16. See the Ollama Official GitHub Repository for platform-specific systemd and launchctl instructions.
Async Python OpenAI-Compatible Benchmark Script (TTFT, TPOT, and Throughput)
This self-contained Python script benchmarks any OpenAI-compatible endpoint (vLLM, SGLang, or Ollama) using streaming Server-Sent Events to capture exact Time to First Token, Time Per Output Token, p95 latency, aggregate throughput, and failure rates.
Install the required async HTTP client (pip install httpx) before running the script:
import argparse
import asyncio
import json
import statistics
import time
from dataclasses import dataclass
from typing import Optional
import httpx
@dataclass
class RequestMetrics:
ok: bool
ttft_ms: float
total_ms: float
output_tokens: int
error: Optional[str] = None
SHARED_SYSTEM_PROMPT = (
"You are a senior distributed systems engineer. Return concise, "
"accurate architectural explanations with concrete trade-offs. "
"Always focus on memory layout, scheduling latency, and failure modes."
)
async def send_streaming_request(
client: httpx.AsyncClient,
base_url: str,
model: str,
user_prompt: str,
max_tokens: int,
) -> RequestMetrics:
url = f"{base_url.rstrip('/')}/chat/completions"
payload = {
"model": model,
"messages": [
{"role": "system", "content": SHARED_SYSTEM_PROMPT},
{"role": "user", "content": user_prompt},
],
"max_tokens": max_tokens,
"temperature": 0.0,
"stream": True,
}
start = time.perf_counter()
first_token_time: Optional[float] = None
token_chunks = 0
try:
async with client.stream("POST", url, json=payload) as resp:
if resp.status_code != 200:
body = await resp.aread()
return RequestMetrics(
ok=False,
ttft_ms=0.0,
total_ms=(time.perf_counter() - start) * 1000.0,
output_tokens=0,
error=f"HTTP {resp.status_code}: {body.decode('utf-8', 'ignore')[:120]}",
)
async for line in resp.aiter_lines():
if not line.startswith("data: "):
continue
data = line[6:].strip()
if data == "[DONE]":
break
try:
event = json.loads(data)
delta = event["choices"][0]["delta"].get("content")
except (KeyError, IndexError, json.JSONDecodeError):
continue
if delta:
if first_token_time is None:
first_token_time = time.perf_counter()
token_chunks += 1
end = time.perf_counter()
ttft_ms = ((first_token_time or end) - start) * 1000.0
return RequestMetrics(
ok=True,
ttft_ms=ttft_ms,
total_ms=(end - start) * 1000.0,
output_tokens=token_chunks,
)
except Exception as exc:
return RequestMetrics(
ok=False,
ttft_ms=0.0,
total_ms=(time.perf_counter() - start) * 1000.0,
output_tokens=0,
error=str(exc),
)
async def run_benchmark(
base_url: str,
model: str,
concurrency: int,
total_requests: int,
max_tokens: int,
) -> None:
limits = httpx.Limits(
max_connections=concurrency + 16,
max_keepalive_connections=concurrency,
)
timeout = httpx.Timeout(connect=10.0, read=120.0, write=30.0, pool=30.0)
semaphore = asyncio.Semaphore(concurrency)
async with httpx.AsyncClient(limits=limits, timeout=timeout) as client:
# Warmup pass to populate CUDA graphs and prefix caches
await send_streaming_request(
client, base_url, model, "Warmup request: define KV caching.", 32
)
async def worker(idx: int) -> RequestMetrics:
prompt = (
f"Request #{idx}: Explain how continuous batching reduces "
f"tail latency in GPU inference servers."
)
async with semaphore:
return await send_streaming_request(
client, base_url, model, prompt, max_tokens
)
wall_start = time.perf_counter()
results = await asyncio.gather(*(worker(i) for i in range(total_requests)))
wall_elapsed = time.perf_counter() - wall_start
ok_results = [r for r in results if r.ok]
errors = [r for r in results if not r.ok]
total_chunks = sum(r.output_tokens for r in ok_results)
print(f"\nEndpoint: {base_url} | Model: {model}")
print(f"Concurrency: {concurrency} | Requests: {total_requests}")
print(f"Success Rate: {len(ok_results)}/{total_requests} ({len(ok_results)/total_requests*100:.1f}%)")
if ok_results:
ttfts = sorted(r.ttft_ms for r in ok_results)
p50_ttft = statistics.median(ttfts)
p95_ttft = ttfts[min(len(ttfts) - 1, int(len(ttfts) * 0.95))]
decode_ms = [max(r.total_ms - r.ttft_ms, 1.0) for r in ok_results if r.output_tokens > 1]
tpot_ms = [
(r.total_ms - r.ttft_ms) / max(r.output_tokens - 1, 1)
for r in ok_results
if r.output_tokens > 1
]
print(f"TTFT p50: {p50_ttft:.1f} ms | TTFT p95: {p95_ttft:.1f} ms")
if tpot_ms:
print(f"TPOT median: {statistics.median(tpot_ms):.2f} ms/chunk")
print(f"Aggregate Throughput: {total_chunks / wall_elapsed:.1f} chunks/sec")
if errors:
print(f"Sample Error: {errors[0].error}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Benchmark vLLM, SGLang, or Ollama")
parser.add_argument("--base-url", required=True, help="e.g. http://localhost:8000/v1")
parser.add_argument("--model", required=True, help="Model name exposed by the server")
parser.add_argument("--concurrency", type=int, default=32)
parser.add_argument("--requests", type=int, default=128)
parser.add_argument("--max-tokens", type=int, default=128)
args = parser.parse_args()
asyncio.run(
run_benchmark(
args.base_url, args.model, args.concurrency, args.requests, args.max_tokens
)
)
Execute the exact same benchmark script against all three endpoints to generate apples-to-apples latency and throughput curves:
# Benchmark vLLM (port 8000)
python bench_serving.py --base-url http://localhost:8000/v1 --model Qwen/Qwen2.5-7B-Instruct --concurrency 32 --requests 128
# Benchmark SGLang (port 30000)
python bench_serving.py --base-url http://localhost:30000/v1 --model Qwen/Qwen2.5-7B-Instruct --concurrency 32 --requests 128
# Benchmark Ollama (port 11434)
python bench_serving.py --base-url http://localhost:11434/v1 --model qwen2.5:7b-instruct --concurrency 32 --requests 128
Interpreting Benchmark Outputs and Guarding Against Warmup Skew
Always discard or isolate the first request before timing TTFT. Both vLLM and SGLang perform lazy initialization or CUDA graph warmup on early traffic, and Ollama loads model weights from disk into VRAM on cold start if OLLAMA_KEEP_ALIVE expired.
To test prefix-caching efficiency accurately, run two passes: one with a shared 4,000-token system prompt (measuring RadixAttention and V1 APC hit rates) and one with randomized unique prefixes per request (measuring raw prefill saturation). Also check that stream_options={"include_usage": true} or tokenizer-exact counts are enabled if your model emits multi-token SSE chunks.
KV-Cache OOM and Concurrency Troubleshooting Runbook
Most production crashes across vLLM, SGLang, and Ollama stem from how each engine reserves Key-Value cache memory. vLLM and SGLang statically pre-allocate massive VRAM pools at startup, while Ollama multiplies per-slot KV memory linearly with OLLAMA_NUM_PARALLEL and rejects overflow traffic once its FIFO queue saturates.
Figure 2: Diagnostic and mitigation stack for resolving CUDA OOM errors, KV-cache saturation, and queue latency spikes.
Diagnosing failures rapidly depends on noting when the error fires: during server startup, during the first long-context prefill, or mid-traffic under burst concurrency.
| Symptom / Error Signature | Engine | Root Cause | Deterministic Fix |
|---|---|---|---|
CUDA out of memory during startup / graph capture |
vLLM | --gpu-memory-utilization (default 0.90) leaves too little headroom for CUDA graphs or draft models |
Drop --gpu-memory-utilization to 0.80 or 0.75 and set PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True |
| Startup OOM after loading weights | SGLang | --mem-fraction-static consumes VRAM needed for dynamic workspace and tensor-parallel buffers |
Lower --mem-fraction-static to 0.75 and cap --context-length to real prompt size |
| OOM on first long prompt prefill | vLLM / SGLang | Default --max-model-len (e.g., 128K) over-allocates KV blocks and activation buffers |
Explicitly pass --max-model-len 8192 (vLLM) or --context-length 8192 (SGLang) |
| Mid-flight preemption / p95 TTFT spike | SGLang / vLLM | Too many concurrent sequences trigger KV eviction or radix cache thrashing | Reduce --max-num-seqs (e.g., 64) and enable FP8 weight or KV-cache quantization |
HTTP 503 Service Unavailable or 60s+ timeouts |
Ollama | Active slots (OLLAMA_NUM_PARALLEL) and OLLAMA_MAX_QUEUE (512) are saturated |
Cap concurrency to 2-8 users or migrate the endpoint to vLLM or SGLang |
| Sudden drop to < 5 tok/s under parallel load | Ollama | OLLAMA_NUM_PARALLEL multiplied KV cache past VRAM, forcing CPU RAM spillover |
Set OLLAMA_FLASH_ATTENTION=1 and OLLAMA_KV_CACHE_TYPE=q8_0 (or q4_0), then verify with ollama ps |
Tuning vLLM gpu-memory-utilization and max-model-len
vLLM’s --gpu-memory-utilization parameter defaults to 0.90, instructing the engine to claim 90% of available GPU memory for weights plus the PagedAttention KV-cache pool. Even when nvidia-smi reports 2 GB of free memory, CUDA graph capture, activation spikes, or speculative decoding draft weights can overflow the remaining headroom.
When diagnosing a vLLM CUDA graph capture OOM, step --gpu-memory-utilization down to 0.80 (or 0.70 to 0.75 if enabling speculative decoding or multimodal vision encoders). Pair that change with an explicit --max-model-len cap matching your application’s actual context window instead of inheriting a 128K default, as documented in the vLLM Official Documentation.
[!WARNING] Never leave
--max-model-lenunbounded on 128K or 1M context models when running on 24 GB to 48 GB GPUs. Even if your application only sends 4,000-token prompts, oversized context limits shrink the available concurrent batch pool and trigger premature request preemption.
Fixing SGLang mem-fraction-static OOMs and Radix Eviction Spikes
SGLang controls static VRAM reservation through --mem-fraction-static, which allocates memory upfront for both model weights and the RadixAttention KV-cache pool. If model weights already occupy 65% to 70% of GPU memory, leaving --mem-fraction-static too high starves dynamic runtime buffers, hybrid Mamba state caches, and NCCL tensor-parallel communication buffers.
Drop --mem-fraction-static to 0.75 and export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True before launching the server to stop PyTorch allocator fragmentation from triggering false OOMs when free memory still exists. If you observe SGLang radix cache eviction latency spikes during bursts, lower concurrent batch caps (--max-running-requests) or switch to --quantization fp8 so more prefix tree nodes stay hot in VRAM.
Preventing Ollama 503 Queue Starvation and KV-Cache Exhaustion
In Ollama, every parallel slot configured by OLLAMA_NUM_PARALLEL reserves its own full KV-cache buffer, meaning memory scales linearly:
Total Memory = Model Weight Size + (OLLAMA_NUM_PARALLEL * Per-Context KV Cache Size)
At 32K context lengths, four parallel streams can consume more VRAM for KV caches than the quantized model weights themselves. Always enable OLLAMA_FLASH_ATTENTION=1 alongside OLLAMA_KV_CACHE_TYPE=q8_0 (50% KV memory reduction) or q4_0 (75% reduction) whenever raising OLLAMA_NUM_PARALLEL above 1.
When incoming requests exceed OLLAMA_NUM_PARALLEL, Ollama buffers them inside a FIFO queue bounded by OLLAMA_MAX_QUEUE (default 512). Once both execution slots and the queue fill, Ollama immediately rejects new calls with HTTP 503 Service Unavailable. If you see recurring 503 errors or CPU layer spillover in ollama ps, verify your hardware budget with our AI VRAM requirements sizing guide and graduate the workload to vLLM or SGLang.
Frequently Asked Questions About vLLM, SGLang, and Ollama
Is SGLang faster than vLLM for production LLM serving?
SGLang frequently beats vLLM by 10% to 17% on multi-turn agentic loops, RAG pipelines, and strict JSON schema decoding because RadixAttention and XGrammar minimize prefix recomputation and logit masking overhead. vLLM matches or surpasses SGLang on broad multi-tenant APIs with disjoint prompts, dynamic multi-LoRA routing, and hardware-native quantization formats such as NVFP4 on Blackwell GPUs.
Can Ollama handle multiple concurrent users in production?
Ollama can serve roughly 2 to 8 concurrent users when tuned with OLLAMA_NUM_PARALLEL, Flash Attention, and quantized KV caches, but it lacks continuous paged batching for heavy traffic. Beyond 10 to 32 simultaneous requests, Ollama queues incoming prompts sequentially, causing Time to First Token to spike past 48 seconds and returning HTTP 503 errors once OLLAMA_MAX_QUEUE fills.
What is the architectural difference between PagedAttention and RadixAttention?
vLLM’s PagedAttention divides each sequence’s KV cache into non-contiguous virtual memory blocks to eliminate fragmentation, with the V1 engine adding hash-based Automatic Prefix Caching across blocks. SGLang’s RadixAttention organizes those cached KV tensors inside a live radix tree with LRU eviction, allowing branching multi-turn agents and few-shot prompts to share arbitrary prefixes automatically.
Which serving engine is best for structured JSON output and tool calling?
SGLang is the strongest choice for strict structured JSON output because its native XGrammar backend compiles schemas into compressed finite state machines and overlaps bitmask generation with the GPU forward pass. This architecture raises JSON schema compliance to 96% to 98.2%+ with minimal token-per-second latency penalty compared to unconstrained decoding.
Can vLLM or SGLang run natively on Apple Silicon Macs?
Both vLLM and SGLang target NVIDIA CUDA and AMD ROCm servers first, though community backends such as vllm-metal and experimental SGLang MLX extensions enable local testing on macOS. For daily Apple Silicon development, Ollama remains the most reliable option because it ships first-class llama.cpp Metal and native Apple MLX runners out of the box.
How do you fix KV-cache out-of-memory errors in vLLM and SGLang?
Lower --gpu-memory-utilization in vLLM (from 0.90 to 0.75 or 0.80) or --mem-fraction-static in SGLang (to 0.75) so CUDA graph capture and runtime activations have sufficient VRAM headroom. Cap --max-model-len to your real prompt budget, restrict --max-num-seqs, and export PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True to prevent allocator fragmentation.
Do vLLM, SGLang, and Ollama support dynamic multi-LoRA serving?
Both vLLM and SGLang support dynamic per-request multi-LoRA routing on CUDA GPUs using specialized Punica and SGMV kernels so one base model serves dozens of tenant adapters simultaneously. Ollama does not support dynamic per-request LoRA multiplexing and instead requires building separate Modelfiles or merging adapter weights ahead of time.
Conclusion: Building a Staged LLM Serving Stack
Most engineering teams do not need to pick a single serving runtime for every environment because all three expose OpenAI-compatible HTTP endpoints. Start local development and workstation testing on Ollama to take advantage of Apple Silicon MLX, GGUF portability, and zero-config Modelfiles.
When moving an application to shared NVIDIA or AMD GPU clusters, graduate to SGLang if your traffic is dominated by multi-turn agents, shared RAG prefixes, and strict JSON schemas, or standardize on vLLM V1 when you need maximum multi-tenant throughput across disjoint prompts, broad model support, and dynamic multi-LoRA fleets. Run the async Python benchmark script above against your exact prompt length and concurrency target before committing GPU budget.