Skip to navigation

Write Custom Routing Strategies

Build Rust filters, scorers, and pickers for the Dynamo frontend or EPP
View as MarkdownOpen in Claude

Experimental. A custom worker-selection policy controls how Dynamo filters and scores eligible workers, then selects one. Dynamo still owns discovery, eligibility, queueing, reservations, accounting, and metrics.

How It Works

This feature replaces the worker-ranking part of Dynamo’s routing pipeline. A WorkerFilter can exclude a host-eligible worker, a WorkerScorer assigns a finite cost to each remaining worker, Dynamo adds costs from all configured scorers, and a WorkerPicker chooses one row from the scored candidates. Filters run in declaration order. Each scorer receives all surviving workers in one call and writes one cost per worker. Rejecting every worker returns an error. Lower costs rank first by convention, but the picker can implement deterministic selection, sampling, tie-breaking, or policy-local state. Dynamo continues to own discovery, eligibility, score validation, accounting, and reservation.

Incoming request Dynamo eligibility filters WorkerFilter(s)keep or reject each worker WorkerScorer(s)one cost per worker Dynamo sums scorer costs WorkerPickerone candidate row Dynamo validates the row Accounting and reservation

For multiple compile-checked policies, see the custom policy examples. Repository contributors who use a coding agent must also provide the worker-selection API rules.

Use a Built-In Policy First

The Dynamo frontend ships built-in worker-selection policies, in lib/router-plugins. Selecting one needs router-policy YAML only — no policy crate, no rebuild, no private image. See Worker-Selection Policies for the available types and how to select one.

Write your own policy when no shipped policy expresses the rule you need. The rest of this page covers that case; a custom policy is added alongside the shipped ones, so you keep both.

Choose the Policy Stage

To classify or reject requests before they enter the scheduling queue, or hold them in it, use a request classifier. It can be combined with a worker-selection policy.

StageInputOutputUse this stage for
WorkerFilterThe WorkerSelectionRequest and one host-eligible workerKeep or rejectThe rule is a hard requirement, not a ranking preference
WorkerScorerThe WorkerSelectionRequest, all surviving workers, and an aligned output sliceOne finite cost per workerThe rule ranks workers or adds a penalty
WorkerPickerAll eligible workers and their total costsOne row indexThe rule samples, breaks ties, tracks policy state, or ignores total cost
Policy factoryOne WorkerSelectionPolicyContext: the selection settings, worker type, and routing partition the policy is built forOne WorkerSelectionPolicyPrefill, decode, models, or routing groups need different components

An external policy owns its filters, scorers, and picker. Dynamo’s default scorer and picker are internal and can change with the built-in routing algorithm.

Public Plugin API and Compatibility

A plugin crate depends on dynamo-kv-router alone and imports the module for the kind of plugin it is. The path says how stable a name is: the plugin API or plugins::experimental.

ModulePublic APICompatibility
plugins::worker_selectionWorkerFilter, WorkerScorer, WorkerPicker, WorkerSelectionPolicy, WorkerSelectionRequest, the picker’s table, WorkerSelectionPolicyContext, SelectionConfig, factories, and everything in the root plugins moduleThe plugin API can change in a minor release. Each change is listed in that release’s deprecation notes
plugins::request_classifierRequestClassifier, ClassifyRequest, ClassifyEvent, RequestProgress, its registration types, and everything in the root plugins moduleSame
pluginsOnly what both kinds share: RouterPluginRegistry, WorkerInputs, the rows both read (WorkerCandidates, WorkerCandidate, WorkerLoadInput, WorkerCacheInput), WorkerInfo, RequestInfo, SessionContext, and the identity types. A crate that only registers plugins imports thisSame
plugins::experimentalOne submodule per API, imported by name: the resident block counts and KVCR occupancy in resident_blocks, decode progress in decode_progress, the dispatch gate in dispatch_gate, and hint policies in hints. An API’s names move into a kind’s module when it is readyNone: an item can change or be removed in any release
plugins::testingSelectionCase and CaseWorker, which run a policy over a request and workers that a test describes. Import it only from tests and benchesSame as the plugin API

A policy and a classifier read workers through the same rows, so a value added to an input group reaches both.

plugins::host holds what a routing host names to resolve and run plugins, such as the resolved RouterPlugins bundle. Plugin crates do not import it. The two kind modules hold no host-only name: a host imports those from plugins::host or from the owning crate’s host module.

Dynamo owns scheduler queues, eligibility checks, reservations, lifecycle synchronization, and the default selector implementation. Low-level host interfaces such as WorkerSelector are used to connect Dynamo components; external plugins use WorkerSelectionPolicy.

Version 1.7 removed the compatibility import paths for these contracts, such as dynamo_kv_router::WorkerFilter and dynamo_kv_router::scheduling::RequestClassifier, along with the WorkerSelectionPolicyRegistry alias, the worker-only RouterPluginRegistry::register method, and the frontend worker_selection_policy_factory setter. Use RouterPluginRegistry and register worker policies with register_worker_selection.

Build the Policy

Create the Policy and Catalog Crates

Set the Dynamo checkout and policy project paths:

