Llm Router Design

Comprehensive guide to llm router design covering architecture, implementation, testing, and operational patterns for production engineering teams.

An LLM router dynamically selects and dispatches natural language queries to the most appropriate large language models based on input characteristics, service requirements, and model capabilities. It is essential when operating multiple LLMs with distinct strengths—such as a dense retrieval model, a specialized code generator, a high-accuracy reasoning engine, and a low-latency summarizer—each with different costs, latency profiles, and input formats. Use an LLM router when you need to combine models into a unified, adaptive inference layer that avoids over- or under-modeling, reduces latency and cost, and enables seamless model upgrades without breaking client APIs.

Dispatching Queries Based on Input Content

To route a query to the correct LLM, the router inspects the input text and applies rules or heuristics derived from content features. The decision is made before forwarding the payload to the selected model.

The router typically receives a JSON request over HTTP:

{
  "query": "Explain the difference between attention and self-attention in transformers.",
  "context": [
    "In neural networks, attention mechanisms allow models to focus on relevant parts of input.",
    "Self-attention computes relationships between all positions in a sequence."
  ],
  "metadata": {
    "user_id": "u123",
    "source": "web",
    "session_id": "s456"
  }
}

A router computes one or more features from the input and uses them to select a model. The most common feature is query length:

A simple router configuration might look like:

routers:
  - name: "content-based-router"
    rules:
      - condition: "length(query) < 100"
        model: "llm-quick"
      - condition: "length(query) >= 100 and length(query) < 500"
        model: "llm-balanced"
      - condition: "length(query) >= 500"
        model: "llm-reasoning"
    fallback: "llm-default"

The router evaluates length(query) using a tokenizer-aware token count. The function length(str) counts tokens using a BPE model with the standard tiktoken encoding, and a query of 372 tokens triggers the llm-balanced route.

The router can also use semantic similarity to match input against a predefined set of query types. For example, a vector representation of the input query is computed using a pre-trained embedding model (e.g., text-embedding-ada-002), and the router computes cosine similarity to prototype queries.

def route_by_semantic_similarity(query, prototypes):
    embedding = embed(query)
    best_match = None
    best_score = -1.0
    for name, prototype_embedding in prototypes.items():
        score = cosine_similarity(embedding, prototype_embedding)
        if score > best_score:
            best_score = score
            best_match = name
    return best_match

The router then maps the best match to a model. This method is especially useful when inputs vary widely in domain and intent, such as support tickets, code reviews, and research summaries.

Routing Based on Metadata and Request Context

Beyond the raw input, the router uses metadata to make routing decisions. Metadata may include client information, user preferences, session state, or prior service behavior.

The router can evaluate conditions on metadata fields using a declarative syntax. For example:

rules:
  - condition: "metadata.user_id in ['u100', 'u200']"
    model: "llm-priority"
  - condition: "metadata.source == 'mobile'"
    model: "llm-mobile"
  - condition: "metadata.session_id starts_with 's'"
    model: "llm-conversational"

The router evaluates each condition in order, and the first matching rule determines the model. If no rule matches, it falls back to a default model.

A common failure mode arises when metadata fields are structured inconsistently. A field metadata.user_type might contain "premium", "pro", or "enterprise" in different formats. The router must normalize values, such as:

condition: "lower(metadata.user_type) in ['premium', 'pro']"

This normalization is often applied across the entire routing pipeline, and failures go unnoticed when user_type is misspelled or in a different case.

Metadata can also carry execution hints from upstream services. For example, a document parser might tag a query with metadata.processing_hint = "high-accuracy" and set metadata.priority = "urgent". The router uses these to route to high-performance models with warm caches.

Combining Multiple Criteria with Weighted Scoring

When a single rule is insufficient, the router computes a composite score from multiple features. Each feature contributes a weighted score, and the model with the highest total score is selected.

Features include:

The router computes a score vector for each model, then applies a weighted sum:

def compute_model_score(input, model_features, weights):
    score = 0.0
    for feature_name, weight in weights.items():
        value = model_features[feature_name](input)
        score += weight * value
    return score

For instance, a router might define:

weights:
  query_length: 0.4
  context_count: 0.3
  has_code_block: 0.2
  is_urgent: 0.1

A query with 450 tokens, 3 context items, a code block, and urgent flag yields:

The router compares this score across all available models and selects the one with the highest value.

A silent failure occurs when feature functions return inconsistent normalization. For example, a query_length function returns raw token counts, while context_count returns a normalized score from 0 to 1, but the router assumes all features are in the same range. The router must normalize all features to a common scale, typically 0 to 1, before summing.

Model Selection and Deployment Integration

