Router Examples
Router Examples
For quick start instructions, see the Router README. This document provides further examples for using the Dynamo Router, including Python API usage, Kubernetes deployments, and custom routing patterns.
Table of Contents
- Using KvRouter Python API
- K8s Examples
- Routing Patterns
- Custom Routing Example: Minimizing TTFT
- KV Event Publishing for Custom Engines
- Global Router (Hierarchical Routing)
Using KvRouter Python API
Instead of launching the KV Router via command line, you can create a KvRouter object directly in Python. This allows per-request routing configuration overrides.
Multiple Routers in Same Process: If you need to run multiple KvRouter instances for fault tolerance or load distribution, you must launch them in separate processes (e.g., using python -m dynamo.frontend with different ports). Creating multiple KvRouter objects in the same Python process is not supported - they share the same cancellation token from the component’s primary lease, so dropping one router will cancel all routers in that process. For in-process routing, use a single KvRouter instance.
Methods
The KvRouter provides the following methods:
-
generate(token_ids, model, ...): Route and execute a request, returning an async stream of responses. Automatically handles worker selection, state tracking, and lifecycle management. -
best_worker(token_ids, router_config_override=None, request_id=None): Query which worker would be selected for given tokens. Returns(worker_id, dp_rank, overlap_blocks).- Without
request_id: Query-only, doesn’t update router state - With
request_id: Updates router state to track the request. Note: If used withrequest_id, you must callmark_prefill_complete()andfree()at the appropriate lifecycle points to maintain accurate load tracking
- Without
-
get_potential_loads(token_ids): Get detailed load information for all workers, including potential prefill tokens and active decode blocks. Returns a list of load dictionaries. -
mark_prefill_complete(request_id): Signal that a request has completed its prefill phase. Only used for manual lifecycle management when usingbest_worker()for manual routing instead ofgenerate(). -
free(request_id): Signal that a request has completed and its resources should be released. Only used for manual lifecycle management when usingbest_worker()for manual routing instead ofgenerate(). -
dump_events(): Dump all KV cache events from the router’s indexer as a JSON string. Useful for debugging and analysis.
Setup
First, launch your backend engines:
Example Script
K8s Examples
For basic Kubernetes deployment with the KV Router, see the Kubernetes Deployment section in the Quick Start guide.
Complete K8s Examples
- TRT-LLM aggregated router example
- vLLM aggregated router example
- SGLang aggregated router example
- Distributed inference tutorial
For A/B Testing and Advanced K8s Setup: See the comprehensive KV Router A/B Benchmarking Guide for step-by-step instructions on deploying, configuring, and benchmarking the KV router in Kubernetes.
Example with Advanced Configuration
Alternative: Using Command Args in K8s
You can also pass CLI arguments directly in the container command:
Recommendation: Use environment variables for easier configuration management and consistency with Dynamo’s K8s patterns.
Routing Patterns
The KvRouter supports multiple usage patterns depending on your control requirements:
1. Automatic Routing (Recommended)
Call generate() directly and let the router handle everything:
- Best for: Most use cases
- Router automatically: Selects best worker, updates state, routes request, tracks lifecycle
2. Manual State Management (Advanced)
Use best_worker(request_id=...) to select and track, then manage the request yourself:
- Best for: Custom request handling with router state tracking
- Requires: Calling
mark_prefill_complete()andfree()at correct lifecycle points - Caution: Incorrect lifecycle management degrades load balancing accuracy
3. Hierarchical Router Probing
Query without state updates, then route through a chosen router:
- Best for: Multi-tier deployments (e.g., Envoy Gateway routing to multiple router groups)
- Advantage: Query multiple routers before committing to one
4. Custom Load-Based Routing
Use get_potential_loads() to implement custom routing logic:
- Best for: Custom optimization strategies beyond the built-in cost function
- Advantage: Full control over worker selection logic
- See also: Detailed example below in “Custom Routing Example: Minimizing TTFT”
All patterns support router_config_override to adjust routing behavior per-request without recreating the router.
Custom Routing Example: Minimizing TTFT
Here’s an example of using get_potential_loads() to implement custom routing that minimizes Time To First Token (TTFT) by selecting the worker with the least prefill work:
This approach gives you complete control over routing decisions, allowing you to optimize for different metrics based on your specific requirements. As some examples:
- Minimize TTFT: Select worker with lowest
potential_prefill_tokens - Maximize cache reuse: Use
best_worker()which considers both prefill and decode loads - Balance load: Consider both
potential_prefill_tokensandpotential_decode_blockstogether
See Router Design for architecture details and the cost function algorithm.
KV Event Publishing for Custom Engines
For full documentation on implementing KV event publishing for custom inference engines, see the dedicated KV Event Publishing for Custom Engines guide. It covers:
- Direct publishing: Call
publish_stored()/publish_removed()to push events over the Dynamo event plane - ZMQ relay: For engines that emit raw KV events over ZMQ (like vLLM and SGLang), the same
KvEventPublishersubscribes to the ZMQ socket and relays events automatically - API reference, event structure, ZMQ wire format, and best practices
Global Router (Hierarchical Routing)
For deployments with multiple worker pools, the Global Router enables hierarchical routing by sitting between the frontend and local routers. It selects the appropriate pool for each request based on configurable policies, supporting disaggregated topologies where pools are tuned for different workload characteristics.
- Component details:
components/src/dynamo/global_router/ - Example:
examples/hierarchical_planner/
See Also
- Router README: Quick start guide for the KV Router
- Router Guide: Configuration, tuning, and production setup
- Router Design: Architecture details and event transport modes