# Set the source and destination paths used by the remaining commands.
export DYNAMO_DIR=/work/dynamo
export POLICY_DIR=/work/acme-routing
# Create one crate for the policy and one crate for policy registration.
mkdir -p "$POLICY_DIR"
cargo init --lib --name acme-routing-policy "$POLICY_DIR/policy"
cargo init --lib --name acme-routing-catalog "$POLICY_DIR/catalog"

Add dynamo-kv-router from the same checkout that builds the frontend or EPP:

# Add the worker-selection API to the policy crate.
cargo add \
--manifest-path "$POLICY_DIR/policy/Cargo.toml" \
--path "$DYNAMO_DIR/lib/router/kv-router" \
dynamo-kv-router
# Add parameter deserialization to the policy crate.
cargo add \
--manifest-path "$POLICY_DIR/policy/Cargo.toml" \
--features derive serde
# Add the policy crate to the catalog.
cargo add \
--manifest-path "$POLICY_DIR/catalog/Cargo.toml" \
--path "$POLICY_DIR/policy" \
acme-routing-policy
# Add the registry API to the catalog.
cargo add \
--manifest-path "$POLICY_DIR/catalog/Cargo.toml" \
--path "$DYNAMO_DIR/lib/router/kv-router" \
dynamo-kv-router

Filter Workers

A filter answers a hard yes-or-no question about one worker that already passed Dynamo’s eligibility checks. Return true to keep the worker or false to remove it. Use a filter only when the worker must not receive the request; use a scorer for preferences.

This filter keeps workers with at least the configured number of device-resident overlap blocks:

use dynamo_kv_router::plugins::worker_selection::{
WorkerCandidate, WorkerFilter, WorkerInputs, WorkerSelectionPolicyError, WorkerSelectionRequest,
};
struct MinimumDeviceOverlapFilter {
minimum_blocks: f64,
}
impl WorkerFilter for MinimumDeviceOverlapFilter {
fn required_worker_inputs(&self) -> WorkerInputs {
WorkerInputs::CACHE
}
fn keep(
&self,
_request: &WorkerSelectionRequest<'_>,
candidate: WorkerCandidate<'_>,
) -> Result<bool, WorkerSelectionPolicyError> {
let cache = candidate
.cache()
.ok_or_else(|| WorkerSelectionPolicyError::failed("cache input unavailable"))?;
Ok(cache.device_overlap_blocks() >= self.minimum_blocks)
}
}

Dynamo runs filters in declaration order before scoring. A worker must pass every configured filter. If no workers remain, selection returns an error.

Pass filters to WorkerSelectionPolicy::new_with_filters. If the policy has no hard requirement, omit filters and use WorkerSelectionPolicy::new.

Score Workers

A scorer expresses a preference without excluding a worker. It writes one finite cost for each worker into a host-owned output slice. Lower total cost is better by convention.

This scorer ranks workers by active requests above the batch minimum:

use dynamo_kv_router::plugins::worker_selection::{
WorkerCandidates, WorkerInputs, WorkerScorer, WorkerSelectionPolicyError,
WorkerSelectionRequest,
};
struct ActiveRequestsScorer;
impl WorkerScorer for ActiveRequestsScorer {
fn required_worker_inputs(&self) -> WorkerInputs {
WorkerInputs::LOAD
}
fn score(
&self,
_request: &WorkerSelectionRequest<'_>,
candidates: WorkerCandidates<'_>,
costs: &mut [f64],
) -> Result<(), WorkerSelectionPolicyError> {
let mut minimum = usize::MAX;
for candidate in candidates.iter() {
let load = candidate
.load()
.ok_or_else(|| WorkerSelectionPolicyError::failed("load input unavailable"))?;
minimum = minimum.min(load.active_requests());
}
for (candidate, cost) in candidates.iter().zip(costs) {
let load = candidate
.load()
.ok_or_else(|| WorkerSelectionPolicyError::failed("load input unavailable"))?;
*cost = (load.active_requests() - minimum) as f64;
}
Ok(())
}
}

Dynamo calls score once per scorer after filtering. The output slice matches the candidate order and length. Write every entry with a finite cost; an unwritten or invalid cost stops selection before picking.

A policy can stack multiple scorers. Dynamo calls them in declaration order and adds their costs. Dynamo rejects a non-finite contribution or total.

Pick a Worker

A picker makes the final choice after filtering and scoring. It sees every remaining worker and its total cost, then returns one row index. Most policies pick the lowest cost, but a picker can instead sample, break ties, or use policy-local state.

This picker selects the lowest-cost row:

use dynamo_kv_router::plugins::worker_selection::{
WorkerInputView, WorkerPicker, WorkerSelectionPolicyError, WorkerSelectionRequest,
};
struct LowestCostPicker;
impl WorkerPicker for LowestCostPicker {
fn pick(
&self,
_request: &WorkerSelectionRequest<'_>,
input: WorkerInputView<'_>,
) -> Result<usize, WorkerSelectionPolicyError> {
input
.candidates()
.iter()
.enumerate()
.min_by(|(_, left), (_, right)| left.cost().total_cmp(&right.cost()))
.map(|(row, _)| row)
.ok_or_else(|| WorkerSelectionPolicyError::failed("no eligible worker"))
}
}