Each routed query is dispatched to a model via a network call. The router uses a registry of available models, each with a URI and optional configuration.

models:
  - name: "llm-quick"
    endpoint: "https://models.example.com/quick"
    timeout: 1000
    max_retries: 3
    config:
      temperature: 0.8
      max_tokens: 128
      top_p: 0.9
  - name: "llm-balanced"
    endpoint: "https://models.example.com/balanced"
    timeout: 2000
    config:
      temperature: 0.7
      max_tokens: 256
      top_p: 0.85

The router constructs the request body for the target model, transforming the input to match the target’s expected schema. If the query uses query and context, but the model expects input_text and context_documents, the router performs a mapping:

{
  "input_text": "Explain the difference between attention and self-attention in transformers.",
  "context_documents": [
    "In neural networks, attention mechanisms allow models to focus on relevant parts of input.",
    "Self-attention computes relationships between all positions in a sequence."
  ],
  "temperature": 0.8,
  "max_tokens": 128,
  "top_p": 0.9
}

The transformation is defined in the router configuration:

transformations:
  "llm-quick":
    mapping:
      query: "input_text"
      context: "context_documents"
      metadata.priority: "priority_level"
    overrides:
      temperature: 0.8
      max_tokens: 128

When a model endpoint is unreachable, the router retries up to three times with exponential backoff. The default retry strategy is:

If all retries fail, the router returns a 503 Service Unavailable with a detailed error:

{
  "error": "LLMRouterError",
  "message": "Failed to route query to llm-quick after 3 retries",
  "details": {
    "model": "llm-quick",
    "endpoint": "https://models.example.com/quick",
    "retries": 3,
    "last_error": {
      "code": "504",
      "message": "Gateway Timeout",
      "timestamp": "2024-07-15T08:32:14Z"
    }
  }
}

Handling Model Failures and Graceful Degradation

When a model fails during dispatch, the router applies fallback strategies. The most common is model fallback, where the router tries a secondary model if the primary fails.

routers:
  - name: "content-based-router"
    rules:
      - condition: "length(query) < 100"
        model: "llm-quick"
        fallback: "llm-default"
      - condition: "length(query) >= 100"
        model: "llm-balanced"
        fallback: "llm-quick"

If llm-quick fails, the router attempts llm-default and returns its result. The fallback model receives the same input, but may be configured with different defaults.

A subtle failure mode occurs when the fallback model expects a different input schema. The router must transform the input before dispatching to the fallback, but this transformation is often forgotten. For example, llm-quick expects context as a list of strings, but llm-default expects context as a single string with newline separation. Without explicit transformation, the fallback model receives a malformed input.

The router can also use model chaining: a primary model generates a response, and the router uses that response to trigger a second model. For example, the router sends a query to llm-balanced, receives the answer, and then routes the answer to llm-summarizer if the response exceeds 500 tokens.

This chaining is implemented via a chain configuration:

chains:
  - name: "summarize-large-response"
    condition: "length(response) > 500"
    model: "llm-summarizer"
    input_mapping:
      original_query: "query"
      summary: "response"

When chaining, the router buffers the response and dispatches the new request only after receiving the first model’s result.

Dynamic Model Selection and A/B Testing

The router supports dynamic routing policies, where the routing logic changes over time. A common pattern is A/B testing, where two routing strategies are active simultaneously, and the router splits incoming requests between them.

The router maintains a routing policy with an active strategy and a target distribution:

policies:
  - name: "ab-test-routing"
    strategy: "content-based-router"
    alternate_strategy: "semantic-first-router"
    distribution:
      "content-based-router": 0.7
      "semantic-first-router": 0.3

The router picks a strategy at random based on the distribution. It logs each decision with metadata:

{
  "routing_decision": {
    "strategy_used": "content-based-router",
    "selected_model": "llm-balanced",
    "metadata": {
      "ab_test_id": "routing-v2",
      "experiment_group": "A",
      "timestamp": "2024-07-15T08:32:14Z"
    }
  }
}

The router can also switch strategies based on performance metrics. For example, if llm-reasoning has a latency above 2s for 5 consecutive minutes, the router promotes it to primary use, and demotes llm-balanced.

A common mistake is failing to instrument the router with routing telemetry. Without logs of which rules fired, which models were selected, and how long each dispatch took, the router becomes a black box. The router must emit structured logs for each request, including:

Failure modes include missing logs, incomplete metadata, and mismatched timestamps across services.

Common Pitfalls and Configuration Gotchas

The router is not a one-size-fits-all component. It is a decision engine at the heart of a multi-model inference system, and its success depends on consistent, observable, and maintainable routing logic.

This page was rewritten on 12 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.