Tiered LLM Selection: Balancing Quality, Cost, and Security in Coding Tasks
This article explains how software teams can adopt a tiered model-selection strategy for LLM-powered coding workflows. It covers four dimensions for classifying tasks, a token-based cost estimation model with code examples, how to build internal benchmarks instead of relying on public leaderboards, evaluation metrics for security tasks, and practical engineering patterns for routing, budgets, and fallback mechanisms.
1. Background: A Single Model Rarely Fits Every Task
Once a software team adopts large language models, a practical problem quickly emerges. The same model is asked to autocomplete a single line of code and, moments later, to trace the root cause of a defect spanning multiple repositories. These two types of requests can differ by an order of magnitude in cost and latency. Routing everything to the most capable model makes the bill spiral out of control. Routing everything to a lightweight model drives up the rework rate on complex tasks.
As a result, more teams are adopting a tiered strategy, dispatching requests to different model tiers based on task difficulty. This resembles service tiering in backend systems: the goal is to match capability with cost.
2. Four Dimensions for Classifying Task Tiers
To decide which tier a task belongs to, consider the following four dimensions.
- Reasoning complexity: Does the task require multi-step reasoning, such as concurrency race analysis or complex algorithm optimization? The more reasoning steps involved, the higher the tier should be.
- Verifiability: Can the result be validated automatically through tests, compilation, or static analysis? Verifiable tasks tolerate retries, because errors are caught quickly.
- Cost of failure: How damaging is an error? Tasks involving permission changes, fund transfers, or data deletion carry a high cost of failure and should use a more robust tier, with human review retained.
- Context size: How much code and documentation must be read in? The longer the context, the more input tokens are consumed, and the higher the cost.
Based on these dimensions, tasks can be grouped into three tiers.
- Basic tier: code completion, format conversion, comment generation. These tasks are latency-sensitive, and per-call cost should be kept as low as possible.
- Standard tier: routine feature development, unit test writing, code review comments. These tasks require some comprehension but rarely demand deep reasoning.
- Deep tier: cross-module refactoring, hard-to-diagnose defect localization, security audits. These tasks need long chains of reasoning and repeated verification, so higher cost is acceptable.
3. Understanding the Token-Based Cost Model
Most model services bill by tokens, distinguishing between input and output tokens. Output tokens are usually priced higher than input tokens. Reasoning models also generate internal reasoning content before producing an answer, and those tokens are billed as well. The true cost of a task therefore depends on three things: how much you read in, how much you generate, and how much reasoning occurs.
The cost of a single task can be estimated with the following formula:
Task cost = input tokens × input price + output tokens × output price + reasoning tokens × reasoning price
Suppose a tier charges 2 yuan per million input tokens and 10 yuan per million output tokens. A code review that reads 30,000 tokens and generates 2,000 tokens costs about 0.06 yuan for input and 0.02 yuan for output—0.08 yuan in total. If the task fails verification and requires two retries, the total cost is roughly 0.24 yuan. The prices in this example are only for demonstrating the calculation method; actual selection should be based on the provider’s current price list.
Prices may change due to promotions or periodic adjustments. A budget model should treat price changes as a parameter, not a fixed constant.
The following code shows how to factor retry counts into cost, instead of looking only at the price of a single call.
def task_cost(input_tokens: int, output_tokens: int,reasoning_tokens: int, prices: dict,retries: int = 0) -> float:"""Compute the total cost of a task, including retries.Prices are in yuan per million tokens."""per_call = (input_tokens * prices["input"]+ output_tokens * prices["output"]+ reasoning_tokens * prices["reasoning"]) / 1_000_000return per_call * (1 + retries)
4. Evaluate Models on Internal Benchmarks, Not Just Public Leaderboards
Public leaderboards reflect general model capability, but they cannot represent your team’s codebase, coding conventions, or business scenarios. A more reliable approach is to extract 200 to 500 real tasks from historical tickets and build an internal benchmark. Each task should come with an automatically gradable acceptance script, such as unit tests or API tests.
Recommended metrics include:
- First-pass rate: the proportion of tasks that pass acceptance without human modification.
- Cost per task: total spending, including retries, divided by the number of completed tasks.
- End-to-end latency: the time from task submission to a usable result.
- Rework rounds: the average number of human edits required.
A single metric can easily mislead decisions. A better way to compare options is to plot cost and pass rate for each tier on the same chart and examine the trade-offs. Options that fall inside the curve—lower pass rate at the same cost, or higher cost at the same pass rate—can be ruled out directly.
Watch out for data contamination as well. If benchmark items already appeared in a model’s training data, scores will be inflated. Periodically replace part of the benchmark, and keep a private set of items used only internally.
5. Evaluation Metrics for Security Tasks
In vulnerability scanning scenarios, two metrics are commonly used to measure effectiveness.
- Recall: the proportion of real vulnerabilities that are detected, reflecting false negatives. It is calculated as TP / (TP + FN).
- Precision: the proportion of reported issues that are actual vulnerabilities, reflecting false positives. It is calculated as TP / (TP + FP).
Both metrics must be observed together. Setting the detection threshold very low can push recall up, but it generates a flood of false positives, and developers quickly lose trust in the reports. The F1 score, the harmonic mean of the two, can serve as a composite metric.
For defensive testing, two additional metrics are common.
- Attack interception rate: the proportion of attack paths blocked by defensive mechanisms in simulated attacks.
- Attack success rate: the number of attacks that successfully bypass defenses divided by the total number of attacks.
Such tests must be conducted within authorized scope and isolated from production environments. Test samples should cover known attack patterns and mutated variants, and results should be broken down by attack type, so that a single aggregate average does not hide weaknesses against a particular class of attacks.
6. Engineering Implementation: Routing, Budgets, and Fallback
With tiering criteria and evaluation data in hand, the next step is implementing the router. The router selects a tier based on task attributes. Rules should be simple, explainable, and adjustable as evaluation results evolve.
from dataclasses import dataclass@dataclassclass Task:complexity: int # reasoning complexity, from 1 to 5verifiable: bool # whether the result can be verified automaticallyrisk: int # cost-of-failure risk, from 1 to 5context_tokens: int # number of tokens in the input contextdef choose_tier(task: Task) -> str:if task.risk >= 4:return "deep"if task.complexity >= 4 and not task.verifiable:return "deep"if task.complexity >= 3 or task.context_tokens > 50_000:return "standard"return "basic"
Beyond routing, three supporting mechanisms are needed.
- Budget thresholds: set daily and monthly spending caps for each project. When approaching the limit, automatically fall back to a lower tier or pause non-critical tasks.
- Retry limits: cap the maximum number of retries per task. Unlimited retries are the most common cause of runaway costs.
- Result caching: reuse existing results for identical inputs to avoid duplicate billing.
Logging also requires security awareness. Call logs should not retain keys, tokens, or personal information embedded in source code; redact sensitive content before writing logs.
7. Common Pitfalls
- Treating the most powerful tier as the default. Most day-to-day tasks can be handled by the standard tier; defaulting to the deep tier wastes a large share of the budget.
- Looking only at per-call price, while ignoring the extra cost from retries and context growth.
- Substituting public leaderboards for internal evaluation. Leaderboard rankings cannot be directly extrapolated to a team’s own scenarios.
- Focusing only on recall in security scenarios, while ignoring the impact of false positives on developer productivity.
- Merging model output directly into the main branch without automated tests or human review. Model-generated code must pass the same quality gates as human-written code.