Candidate order is unspecified, so inspect explicit values instead of relying on row order. Dynamo rejects an out-of-range index before accounting or reservation.

Parse Parameters and Create the Factory

The provider runs once at startup. Parse and validate all parameters there, then capture the validated values in the factory:

use std::sync::Arc;
use dynamo_kv_router::plugins::worker_selection::{
WorkerSelectionPolicyFactory, WorkerSelectionPolicyParameters,
WorkerSelectionPolicyProviderError,
};
use dynamo_kv_router::plugins::worker_selection::{
WorkerFilter, WorkerScorer, WorkerSelectionPolicy,
};
#[derive(serde::Deserialize)]
#[serde(deny_unknown_fields)]
struct Parameters {
min_device_overlap_blocks: f64,
}
fn provider(
parameters: &WorkerSelectionPolicyParameters,
) -> Result<WorkerSelectionPolicyFactory, WorkerSelectionPolicyProviderError> {
let parameters: Parameters = parameters.deserialize()?;
if !parameters.min_device_overlap_blocks.is_finite()
|| parameters.min_device_overlap_blocks < 0.0
{
return Err(WorkerSelectionPolicyProviderError::new(
"min_device_overlap_blocks must be a finite non-negative number",
));
}
let minimum_blocks = parameters.min_device_overlap_blocks;
Ok(Arc::new(move |context| {
let filters: Vec<Box<dyn WorkerFilter>> = vec![
Box::new(MinimumDeviceOverlapFilter { minimum_blocks }),
];
let scorers: Vec<Box<dyn WorkerScorer>> = vec![Box::new(ActiveRequestsScorer)];
WorkerSelectionPolicy::new_with_filters(
context.worker_type().as_str(),
filters,
scorers,
Box::new(LowestCostPicker),
)
}))
}

Dynamo calls the returned factory once per routing partition and passes it one WorkerSelectionPolicyContext:

AccessorValue
worker_type()The typed role of the worker pool: WorkerType::Aggregated, WorkerType::Prefill, WorkerType::Decode, or WorkerType::Encode. Branch on it when worker pools need different components
partition()The model and routing group the policy is built for. Use it for distinct model or routing-group state
selection_config()The scoring and sampling settings of the model that partition serves. They can differ per model, because a worker’s model card can replace the frontend’s settings. Read a setting with the accessor of its name, as in context.selection_config().router_temperature()

The context describes the partition, not a request. Filters, scorers, and pickers read each request through WorkerSelectionRequest.

Register the Policy

Expose a registration function from the policy crate:

use dynamo_kv_router::plugins::worker_selection::{
RouterPluginRegistry, WorkerSelectionPolicyRegistryError,
};
pub fn register(
registry: &mut RouterPluginRegistry,
) -> Result<(), WorkerSelectionPolicyRegistryError> {
registry.register_worker_selection("least-busy", Arc::new(provider))
}

Call this function from the catalog:

pub fn register(
registry: &mut RouterPluginRegistry,
) -> Result<(), WorkerSelectionPolicyRegistryError> {
acme_routing_policy::register(registry)
}

Choose a stable, unique type name. Unknown types, duplicate registrations, and invalid parameters stop startup.

Configure Each Role

Create $POLICY_DIR/worker-selection.yaml:

worker_selection:
aggregated:
type: least-busy
parameters:
min_device_overlap_blocks: 0
prefill:
type: least-busy
parameters:
min_device_overlap_blocks: 1
decode:
type: least-busy
parameters:
min_device_overlap_blocks: 0

worker_selection.aggregated, worker_selection.prefill, worker_selection.decode, and worker_selection.encode each select the policy for the matching worker pool. type selects a registered provider and parameters is the mapping that provider validates. A role may also be a bare type name when the provider accepts an empty parameters mapping. An omitted role uses Dynamo’s built-in policy; one role does not fall back to another role’s selection.

The pre-v1.7 form, a worker_selection.instances list of named {type, parameters} entries referenced by name from each role, still loads with a deprecation warning and is scheduled for removal in v1.8.

worker_selection.encode applies only to a surface-carrying encode worker set that constructs the standard KV chooser. It does not configure the surface-less multimodal encoder hop: EncoderRouter selects those workers independently with round-robin routing.

For prefill and decode, the selection order is the role-specific CLI or environment override, DYN_ROUTER_WORKER_SELECTION_POLICY, the matching YAML selection, and then Dynamo’s built-in policy. For aggregated and encode, the order is DYN_ROUTER_WORKER_SELECTION_POLICY, the matching YAML selection, and then the built-in policy. Set any selection to default to use the built-in policy for that scope.

Role selections are startup settings. Configure them in the worker-selection YAML, with the CLI flags or environment variables above, or through the Python KvRouterConfig constructor. They are not part of serialized KvRouterConfig JSON, and KvRouterConfig.from_json rejects those keys.

Check the Policy and Catalog

cargo check --manifest-path "$POLICY_DIR/catalog/Cargo.toml"

