Choosing an LLM for Production: Start with Tiering, Then Test on Your Own Data

    Selecting the right large language model (LLM) for production involves more than comparing benchmark scores. This article provides a technical framework for evaluating models by tier—lightweight, standard, and flagship—based on latency, cost, and quality requirements for specific task types. It covers practical methods for estimating KV cache memory usage, running need-in-a-haystack tests for long-context reliability, and deciding between RAG and long-context input. It also includes a minimal Python implementation of a multi-model router with fallback logic to manage reliability in production environments.

    Tiering Models by Task Type

    With the release of new model versions, the number of options increases, and so does the cost of comparing them. The key differences between models typically lie in time-to-first-token, unit cost, long-text stability, and tool-calling accuracy. The goal of model selection is clear: find a model that meets quality requirements at a controlled cost for each type of request.

    Most vendors offer lightweight, standard, and flagship tiers. Lightweight versions are usually quantized using INT8 or INT4 and combine knowledge distillation, resulting in lower memory usage and lower time-to-first-token. They are well-suited for high-concurrency, short-output scenarios such as intent recognition, classification, and simple Q&A. Flagship models retain higher-precision weights and are more stable on complex reasoning and long code generation tasks, but individual calls are more expensive and slower.

    Before starting the selection process, list the request types in your business. For each type, define three metrics:

    • Acceptable time-to-first-token
    • Cost cap per request
    • Quality baseline

    The quality baseline must be evaluated with your own business data. Vendor-published benchmark scores should be treated as reference only, because the distribution of benchmark questions often differs from real-world requests like contract review, ticket processing, or codebase Q&A.

    The table below is a template you can fill in. The tiers and values need to be determined based on load testing and trial evaluations; fields marked “TBD” should not be filled in based purely on experience.

    Request Type Recommended Starting Tier Time-to-First-Token Cap (ms) Cost Cap per Request (USD) Quality Baseline
    Intent recognition, classification Lightweight TBD TBD Determine via evaluation on business samples
    Ticket summarization Standard TBD TBD Determine via evaluation on business samples
    Contract clause comparison, codebase Q&A Flagship TBD TBD Determine via evaluation on business samples

    Long Context and KV Cache: When You Need to Measure

    When flagship models handle long contexts, KV cache memory usage grows quickly. The following formula provides a rough estimate:

    KV Cache Bytes ≈ 2 × Layers × Sequence Length × Batch Size × KV Heads × Head Dimension × Bytes per Element

    • The factor of 2 accounts for both Key and Value caches.
    • Sequence Length is the context length of a single request, including input and generated output.
    • Batch Size is the number of requests processed in parallel in a batch.
    • Bytes per Element depends on precision: 2 bytes for FP16 or BF16, 1 byte for INT8, and approximately 0.5 bytes for INT4.
    • KV Heads is the number of key-value heads actually stored in the cache.

    This formula applies to standard multi-head attention architectures. Models using Grouped Query Attention (GQA) have fewer KV heads than query heads, so the cache is correspondingly smaller. For example, consider a model with 32 layers, 8 KV heads, head dimension 128, sequence length 8192, batch size 1, and FP16 precision. The cache is approximately 2 × 32 × 8192 × 1 × 8 × 128 × 2 = 1,073,741,824 bytes, or 1 GiB. If the same model has 32 KV heads, the cache grows to 4 GiB.

    This estimate covers only the cache itself. It does not account for beam search, parallel sampling, model weights, activation values, or inference framework overhead. The actual GPU memory required includes these additional components. Therefore, high-concurrency services should cap the maximum context length per request and run load tests with traffic close to real conditions on the target hardware, recording peak memory usage to determine the concurrency limit.

    Validating Long-Context Capabilities

    The “lost in the middle” problem can be tested using the need-in-a-haystack test. The approach: embed a fact at different positions within a long text, ask the model a question about that fact, and measure accuracy across different text lengths and insertion positions. The test material should be replaced with real business content—for example, contract clauses or function definitions from a codebase—rather than generic articles.

    Record the test results in a table like the one below. Each row represents a combination of conditions.

    Text Length (Tokens) Insertion Depth (%) Samples per Cell Accuracy Time-to-First-Token (ms) Cost per 1K Tokens (USD)
    8k 0, 25, 50, 75, 100 20 TBD TBD TBD
    32k 0, 25, 50, 75, 100 20 TBD TBD TBD
    128k 0, 25, 50, 75, 100 20 TBD TBD TBD

    In the table, 0% and 100% represent boundary positions at the beginning and end of the text. Models tend to perform better at the boundaries, so including these samples in the overall statistics can inflate the results. It is recommended to list boundary samples separately or note them in the report.

    20 samples per cell is only suitable for a pilot run—enough to screen out clearly subpar combinations, but insufficient for a final decision. To keep the accuracy error within ±10% (at a 95% confidence level), you need approximately 60–100 samples per cell, with the largest sample size required when accuracy is near 50%.

    Evaluate all three metrics together. Looking at accuracy alone might lead you to select a model that is slow and expensive. Looking only at latency and cost might cause you to overlook the problem of forgetting mid-context. The decision criteria should follow the quality baseline and cost caps defined in the first section.

    RAG or Long Context: A Decision Guide

    Both approaches have their place. The table below compares the key dimensions.

    Dimension Long Context - Direct Input RAG - Retrieve Then Input
    Applicable tasks Single or few documents needing full analysis Answering specific questions from a large knowledge base
    Text scale Limited by the model’s reliable working window Can cover millions of documents
    Update frequency Re-sent per request; updates take effect immediately Requires chunking, vectorization, and indexing—sync delay
    Latency Longer input leads to higher time-to-first-token Adds a retrieval step, but input is shorter—usually faster
    Cost per request Billed on full text each time Retrieval plus small excerpts—usually lower
    Data security Full text sent to model service—larger exposure Can filter by user permissions at retrieval layer; only sends necessary excerpts
    Main risks Mid-context forgetting; cost grows linearly with text length Missed recall; poor chunking leads to incomplete answers

    Decision rules:

    1. If the total document volume fits within the model’s reliable working window, and the task requires full-text understanding—for example, comparing clauses for consistency—prefer long context.
    2. If the knowledge base is large and frequently updated, and answers need to cite sources, choose RAG.
    3. If strict permission isolation is required, choose RAG and enforce access control filtering at the retrieval layer.
    4. If both are needed, use a hybrid approach: first retrieve candidate documents, then pass the full text of those candidates to a long-context model.
    5. No matter which approach you take, you must handle the case where retrieval returns no results.

    Hybrid approaches can also fail. When retrieval returns nothing, or when the highest relevance score falls below a threshold, do not let the model fabricate an answer. Fall back to long context (when document volume allows), or ask the user to provide more specific keywords, and explicitly state that the evidence is insufficient.

    A counterexample: A company used RAG to answer “Are there any clauses in all procurement contracts where liquidated damages exceed 20% of the contract amount?” The retrieval only returned the top fragments most semantically similar to the query, missing most of the contracts. The conclusion was unreliable. For this type of full-coverage statistical question, you should use structured extraction or batch processing first, rather than relying solely on Top-K retrieval.

    Multi-Model Routing: Minimal Implementation and Failure Scenarios

    The following code implements routing, authentication, timeouts, limited retries, and fallback. Requirements: Python 3.9+, requests 2.31+. The code does not include a circuit breaker or rate limiting—those need to be implemented at the gateway or service layer.

    Save the code as model_router.py:

    1. import logging
    2. import os
    3. import time
    4. import uuid
    5. import requests # Requires: requests>=2.31, Python 3.9+
    6. logger = logging.getLogger("model_router")
    7. RETRYABLE_STATUS = {429, 500, 502, 503, 504}
    8. MAX_RETRY_AFTER = 10 # seconds. Caps the wait time returned by upstream, avoiding long blocking
    9. class TransientError(Exception):
    10. """Retryable transient errors: network timeout, connection failure, 429, 5xx, invalid JSON response."""
    11. def __init__(self, message, retry_after=None):
    12. super().__init__(message)
    13. self.retry_after = retry_after
    14. class PermanentError(Exception):
    15. """Non-retryable errors: 400, 401, 403, misconfigured endpoint URL. Retry and fallback will not change the outcome."""
    16. class AllModelsFailed(Exception):
    17. """Primary and all fallback models have failed."""
    18. def _parse_retry_after(value):
    19. """Parse Retry-After into seconds. HTTP date format is not parsed; returns None and backoff strategy takes over."""
    20. if value and value.strip().isdigit():
    21. return min(float(value), MAX_RETRY_AFTER)
    22. return None
    23. class ModelRouter:
    24. def __init__(self, endpoints, routing, fallback_order,
    25. max_retries=2, timeout=30, backoff=0.5):
    26. api_key = os.environ.get("MODEL_API_KEY")
    27. if not api_key:
    28. raise RuntimeError("Missing environment variable MODEL_API_KEY; set it before starting the service.")
    29. if "standard_model" not in endpoints:
    30. raise ValueError("endpoints must contain standard_model")
    31. referenced = set(routing.values()) | set(fallback_order)
    32. missing = referenced - set(endpoints)
    33. if missing:
    34. raise ValueError(f"Models not defined in endpoints: {sorted(missing)}")
    35. self._api_key = api_key # kept in memory only; never printed, never logged
    36. self.endpoints = endpoints # model name -> endpoint URL
    37. self.routing = routing # request type -> primary model name
    38. self.fallback_order = fallback_order # fallback sequence after primary fails
    39. self.max_retries = max_retries
    40. self.timeout = timeout
    41. self.backoff = backoff
    42. def pick_model(self, query_type):
    43. return self.routing.get(query_type, "standard_model")
    44. def _post_once(self, url, payload, request_id):
    45. headers = {
    46. "Content-Type": "application/json",
    47. "Authorization": f"Bearer {self._api_key}",
    48. "X-Request-Id": request_id,
    49. }
    50. try:
    51. resp = requests.post(url, json=payload, headers=headers, timeout=self.timeout)
    52. except (requests.Timeout, requests.ConnectionError) as exc:
    53. raise TransientError(f"Network timeout or connection failure: {type(exc).__name__}") from exc
    54. except requests.RequestException as exc:
    55. # e.g., InvalidURL, MissingSchema, TooManyRedirects—mostly configuration issues; retrying is pointless
    56. raise PermanentError(f"Request error; check endpoint URL configuration: {type(exc).__name__}") from exc
    57. if resp.status_code == 429:
    58. retry_after = _parse_retry_after(resp.headers.get("Retry-After"))
    59. raise TransientError("HTTP 429", retry_after=retry_after)
    60. if resp.status_code in RETRYABLE_STATUS:
    61. raise TransientError(f"HTTP {resp.status_code}")
    62. if resp.status_code in (401, 403):
    63. raise PermanentError("Authentication failed; check MODEL_API_KEY and its permissions")
    64. if resp.status_code >= 400:
    65. raise PermanentError(f"HTTP {resp.status_code}; check request parameters")
    66. try:
    67. return resp.json()
    68. except ValueError as exc:
    69. raise TransientError("Response body is not valid JSON") from exc
    70. def _call_with_retry(self, model_name, payload, request_id):
    71. url = self.endpoints[model_name]
    72. for attempt in range(self.max_retries + 1):
    73. try:
    74. return self._post_once(url, payload, request_id)
    75. except TransientError as exc:
    76. if attempt == self.max_retries:
    77. raise
    78. if exc.retry_after is not None:
    79. wait = exc.retry_after
    80. else:
    81. wait = self.backoff * (2 ** attempt)
    82. logger.warning("request_id=%s model=%s attempt %d failed: %s; retrying in %.1f seconds",
    83. request_id, model_name, attempt + 1, exc, wait)
    84. time.sleep(wait)
    85. def route(self, query_type, payload):
    86. request_id = str(uuid.uuid4())
    87. primary = self.pick_model(query_type)
    88. candidates = [primary] + [m for m in self.fallback_order if m != primary]
    89. for model_name in candidates:
    90. try:
    91. data = self._call_with_retry(model_name, payload, request_id)
    92. except TransientError as exc:
    93. logger.error("request_id=%s model=%s retries exhausted; falling back: %s",
    94. request_id, model_name, exc)
    95. continue
    96. if model_name != primary:
    97. logger.warning("request_id=%s failed over to %s", request_id, model_name)
    98. return {"model": model_name, "request_id": request_id, "data": data}
    99. raise AllModelsFailed(f"request_id={request_id} all models unavailable")
    100. if __name__ == "__main__":
    101. logging.basicConfig(level=logging.INFO)
    102. router = ModelRouter(
    103. endpoints={
    104. "light_model": "https://models.example.internal/v1/light",
    105. "standard_model": "https://models.example.internal/v1/standard",
    106. "flagship_model": "https://models.example.internal/v1/flagship",
    107. },
    108. routing={"simple_qa": "light_model", "complex_reasoning": "flagship_model"},
    109. fallback_order=["standard_model", "light_model"],
    110. )
    111. result = router.route("simple_qa", {"prompt": "How can I check my order status?", "max_tokens": 256})
    112. print(result)