Practical LLM Selection: A Quantitative Guide to Latency and Token Costs
Selecting a large language model (LLM) for production requires looking beyond public leaderboards to evaluate practical engineering constraints. This article provides a quantitative framework for LLM selection based on latency, throughput, and token costs. It covers how to dissect billing models, build reproducible benchmarking scripts, implement tiered routing, handle rate limits, and optimize prompt design for caching. By following this structured evaluation process, engineering teams can make data-driven decisions that balance performance, quality, and cost.
1. Why Leaderboards Aren’t Enough
Public LLM leaderboards primarily reflect a model’s capabilities on standard datasets. However, engineering teams care about more specific questions: How long does a single request take? How many tasks can be processed daily? What is the cost per task? Will the service be rate-limited during peak hours? The answers to these questions often diverge from leaderboard rankings. A top-ranking model might have high Time To First Token (TTFT) or cost several times more than similar models.
Therefore, model selection should start with business constraints. You need to define three things clearly: the task’s tolerance for latency, the minimum acceptable output quality, and the maximum acceptable unit cost. Only by comparing candidate models within these constraints can you draw meaningful conclusions.
2. Core Metrics Breakdown
Model evaluation typically involves the following types of metrics.
2.1 Latency
Latency refers to the time elapsed from sending a request to receiving the complete response, usually measured in milliseconds. In interactive scenarios, Time To First Token (TTFT) affects user experience more than total latency. In batch processing scenarios, total latency and throughput matter more.
When benchmarking, it is recommended to record percentiles rather than averages. Averages are easily skewed by extreme outliers, whereas P50 and P95 better reflect typical and tail-end user experiences.
2.2 Throughput
Throughput is generally measured in output tokens per second (tokens/s), which determines the completion speed of long-form text generation. The formula is:
Throughput = Output Tokens / Generation Time (seconds)
Note that throughput is affected by server load, network links, and request concurrency. A single measurement has no reference value; you must sample multiple times and take the average.
2.3 Input and Output Tokens
Tokens are the basic unit of text processing for models. The tokenization methods differ between languages, meaning the same text can yield significantly different token counts across models. Therefore, when comparing costs, you should directly use the actual billed token count from the same model rather than estimating based on character count.
2.4 Cost
Cost is the metric most teams care about, but its calculation is more complex than a simple price list. The next section explores this in detail.
3. Understanding Billing Models
Many token-based billing services use a tiered, weighted calculation method. Here is a general formula for calculating credits or fees:
Cost = Input Tokens × Input Rate + Cache Write Tokens × Cache Write Rate + Cache Hit Tokens × Cache Hit Rate + Output Tokens × Output Rate
This formula involves four key points:
First, input and output usually have different rates. Generating output tokens requires more computation, so the output rate is generally higher than the input rate.
Second, cache write refers to storing a prefix content into the cache for subsequent requests to reuse. Writing to the cache may incur additional costs.
Third, cache hit refers to subsequent requests reusing a cached prefix. The unit price for the hit portion is usually much lower than standard input. Thus, in scenarios like multi-turn conversations, long system prompts, and fixed knowledge base Q&A, cache design significantly impacts cost.
Fourth, specific rate values vary by provider and model. You must refer to the official billing documentation of your chosen platform and cannot directly apply data from others.
The following code snippet breaks down a bill into comparable per-request costs:
def estimate_cost(input_tokens: int,output_tokens: int,cache_write_tokens: int,cache_hit_tokens: int,rate_in: float,rate_out: float,rate_cache_write: float,rate_cache_hit: float,) -> float:"""Estimate the billing value for a single request based on tiered rates."""return (input_tokens * rate_in+ cache_write_tokens * rate_cache_write+ cache_hit_tokens * rate_cache_hit+ output_tokens * rate_out)# Example: input rate=1, output rate=4, cache hit rate=0.1.# These values are for demonstration only and do not represent any real service's pricing.cost = estimate_cost(input_tokens=1200,output_tokens=400,cache_write_tokens=0,cache_hit_tokens=3000,rate_in=1.0,rate_out=4.0,rate_cache_write=1.25,rate_cache_hit=0.1,)print(f"Billing value per request: {cost:.1f}")
As shown in the example, output tokens carry the highest weight, while cache hit portions carry the lowest. If your business generates long outputs, the optimization focus should be on controlling output length. If your business involves long, highly repetitive contexts, the focus should be on maximizing the cache hit rate.
4. Building Reproducible Benchmarks
Directly testing models based on intuition makes conclusions hard to reproduce. A reliable benchmark should include a sample set, evaluation dimensions, and statistical methods.
4.1 Sample Set Design
The sample set should come from real business traffic and cover tasks of varying difficulty. It is recommended to include at least the following four types of samples:
- Short Q&A: tests TTFT and baseline accuracy;
- Long document summarization: tests long-context processing and output stability;
- Structured extraction: tests whether the output format meets requirements;
- Complex reasoning: tests multi-step logic accuracy.
The quantity of each sample type should be sufficient to support statistical conclusions. With too few samples, a single anomalous result can alter the ranking.
4.2 Benchmarking Script
The following example demonstrates how to collect latency and throughput metrics, where call_fn is a wrapper for the specific service that you need to implement based on the API:
import statisticsimport timedef benchmark(call_fn, prompts, repeat: int = 3) -> dict:"""Call the same set of prompts multiple times to collect latency percentiles and average throughput."""records = []for prompt in prompts:for _ in range(repeat):start = time.perf_counter()resp = call_fn(prompt) # Assumes response format: {"text": ..., "usage": {"output_tokens": int}}elapsed_s = time.perf_counter() - startout_tokens = resp["usage"]["output_tokens"]records.append({"latency_ms": elapsed_s * 1000,"tps": out_tokens / elapsed_s if elapsed_s > 0 else 0.0,})latencies = sorted(r["latency_ms"] for r in records)p50 = statistics.median(latencies)p95 = latencies[min(len(latencies) - 1, int(len(latencies) * 0.95))]avg_tps = statistics.mean(r["tps"] for r in records)return {"p50_ms": p50, "p95_ms": p95, "avg_tps": avg_tps, "samples": len(records)}
There are two things to note with this script. First, measurements should be conducted in the same time window and network environment to avoid misinterpreting network fluctuations as model differences. Second, if the service supports streaming output, you should also record the Time To First Byte (TTFB), as perceived latency in streaming scenarios depends heavily on the first chunk.
4.3 Quality Assessment
Latency and cost are only half of the selection process; output quality is equally critical. Quality assessment can utilize three methods:
- Rule-based validation, such as checking if JSON is parseable and fields are complete;
- Manual spot-checking, suitable for open-ended generation tasks;
- Reference answer comparison, suitable for tasks with definitive correct answers.
Quality metrics should have a passing threshold. Only models that pass the threshold should proceed to the cost comparison phase.
5. Tiered Routing for Cost and Quality
In production systems, it is rare to route all requests through a single model. A common approach is tiered routing: simple tasks are handled by small models, while complex tasks are routed to large models. This controls costs while ensuring quality for critical tasks.
Here is a simplified routing example:
def route(task: dict) -> str:"""Select model tier based on task complexity and latency budget."""if task["requires_reasoning"]:return "large-tier"if task["complexity"] <= 2 and task["latency_budget_ms"] < 3000:return "small-tier"return "mid-tier"
The key to tiering is accurately judging task complexity. Common indicators include task type, input length, whether multi-step reasoning is required, and the historical failure rate of similar tasks. Once a tiered strategy is deployed, you should continuously monitor the quality and cost of each tier and adjust thresholds accordingly.
6. Rate Limiting and Stability
Most services cap request frequency, often measured in Requests Per Minute (RPM) or Tokens Per Minute (TPM). Rate limits must be factored into your evaluation; otherwise, peak performance may fall far short of benchmark results.
Engineering teams typically adopt the following measures:
- Client-side rate limiting: control request rates to stay within quotas;
- Exponential backoff retry: gradually increase wait times when encountering rate limits or temporary errors;
- Timeout control: set explicit upper bounds for each request to prevent a single slow request from stalling the entire pipeline;
- Fallback strategies: switch to a backup tier if the primary model is unavailable.
import randomimport timedef call_with_backoff(call_fn, prompt: str, max_retries: int = 5):"""Retry with exponential backoff on temporary errors, including random jitter."""for attempt in range(max_retries):try:return call_fn(prompt)except Exception:if attempt == max_retries - 1:raisesleep_s = min(30, (2 ** attempt)) + random.uniform(0, 0.5)time.sleep(sleep_s)
Random jitter prevents multiple clients from retrying simultaneously, reducing secondary congestion. In real-world projects, you should only retry retriable errors like rate limits and timeouts, and immediately throw exceptions for deterministic errors like invalid parameters.
7. Caching and Prompt Design
Caching and prompt structure directly impact token consumption. The following practices typically yield significant benefits:
First, place static content at the beginning of the prompt. System instructions, role definitions, and knowledge base snippets are more likely to form a reusable prefix if they remain stable.
Second, avoid inserting volatile content into the prefix, such as timestamps, request IDs, or random fields. These will invalidate the cache.
Third, compress conversational history. In multi-turn dialogs, you can retain key conclusions and discard pleasantries and repetitive content, reducing the number of tokens that need to be reprocessed each turn.
Fourth, constrain output length. Explicitly requiring output format and word count in the prompt, and setting a sensible maximum output token parameter, can directly lower output costs.
8. Selection Process and Decision Checklist
Synthesizing the above, model selection can proceed with the following steps:
- Define business constraints: latency limits, quality thresholds, max unit cost, and concurrency scale.
- Build a sample set covering main task types and difficulty tiers.
- Benchmark candidate models under identical conditions, recording P50, P95, throughput, and quality results.
- Use the billing formula to translate estimated costs for each task onto a comparable basis.
- Filter candidates that meet quality and latency thresholds, then compare costs.
- Design tiered routing and fallback strategies, and validate them with low-traffic canary testing.
- Continuously monitor costs, quality, and rate limits post-launch, and re-evaluate regularly.
Model selection is not a one-time decision. Model versions, billing rules, and business traffic will change. Regular re-evaluation is more valuable than a single optimal selection. As long as your benchmarking standards and cost metrics remain consistent, your team can quickly compare new models as they emerge and adjust your technical approach accordingly.