Add one focused test for each policy decision and one registration test for every type name. plugins::testing::SelectionCase describes a request and its workers and runs the policy through the router’s own selection path, so a test names no router type outside the plugin API. Put the test in a #[cfg(test)] module of the policy crate; the harness is for tests, and policy code does not import it:

#[cfg(test)]
mod tests {
use dynamo_kv_router::plugins::testing::{CaseWorker, SelectionCase};
use dynamo_kv_router::plugins::worker_selection::WorkerWithDpRank;
use super::*;
#[test]
fn prefers_the_worker_with_fewer_requests() {
let policy = WorkerSelectionPolicy::new(
"test",
vec![Box::new(ActiveRequestsScorer)],
Box::new(LowestCostPicker),
);
let selected = SelectionCase::new(160, 16)
.worker(29, CaseWorker::new().active_requests(4))
.worker(41, CaseWorker::new().active_requests(1))
.select(&policy)
.unwrap();
assert_eq!(selected, WorkerWithDpRank::from_worker_id(41));
}
}

SelectionCase::new takes the prompt length in tokens and the block size. CaseWorker sets the cache overlap, load, and capacity a worker reports; a value a test does not set reads as zero or unreported. For a registration test, plugins::testing::registered_policy builds the policy a registry holds under a type name from parameters written as a policy file writes them, in YAML, so a test can check that the provider accepts good parameters and rejects bad ones. For a request classifier, plugins::testing::registered_classifier does the same registration check, SelectionCase::classify runs it on the case, with the request and the worker rows both built from the case; for a classifier that reads no workers, plugins::testing::classify_request builds a request and plugins::testing::classify runs the classifier on it with no worker rows.

Shared Plugin Construction

The catalog registers plugin providers once. A host then calls resolve_plugins, which validates the selected configuration and returns a RouterPlugins bundle containing the configured factories. Resolution is a host action: it is on the plugins::host::RouterPluginRegistryHostExt trait, not on the registry a plugin’s register receives. Both the HTTP frontend and Python router pass this bundle to the shared router construction path. Each router receives fresh plugin instances; factories run during construction, not for each request.

Rust embedders start with the host registry, which includes the default policy, then register their catalog:

use dynamo_kv_router::plugins::host::RouterPluginRegistryHostExt;
use dynamo_llm::entrypoint::input::http::HttpFrontend;
use dynamo_llm::kv_router::plugins::router_plugin_registry;
let mut registry = router_plugin_registry();
acme_routing_catalog::register(&mut registry)?;
let plugins = registry.resolve_plugins(&kv_router_config)?;
HttpFrontend::default()
.plugins(plugins)
.run(distributed_runtime, engine_config)
.await?;
resolve_plugins catalog::register RouterPluginRegistry Router policy YAML RouterPlugins HTTP discovery Python KvRouter Shared router construction Per-router worker selector

Each worker policy is constructed once per routing partition. An empty bundle retains the default selector.

Available Signals

Worker identity and ordinary request metadata are always available. Dynamo calculates optional per-worker signals only for groups that a filter, scorer, or picker requests.

Routing cache resources start only if a component requests CACHE or a scorer requests KV_COPY. serve_indexer, enable_session_prefix_index, and the experimental RESIDENT_BLOCKS input require CACHE.

Request

Filters, scorers, and pickers receive each request as a WorkerSelectionRequest. Its info() returns a RequestInfo, the request facts every stage reads. A request classifier reads the same RequestInfo from its ClassifyRequest:

RequestInfo accessorMeaning
request_id()Optional request ID; None for a selection that tracks no request
isl_tokens()Input sequence length in tokens; zero when the request has no token IDs, such as embeddings-only input
session_context()Optional session metadata described below
pinned_worker()Exact worker and rank the request must run on, if any, such as an explicit request target, a hard session binding to one rank, or the worker Dynamo chose when it previewed the route. Read-only: Dynamo offers the policy only this worker. A session binding that Dynamo passes only as affinity_target() is not a pin

What exists only at worker selection is on the WorkerSelectionRequest itself:

AccessorMeaning
request_blocks()Incoming prompt size in KV blocks, rounded up
block_size()Tokens in one KV block
tracks_prefill_tokens()Whether the request contributes to prefill-load tracking
affinity_target()Optional advisory worker and data-parallel rank from soft session affinity
expected_output_tokens()Optional expected output length
priority_jump()Scheduler priority boost. Queue policies treat negative values as zero
strict_priority()Strict integer priority. The queue orders larger values first
router_temperature_override()Optional per-request router temperature override

Session Context

info().session_context() returns None when the request has no session metadata. This policy-facing view contains selected session metadata; it is not Dynamo’s internal request envelope. When present, it provides:

AccessorMeaning
session_id()Stable reasoning or tool-session identifier
parent_session_id()Optional parent session for subagents
session_final()Optional terminal marker for lifecycle-aware policies
input_trigger()Optional UserMessage, ToolResult, or Other request trigger
agent_headers()Opaque coding-agent header names mapped to ordered lists of string values

