A high-performance, concurrency-hardened Smart Router and Gateway simulator designed to optimize
Time-To-First-Token (TTFT) and KV-cache utilization across distributed vLLM instances.
By employing a dynamic Radix Tree structure for token prefix-matching combined with an encapsulated, thread-safe Block Manager,
vllm-context-cache-router pins incoming stateful requests to the precise worker containing the warmest cache overlap,
maximizing cluster throughput while completely neutralizing race conditions under extreme load.
In high-throughput multi-turn LLM applications (e.g., compound AI systems, multi-agent frameworks, long-context retrieval), routing requests randomly or via simple Round-Robin destroys performance. Workers constantly evict and recompute identical system prompts, tool schemas, and chat histories, leading to severe TTFT degradation and unnecessary GPU compute cost.
vllm-ccr solves this with an advanced architectural approach:
- Max-Prefix Routing Strategy: The gateway dynamically tracks token allocations using an internal Radix Tree. Incoming payloads are analyzed, and routing decisions are made by evaluating which distributed worker possesses the longest deterministic prefix match.
- Production-Grade Concurrency Isolation: Completely eliminates Time-of-Check to Time-of-Use (TOCTOU) vulnerabilities. The state loop encapsulates internal dataclasses behind an atomic reentrant lock (
threading.RLock) and serves immutable, frozen snapshots (WorkerStats) to callers, ensuring metrics reads never block or corrupt mutation threads. - Deterministic LRU Eviction & State Hygiene: Implements an advanced Least Recently Used (LRU) cache clearing routine that safely targets unallocated warm blocks while ensuring active in-flight blocks are never prematurely freed or corrupted.
- Native Backpressure & Resiliency: Replaces raw server crashes during cache exhaustion with a custom
KVCacheExhaustedException, allowing the FastAPI gateway to gracefully degrade by shedding load with standardHTTP 429 (Too Many Requests)responses and explicitRetry-Afterheaders.
[ Incoming Client Request ]
|
v
+-----------------+
| FastAPI Gateway |<--------------+
+--------+--------+ |
| |
v |
+-----------------+ +------+------+
| Smart Router +------->| Prometheus |
+--------+--------+ | Telemetry |
| +-------------+
+------------------+------------------+
v v
+------------------+ +------------------+
| Worker 0 (Warm) | | Worker 1 (Cold) |
+------------------+ +------------------+
| +--------------+ | | +--------------+ |
| | Radix Tree | | | | Radix Tree | |
| +--------------+ | | +--------------+ |
| +--------------+ | | +--------------+ |
| | BlockManager | | | | BlockManager | |
| +--------------+ | | +--------------+ |
+------------------+ +------------------+
- Gateway (
vllm_ccr.gateway): Exposes an OpenAI-compliant/v1/chat/completionslayer alongside a production/metricstelemetry endpoint. - Router (
vllm_ccr.router): Contains the core logic executing maximum prefix evaluations, load tracking, and fallback allocation choices. - Cache Layer (
vllm_ccr.cache): Manages the physical representation of the simulated GPU memory layout. Tokens are broken into discrete block arrays where metadata tracking is strictly separated from mutable lookups.
In 2026, production AI deployments have transitioned from monolithic single-turn models to Compound AI Systems and continuous Multi-Agent Orchestration Loops (e.g., autonomous workflows executing iterative reasoning, reflection, and tools usage). These systems pass massive, evolving state contexts---including thousands of tokens of system schemas, neuro-symbolic guardrails, and conversation histories---on every iteration.
Standard infrastructure load balancers (e.g., Least-Connections, Round-Robin, or simple IP Hashing) are state-blind. When concurrent agentic loops execute parallel tool calls or sub-agent routines, their requests are scattered across different physical GPU nodes. This scatters identical prefix sequences across the cluster, forcing workers to constantly evict warm data and redundantly recompute KV-caches. This destroys Time-To-First-Token (TTFT) performance and wastes valuable GPU SRAM.
vllm-context-cache-router acts as the missing state-aware centralized orchestration fabric that synchronizes these distributed environments.
- Cross-Node Prefix Coherence: By managing a global, thread-safe Radix Tree abstraction over individual worker topologies, the router guarantees that complex multi-turn multi-agent workflows are deterministically pinned to the exact worker containing the highest prefix overlap.
- Mitigation of the Concurrent Allocation Panic: As context windows scale, concurrent multi-turn requests hitting a cluster at the same millisecond frequently trigger race conditions during physical chunk allocation. This repo introduces atomic reentrant lock (
RLock) scheduling and immutableWorkerStatsstate-isolation, preventing the over-allocation panics common in high-concurrency event loops. - Graceful Degradation via Real-Time Telemetry: Under severe load spikes, instead of allowing internal worker engines to undergo hard OOM panics or drop active inference streams, the repository implements strict backpressure compilation (
KVCacheExhaustedException), automatically translating cluster exhaustion into clean, load-sheddingHTTP 429actions with standardRetry-Aftermetrics.
The design of vllm-ccr bridges the gap between raw hardware-level page allocation frameworks and application-layer distributed routing meshes. Key foundational references include:
- RadixAttention (SGLang Paradigm): Adapting the concept of using a Radix Tree to manage KV-cache lifetime dynamically on a single device, scaling the abstraction up to operate as a centralized router across a distributed network of independent inference workers.
- vLLM PagedAttention & Automatic Prefix Caching (APC): Built to perfectly complement environments running
PagedAttention. While vLLM manages token blocks at the physical kernel level,vllm-ccracts as the macro-scheduler to ensure requests arrive at the worker best positioned to utilize its local block layout. - Compound AI System Orchestration Loops: Architected specifically to meet the high-concurrency, low-latency requirements of multi-agent runtimes, where maintaining a warm context tree is the single most effective way to optimize operational compute budgets.
- Python 3.12+
- Linux/macOS environment
uv(recommended fast Python package installer) or standardpip
-
Clone the repository:
git clone https://github.com/aragit/vllm-context-cache-router.git cd vllm-context-cache-router -
Create a virtual environment and install dependencies:
Using
uv:uv venv source .venv/bin/activate uv pip install -e .
Or using standard
pip:python3 -m venv .venv source .venv/bin/activate pip install -e .
To fire up the Uvicorn-backed FastAPI server process locally:
uv run python -m vllm_ccr.mainThe server will initialize 4 simulated execution workers and begin listening on http://0.0.0.0:8000.
1. Cold Start Initialization
Send a request containing a shared system validation prefix:
curl -X POST http://localhost:8000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "vllm-ccr-sim",
"messages": [
{"role": "system", "content": "SYSTEM_VALIDATION: CACHE_TAG=0X44A2. SECURE_COMPLIANCE=TRUE."},
{"role": "user", "content": "Ingest initial baseline token array."}
]
}' | jqExpected Behavior: The router assigns this to Worker 0, registering a cache_hit_ratio of 0.000 and executing at full cold-start latency (~550ms).
2. Targeted Warm Prefix Match
Send a second request leveraging the exact same system context tag but with a different user payload:
curl -X POST http://localhost:8000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "vllm-ccr-sim",
"messages": [
{"role": "system", "content": "SYSTEM_VALIDATION: CACHE_TAG=0X44A2. SECURE_COMPLIANCE=TRUE."},
{"role": "user", "content": "Execute secondary pipeline extraction block."}
]
}' | jqExpected Behavior: The router maps the prefix match, keeps the execution pinned to Worker 0, registers a positive cache_hit_ratio, and drops TTFT latency by over 40%.
The router exposes native Prometheus metrics to feed standard operational dashboards. You can poll the endpoint directly:
curl http://localhost:8000/metrics| Metric Name | Type | Description |
|---|---|---|
vllm_ccr_requests_total |
Counter | Cumulative requests broken down by target model. |
vllm_ccr_cache_hits_total |
Counter | Total number of requests finding successful block overlaps. |
vllm_ccr_worker_utilization |
Gauge | Real-time KV-cache block occupancy per worker_id. |
vllm_ccr_ttft_seconds |
Histogram | High-resolution tracking of time-to-first-token latencies. |
All settings are env-overridable with the VLLM_CCR_ prefix:
| Variable | Default | Description |
|---|---|---|
VLLM_CCR_WORKER_COUNT |
4 |
Number of simulated workers |
VLLM_CCR_BLOCK_SIZE |
16 |
Tokens per KV block |
VLLM_CCR_MAX_BLOCKS_PER_WORKER |
128 |
Max blocks per worker |
VLLM_CCR_MAX_CONCURRENT_PER_WORKER |
8 |
Max concurrent requests per worker |
VLLM_CCR_MAX_CONCURRENT_TOTAL |
32 |
Max total concurrent requests |
VLLM_CCR_ROUTING_STRATEGY |
max_prefix |
max_prefix, round_robin, or least_loaded |
VLLM_CCR_PORT |
8000 |
Server port |
VLLM_CCR_SIMULATED_TTFT_COLD_MS |
550.0 |
Cold TTFT in ms |
VLLM_CCR_SIMULATED_TTFT_WARM_MS |
12.0 |
Warm TTFT in ms |
| Method | Path | Description |
|---|---|---|
POST |
/v1/chat/completions |
OpenAI-compatible chat completion |
GET |
/v1/models |
List available models |
GET |
/metrics |
Prometheus metrics |
GET |
/health |
Health check |
GET |
/debug/tree |
Radix tree statistics |
GET |
/debug/pool |
Worker pool statistics |
The engine includes a rigorous testing setup validating everything from basic data insertions to multi-threaded memory stress profiles.
Run the entire 48-test verification framework via:
.venv/bin/python -m pytest tests/ -vThe repository includes dedicated regression tests inside tests/test_block_manager.py (TestBlockManagerConcurrency) that explicitly spawn 20+ simultaneous workers executing rapid mutations. These tests explicitly guarantee:
- Thread-Safe Copy Segregation: Verifies that internal structures always pass snapshots, ensuring no asynchronous operations mutate data mid-iteration.
- Capacity Boundary Enforcements: Verifies that concurrent block allocations can never force the underlying memory queue into negative availability boundaries.
vllm-context-cache-router/
├── src/vllm_ccr/
│ ├── cache/
│ │ ├── __init__.py
│ │ └── block_manager.py # Thread-safe KV-cache block allocation (RLock)
│ ├── gateway/
│ │ ├── __init__.py
│ │ └── app.py # FastAPI gateway + OpenAI-compliant endpoints
│ ├── models/
│ │ ├── __init__.py
│ │ ├── chat.py # Pydantic request/response models
│ │ └── telemetry.py # Prometheus metrics data models
│ ├── radix_tree/
│ │ ├── __init__.py
│ │ └── tree.py # Compressed prefix tree for cache tracking
│ ├── router/
│ │ ├── __init__.py
│ │ └── smart_router.py # Max-prefix / round-robin / least-loaded routing
│ ├── telemetry/
│ │ ├── __init__.py
│ │ └── collector.py # Prometheus metrics collector + structlog
│ ├── workers/
│ │ ├── __init__.py
│ │ ├── pool.py # Worker pool with global concurrency semaphore
│ │ └── worker.py # Simulated vLLM worker with prefill/decode
│ ├── config.py # Pydantic-settings configuration
│ ├── exceptions.py # KVCacheExhaustedException
│ ├── main.py # Uvicorn entrypoint
│ └── __init__.py
├── tests/
│ ├── __init__.py
│ ├── test_block_manager.py # Block allocation + concurrency regression tests
│ ├── test_gateway.py # FastAPI endpoint integration tests
│ ├── test_radix_tree.py # Radix tree CRUD + eviction tests
│ └── test_router.py # Routing strategy tests
├── benchmarks/
│ └── stress_test.py # High-load stress testing harness
├── .github/workflows/ci.yml # GitHub Actions CI pipeline
├── pyproject.toml # Project config + tooling (ruff, mypy, pytest)
├── .python-version # Pins Python 3.12 for uv
├── README.md
└── LICENSE
| Component | Technology |
|---|---|
| Language | Python 3.12+ |
| Web Framework | FastAPI + Uvicorn |
| Data Validation | Pydantic v2 + pydantic-settings |
| Concurrency | threading.RLock + asyncio.Semaphore |
| Metrics | Prometheus Client |
| HTTP Client | httpx |
| Serialization | orjson |
| Logging | structlog |
| Package Manager | uv |
| Build Backend | Hatchling |
| Linting | Ruff |
| Type Checking | Mypy |
| Testing | Pytest + pytest-asyncio |
If you use vllm-context-cache-router in your research or production systems, please cite:
@software{anicomanesh2026vllm_ccr,
author = {Arash Nicoomanesh},
title = {vLLM Context Cache Router: A Concurrency-Hardened Smart Router for Distributed KV-Cache Optimization},
year = {2026},
url = {https://github.com/aragit/vllm-context-cache-router},
license = {MIT}
}MIT