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:
- 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.
- If the knowledge base is large and frequently updated, and answers need to cite sources, choose RAG.
- If strict permission isolation is required, choose RAG and enforce access control filtering at the retrieval layer.
- 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.
- 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:
import loggingimport osimport timeimport uuidimport requests # Requires: requests>=2.31, Python 3.9+logger = logging.getLogger("model_router")RETRYABLE_STATUS = {429, 500, 502, 503, 504}MAX_RETRY_AFTER = 10 # seconds. Caps the wait time returned by upstream, avoiding long blockingclass TransientError(Exception):"""Retryable transient errors: network timeout, connection failure, 429, 5xx, invalid JSON response."""def __init__(self, message, retry_after=None):super().__init__(message)self.retry_after = retry_afterclass PermanentError(Exception):"""Non-retryable errors: 400, 401, 403, misconfigured endpoint URL. Retry and fallback will not change the outcome."""class AllModelsFailed(Exception):"""Primary and all fallback models have failed."""def _parse_retry_after(value):"""Parse Retry-After into seconds. HTTP date format is not parsed; returns None and backoff strategy takes over."""if value and value.strip().isdigit():return min(float(value), MAX_RETRY_AFTER)return Noneclass ModelRouter:def __init__(self, endpoints, routing, fallback_order,max_retries=2, timeout=30, backoff=0.5):api_key = os.environ.get("MODEL_API_KEY")if not api_key:raise RuntimeError("Missing environment variable MODEL_API_KEY; set it before starting the service.")if "standard_model" not in endpoints:raise ValueError("endpoints must contain standard_model")referenced = set(routing.values()) | set(fallback_order)missing = referenced - set(endpoints)if missing:raise ValueError(f"Models not defined in endpoints: {sorted(missing)}")self._api_key = api_key # kept in memory only; never printed, never loggedself.endpoints = endpoints # model name -> endpoint URLself.routing = routing # request type -> primary model nameself.fallback_order = fallback_order # fallback sequence after primary failsself.max_retries = max_retriesself.timeout = timeoutself.backoff = backoffdef pick_model(self, query_type):return self.routing.get(query_type, "standard_model")def _post_once(self, url, payload, request_id):headers = {"Content-Type": "application/json","Authorization": f"Bearer {self._api_key}","X-Request-Id": request_id,}try:resp = requests.post(url, json=payload, headers=headers, timeout=self.timeout)except (requests.Timeout, requests.ConnectionError) as exc:raise TransientError(f"Network timeout or connection failure: {type(exc).__name__}") from excexcept requests.RequestException as exc:# e.g., InvalidURL, MissingSchema, TooManyRedirects—mostly configuration issues; retrying is pointlessraise PermanentError(f"Request error; check endpoint URL configuration: {type(exc).__name__}") from excif resp.status_code == 429:retry_after = _parse_retry_after(resp.headers.get("Retry-After"))raise TransientError("HTTP 429", retry_after=retry_after)if resp.status_code in RETRYABLE_STATUS:raise TransientError(f"HTTP {resp.status_code}")if resp.status_code in (401, 403):raise PermanentError("Authentication failed; check MODEL_API_KEY and its permissions")if resp.status_code >= 400:raise PermanentError(f"HTTP {resp.status_code}; check request parameters")try:return resp.json()except ValueError as exc:raise TransientError("Response body is not valid JSON") from excdef _call_with_retry(self, model_name, payload, request_id):url = self.endpoints[model_name]for attempt in range(self.max_retries + 1):try:return self._post_once(url, payload, request_id)except TransientError as exc:if attempt == self.max_retries:raiseif exc.retry_after is not None:wait = exc.retry_afterelse:wait = self.backoff * (2 ** attempt)logger.warning("request_id=%s model=%s attempt %d failed: %s; retrying in %.1f seconds",request_id, model_name, attempt + 1, exc, wait)time.sleep(wait)def route(self, query_type, payload):request_id = str(uuid.uuid4())primary = self.pick_model(query_type)candidates = [primary] + [m for m in self.fallback_order if m != primary]for model_name in candidates:try:data = self._call_with_retry(model_name, payload, request_id)except TransientError as exc:logger.error("request_id=%s model=%s retries exhausted; falling back: %s",request_id, model_name, exc)continueif model_name != primary:logger.warning("request_id=%s failed over to %s", request_id, model_name)return {"model": model_name, "request_id": request_id, "data": data}raise AllModelsFailed(f"request_id={request_id} all models unavailable")if __name__ == "__main__":logging.basicConfig(level=logging.INFO)router = ModelRouter(endpoints={"light_model": "https://models.example.internal/v1/light","standard_model": "https://models.example.internal/v1/standard","flagship_model": "https://models.example.internal/v1/flagship",},routing={"simple_qa": "light_model", "complex_reasoning": "flagship_model"},fallback_order=["standard_model", "light_model"],)result = router.route("simple_qa", {"prompt": "How can I check my order status?", "max_tokens": 256})print(result)