agent_headers() exposes the request’s ingress observations. Names are lowercase; values retain their original text, including unknown values and malformed embedded JSON. The map is shared across clones of the request and of the policy’s view of it without copying header strings, needs no WorkerInputs group, and is not interpreted by the default policy. Missing keys mean no observation was captured. Plugins own any parsing, normalization, and decisions based on this untrusted data. For the captured families, size limits, and rolling-upgrade behavior, see Connect an Agent Harness and Trace an Agent Run.

The custom policy examples use input_trigger() to give tool-result turns a cache-local picker path.

Soft Session Affinity

Set --router-session-affinity-mode soft with a session-affinity TTL to let a custom policy influence an existing session binding. The current binding enters the normal selection pipeline as affinity_target(). The policy still receives the full host-eligible candidate set, subject to its own filters, and may select another worker. Dynamo rebinds the session after dispatch returns a response stream.

Session binding lookup affinity_target() Custom filter, score, and pick Dispatch selected worker Commit selected worker as new binding

Match both fields when a policy wants to recognize the target. A target with dp_rank: None matches every rank on its worker; a populated rank matches only that worker-rank pair. The target can be absent from the candidate table when the worker is unavailable or a custom filter rejects it.

Hard affinity remains the default. A hard binding and every explicit request target take the exact-target path instead of advisory custom selection. A selection, setup, or dispatch failure before a response stream leaves the previous soft binding intact. An error or cancellation after the stream is returned does not roll back a completed rebind.

The custom policy examples include an overload-aware soft pinning policy that retains the advisory target until its active-request count exceeds a configured threshold, then selects the least-loaded alternative. Its two-Mocker walkthrough holds the first request open and verifies an A -> B -> B worker sequence: overload moves the second request to B, and the third request retains B after load drains, proving that the plugin-selected dispatch updated the binding.

Worker Identity and Cost

AccessorMeaning
WorkerCandidate::worker()Candidate worker ID and data-parallel rank
WorkerCandidate::info()Candidate WorkerInfo
ScoredWorkerCandidate::worker()Picker row worker ID and data-parallel rank
ScoredWorkerCandidate::cost()Sum of all scorer contributions for the picker row
WorkerInputView::info(row)Picker row WorkerInfo, or None for an out-of-range row

WorkerInfo holds static facts about a worker rank, so no component declares an input group to read it. worker() returns the worker ID and data-parallel rank. max_num_batched_tokens() and total_kv_blocks() return what the worker’s runtime config advertises, or None when it is unreported or reported as zero (vLLM’s Ray data-parallel backend registers a zero placeholder); total_kv_blocks() is capacity, not free blocks. The values change only when a worker registers again. For filters, scorers, and pickers Dynamo looks them up in its cached worker configs on each info() call, so a component that never calls it pays nothing. Classifier rows outlive that map, so they carry each rank’s capacity (40 bytes per rank) whenever a classifier declares an input group.

Optional Worker Inputs

If a component needs no optional worker data, return WorkerInputs::NONE. Combine exact groups with |, such as WorkerInputs::CACHE | WorkerInputs::LOAD.

GroupAccessorMeaning
CACHEdevice_overlap_blocks()Device-resident prefix overlap in blocks
CACHEhost_overlap_blocks()Host-pinned prefix overlap in blocks
CACHEdisk_overlap_blocks()Disk prefix overlap in blocks
CACHEaccounting_cache_estimate()Accounting estimate as weighted KV blocks and rounded tokens; zero if missing, not clamped to prompt length
CACHEhas_tier_matches()Whether the lookup contains any GPU, CPU, or disk matches before filtering; false means only accounting estimates or no cache data were supplied
CACHEshared_hits()None if no shared result was supplied; otherwise unweighted ranges with total_hits(), hits_beyond(prefix) (every hit at or past prefix), and loadable_beyond(prefix) (the unbroken run starting at prefix, or zero when it is shorter than the engine loads)
LOADis_available()Whether the host supplied a load observation; distinguishes missing data from an observed idle worker
LOADactive_prefill_tokens()Tokens currently active in the worker’s prefill stage
LOADactive_decode_blocks()KV blocks the worker’s active requests hold; excludes this request. Prompt blocks by default, plus the blocks generation adds only with --router-track-output-blocks; zero with --no-router-track-active-blocks
LOADdecode_cost_blocks()Projected active decode footprint, including this request’s additional active blocks
LOADactive_requests()Requests currently active on the worker
PREFERRED_TAINTpreferred_taint_multiplier()Optional cost multiplier from matching preferred routing taints
ACTIVE_REQUESTSWorkerInputView::active_requests(row)Picker only. Requests in flight on the row’s worker; None only when the picker did not declare the group or the row is out of range
KV_COPYkv_copy()The worker’s copy offer. None if the host has no copy data for this request: no worker in the partition advertises router_hint, or the indexer cannot retain the matched block chain
KV_COPYsource_prefix_blocks()Prefix blocks held by the source this worker would copy from, and so held by the worker after the copy; None when no eligible source holds more than the worker’s device-resident plus host-pinned prefix

The GPU, CPU, and disk overlap accessors return raw tier counts. A missing tier or worker entry is zero; Dynamo does not substitute its weighted effective-overlap estimate. Each custom scorer chooses how to combine the raw counts.

A filter or scorer reads groups through WorkerCandidate::cache() or load(). A picker reads index-aligned views through WorkerInputView; its cache view supports get(row) and iter(). Each component must declare every group it reads; another component requesting a group does not grant access.

Declare ACTIVE_REQUESTS instead of LOAD when a request count is all the picker needs. It is cheaper, and LOAD needs the KV scheduler, which tracks each worker’s active tokens and blocks.

A scorer reads KV_COPY through WorkerCandidate::kv_copy(). Filters and pickers do not receive it, and declaring it there has no effect. The host picks each worker’s copy offer with the KV fetch hint rules, including topology islands.

A policy whose scorer reads KV_COPY commits the selected worker to its offer, so the worker’s role must run a hint policy that sends it, such as kv_fetch.

This scorer charges each worker for the prompt blocks it can neither reuse nor copy. A worker without copy data still counts its own cache:

use dynamo_kv_router::plugins::worker_selection::{
WorkerCandidates, WorkerInputs, WorkerScorer, WorkerSelectionPolicyError,
WorkerSelectionRequest,
};
struct UncoveredPromptScorer;
impl WorkerScorer for UncoveredPromptScorer {
fn required_worker_inputs(&self) -> WorkerInputs {
WorkerInputs::CACHE | WorkerInputs::KV_COPY
}
fn score(
&self,
request: &WorkerSelectionRequest<'_>,
candidates: WorkerCandidates<'_>,
costs: &mut [f64],
) -> Result<(), WorkerSelectionPolicyError> {
for (candidate, cost) in candidates.iter().zip(costs) {
let cached = candidate.cache().map_or(0.0, |cache| {
cache.device_overlap_blocks()
+ cache.host_overlap_blocks()
+ cache.disk_overlap_blocks()
});
let copyable = candidate
.kv_copy()
.and_then(|copy| copy.source_prefix_blocks())
.map_or(0.0, f64::from);
*cost = (request.request_blocks() as f64 - cached.max(copyable)).max(0.0);
}
Ok(())
}
}

WorkerCandidate::preferred_taint_multiplier() and ScoredWorkerCandidate::preferred_taint_multiplier() return the optional cost multiplier from preferred routing constraints. A filter, scorer, or picker must request WorkerInputs::PREFERRED_TAINT before reading the multiplier. Without that declaration, the component receives None, even when another component requested the multiplier. Exact hard-pinned requests also do not materialize it. Required routing constraints remain host-enforced eligibility rules.

Both paths use the same policy crate, catalog, and YAML file. Choose the process that owns worker selection.

Add the catalog to the Python binding manifest. Keep the dependency alias dynamo-worker-selection-policy-catalog:

Your catalog is registered alongside the policies Dynamo ships, not instead of them, so both remain selectable. Your catalog cannot reuse a shipped policy’s type name; the registry rejects the duplicate at startup rather than overriding it.

# Link the policy catalog into the Python extension.
cargo add \
--manifest-path "$DYNAMO_DIR/lib/bindings/python/Cargo.toml" \
--optional \
--rename dynamo-worker-selection-policy-catalog \
--path "$POLICY_DIR/catalog" \
acme-routing-catalog

Build the extension with the linked catalog:

# Build the extension with the custom-policy feature.
cd "$DYNAMO_DIR/lib/bindings/python"
CARGO_TARGET_DIR="$DYNAMO_DIR/target" maturin develop --uv --features custom-policy
# Install the Python package from this checkout.
cd "$DYNAMO_DIR"
uv pip install -e .
# Start the frontend with the policy configuration.
python3 -m dynamo.frontend \
--router-mode kv \
--router-policy-config "$POLICY_DIR/worker-selection.yaml" \
--router-prefill-policy prefill-least-busy \
--router-decode-policy least-busy

The role-specific CLI flags override the matching YAML fields for this process. In this command, prefill-least-busy replaces worker_selection.prefill, and least-busy replaces worker_selection.decode.

The linked extension also applies custom policies in python3 -m dynamo.router. That process waits for a worker model card so it can choose built-in or custom policy behavior from the card’s typed role. DYN_ROUTER_MODEL_CARD_WAIT_SECS bounds the startup wait and defaults to 600 seconds.

Request Classifier Sequence Hashes

ClassifyRequest::sequence_hashes() returns a read-only snapshot of the existing ordered active-tracking sequence hashes before admission. Each entry covers a complete tracking block; use the factory context’s block_size() for token units. Partial trailing blocks are excluded. None means tracking data is absent; Some(&[]) means the host supplied an empty sequence. The snapshot lives for the classify call and does not grow with generated output.

Sequence hashes retain the host’s tracking configuration. When KV reuse is disabled, they are randomized identities rather than reusable content hashes. Public and keyed hashes must stay within their respective tracking domains and configurations; matching values do not establish physical KV residency or a safe shared-budget discount. This accessor adds no hashing or scheduling overrides.

Preparing a classifier input copies the supplied sequence on each eligible scheduling attempt, including retries that subsequently reuse cached classification overrides. Each nonempty snapshot allocates and copies 8 * hashes.len() bytes. Missing and empty sequences need no hash-buffer allocation. Requests without a classifier skip this snapshot construction.

For P retained inputs containing H hashes each, the added hash payload is 8 * P * H bytes, plus request layout and allocator overhead. For example, 1,024 inputs of 32,768 tokens with 64-token tracking blocks retain 4 MiB of additional hash payload. The original scheduling hashes remain live separately. Snapshots are created before waiting for the classifier lock and are freed when classify returns. Worker queue limits apply after classification; they do not bound these copies. There is no universal prompt-length limit here, so deployments must bound prompt length before this projection to bound its memory use.

For example, a classifier can inspect the sequence before it queues the request:

use dynamo_kv_router::plugins::request_classifier::{
ClassifierError, ClassifyRequest, RequestClassifier, WorkerCandidates,
};
struct InspectPrefixes;
impl RequestClassifier for InspectPrefixes {
fn classify(
&mut self,
request: ClassifyRequest,
_workers: WorkerCandidates<'_>,
) -> Result<ClassifyRequest, Box<ClassifierError>> {
let _tracked_blocks = request.sequence_hashes().map(|hashes| hashes.len());
Ok(request)
}
}

Experimental Resident Block Counts

A policy can read how many blocks the router’s indexer holds for each worker rank, including cached blocks no running request uses, and charge a placement for the cache it would evict; use LOAD for work in flight. The API lives in plugins::experimental, whose items have no compatibility guarantee and may change or be removed in any release. Declare resident_blocks::RESIDENT_BLOCKS together with WorkerInputs::CACHE, then import the ResidentBlocks trait to read candidate.resident_blocks() in a filter or scorer, or ResidentBlocksByRow to read input.resident_blocks(row) in a picker:

use dynamo_kv_router::plugins::experimental::resident_blocks::{
RESIDENT_BLOCKS, ResidentBlocks,
};
/// Charges one unit per block a placement could evict.
struct EvictionPressure;
impl WorkerScorer for EvictionPressure {
fn required_worker_inputs(&self) -> WorkerInputs {
WorkerInputs::CACHE | RESIDENT_BLOCKS
}
fn score(
&self,
_request: &WorkerSelectionRequest<'_>,
candidates: WorkerCandidates<'_>,
costs: &mut [f64],
) -> Result<(), WorkerSelectionPolicyError> {
for (candidate, cost) in candidates.iter().zip(costs) {
// None means the host has no count for this rank; treat it as neutral.
*cost = candidate.resident_blocks().unwrap_or(0) as f64;
}
Ok(())
}
}

The count is unweighted, not clamped to total_kv_blocks, and measures occupancy rather than reusable cache: blocks that prefix matching can no longer reach, such as descendants of an evicted block, count until their own remove events arrive, and a lost remove event inflates the count until the rank is removed. A count is current as of the last event its indexer thread applied, the same freshness as the CACHE overlap scores, so it can trail queued events and change between two reads in one selection. A rank reads None until its indexer thread has reached the policy’s request and holds a block for it, 0 after a clear, and None again once the rank or its worker is removed. A component also reads None when it did not declare RESIDENT_BLOCKS, with a remote indexer, or after an indexer thread stops, so a worker whose KV events never arrive never looks empty. Only filters, scorers, and pickers receive counts: a request classifier that declares RESIDENT_BLOCKS reads None. A policy that declares RESIDENT_BLOCKS must also declare CACHE, because the counts come from the indexer that CACHE starts. The router checks this for every policy it builds for a routing partition: the frontend fails to start, and the standalone selection service marks the partition’s workers unschedulable with the reason.

What the count contains, and whether router replicas agree on it, depends on the routing mode:

  • KV events: the device-tier blocks the indexer currently tracks from engine events. Every router replica sees the same counts.
  • Approximate routing: the blocks routed to the rank within the TTL, or the distinct full blocks the LRU cache policy retains, which leaves out its partial tail blocks and duplicate copies. Each replica counts only the requests it routed, except a replica that serves its indexer (serve_indexer), whose counts also include the routing decisions other replicas send it.

KVCR Occupancy

A KVCR instance is the host-memory KV cache attached to one worker rank. A policy that declares RESIDENT_BLOCKS can also read how many blocks the router has indexed for a worker’s instance, and any policy can read the capacity the worker advertises for it; occupancy is the first divided by the second. The same traits carry the count: candidate.cache_owner_blocks() in a filter or scorer, and input.cache_owner_blocks(row) in a picker. CacheOwnerCapacity adds cache_owner_capacity_blocks() to WorkerInfo:

use dynamo_kv_router::plugins::experimental::resident_blocks::{
CacheOwnerCapacity, ResidentBlocks,
};
let capacity = candidate.info().cache_owner_capacity_blocks();
let occupancy = candidate.cache_owner_blocks().zip(capacity)
.map(|(blocks, capacity)| (blocks as f64 / capacity as f64).min(1.0));
  • cache_owner_blocks() needs RESIDENT_BLOCKS and CACHE. It is the number of host-pinned blocks Dynamo’s lower-tier index holds for the instance, built from KVCR’s KV events and read live, so two reads in one selection can differ. Events are best effort: blocks KVCR is still filling and non-main KV groups are not counted, and a lost Removed event counts until the instance’s next recovery. It is None when no instance is attached to the worker, before the router has received a host-pinned KV event, when the router uses a remote indexer, and in a request classifier.
  • cache_owner_capacity_blocks() needs no input group. A vLLM worker advertises its KVCR tier’s secondary_g2_slots times the offload chunk size (the connector’s blocks_per_chunk or block_size), in router blocks; a pool served by kvcr-service advertises none.

Dynamo looks a count up only when a component calls the accessor, so a policy that reads only resident block counts pays nothing for it. KVCR evicts least-recently-used blocks, so a warm instance usually reads close to full.

Experimental Decode Progress

A picker declares DECODE_PROGRESS in required_worker_inputs() and imports DecodeProgressByRow to read input.decode_progress(row):

use dynamo_kv_router::plugins::experimental::decode_progress::{
DECODE_PROGRESS, DecodeProgressByRow,
};
MethodValue
observed_requests()Number of active requests covered by the summary
remaining_token_budget()Sum of effective output limits minus observed output, in raw tokens. This is an upper bound.
observed_age()Duration since the oldest nonempty token observation. Apply your policy’s freshness limit.

Collection supports single-choice aggregated requests with a positive effective output limit, including requests that can finish at EOS or a stop condition. If the frontend derives a limit from the remaining context, that limit counts too.

A rank returns None if it is idle or any active request is prefilling, has no effective limit, or lacks a valid observation. An undeclared input or unsupported host, including the standalone EPP, also returns None. Choose a fallback for those cases.

Observations are local to one frontend. LOAD and progress are advisory reads and can differ during concurrent updates.

Policy Contract

  • Return true from a filter to keep a worker and false to reject it.
  • Expect filters to run in declaration order before scoring. Rejecting every worker returns an error.
  • Return finite scorer costs.
  • Return a valid picker row.
  • Treat candidate order as unspecified.
  • Request only the signal groups that the component reads.
  • Keep blocking I/O and panics out of keep, score, and pick.
  • Keep any state your policy shares across requests correct under concurrent updates. Dynamo reuses one policy for every request to a model and worker role and handles many requests at once, so two selections can read and change that state at the same time. Policies without such state need nothing extra.
  • Keep policy state local to the factory-created policy unless cross-partition sharing is a deliberate requirement.
  • Build the policy against the same Dynamo revision as the frontend or EPP.
  • If a signal adds work, storage, allocation, or another scan, run the worker-selection benchmark.

The example README contains the in-tree package names and build-check commands. For the built-in cost model, see Routing Concepts. For the standalone selection lifecycle, see Standalone Selection Service.

Default Policy Plugin

To give a worker role its own default-policy settings, select dynamo-default-cost-fn:

worker_selection:
aggregated:
type: dynamo-default-cost-fn
parameters:
overlap_score_credit: 1.0
prefill_load_scale: 1.0
router_temperature: 0.0

The provider also accepts overlap_score_credit_decay, decode_active_request_weight, host_cache_hit_weight, disk_cache_hit_weight, and shared_cache_multiplier. The kvcr policy takes the same parameters and also credits blocks a worker can copy from a peer at that multiplier. Values must be finite and non-negative. Per-request score and temperature overrides do not apply to this policy.

Omitted parameters normally inherit router configuration. When the resolved overlap_score_credit is nonzero, an omitted shared-cache multiplier uses the router’s value, or 0.5 if shared cache is enabled and no value is configured. When device credit is zero, omitted host, disk, and shared-cache weights instead resolve to zero.

For cache-capable roles, any nonzero cache-scoring weight requires cache inputs. An explicit nonzero host, disk, or shared-cache weight therefore enables cache inputs even when overlap_score_credit: 0. This changes startup behavior for existing policy YAML that previously used zero device credit to suppress all cache inputs despite explicit nonzero tier weights. Set all four cache-scoring weights to zero to keep such a policy load-only. Plain disaggregated decode always resolves all four weights to zero and skips cache inputs.

Runtime Configuration

Policies can opt in to process-local configuration updates with WorkerSelectionPolicy::with_runtime_config(initial_parameters, builder). The initial JSON object defines the patchable parameter names and their resolved reset values. The builder receives a complete parameter object and must validate it before returning a replacement policy. It runs synchronously on the scheduler actor: do not perform I/O or mutate shared policy state while constructing a replacement. Return RuntimePolicyError::InvalidParameters for invalid values. Policies that do not opt in remain startup-only.

Use the scheduler’s policy_control() handle to read or update an opted-in policy. The runtime policy API defines revision, patch, and reset semantics.

Updates run between selection calls. A replacement cannot add worker-input groups beyond those declared at startup, change the worker label, or change exclusive-affinity behavior. Queues, worker discovery, cache indexes, and host accounting are retained. The replacement’s filters, scorers, and picker are new instances, so state the previous instances held, such as a cursor, does not carry over. A cancelled control request still waiting in the actor queue is skipped.

The simple-filter-score-pick example opts in for its min_device_overlap_blocks parameter. The built-in default policy opts in for its scoring weights and temperature. See Runtime Policy Updates for the frontend HTTP contract, scope, and persistence limits.