Tiered Model Routing with Fallback: Engineering Practices for LLM Cost Control
Large language model costs can spiral quickly in agent workloads, where multi-turn loops and growing context windows drive token consumption into the hundreds of thousands per task. This article presents a practical engineering approach: classify tasks into tiers, assign candidate models to each tier, route requests by priority, and automatically fall back when a model fails. It includes a working Python implementation, cost accounting formulas, budget estimation, token reduction techniques, and evaluation metrics for production rollout.
1. Where the Cost Comes From
An ordinary Q&A interaction usually involves only a few thousand tokens: one input, one output, done. Agent-style tasks are different—they run in multi-turn loops. The agent reads multiple files, analyzes structure, edits several locations, runs tests, and continues fixing based on failure messages. Each turn resends the previous context to the model, so input tokens accumulate rapidly.
For a typical coding task, consuming several hundred thousand tokens is common; complex refactoring or debugging sessions can reach millions. At current pricing, a single task may cost anywhere from roughly one to a few US dollars. Running multiple tasks daily can easily push the monthly bill to dozens of dollars or more. These figures vary by provider and model version—always base your analysis on your own request logs and invoices.
When cost pressure appears, the first instinct is often to switch to a cheaper model. That helps somewhat, but it has two problems. First, a cheaper model tends to retry and rework more on difficult tasks, and the extra tokens may offset the unit-price advantage. Second, if you start chasing off-peak pricing windows, your tooling decisions end up being driven by prices. A more robust approach is to establish a routing strategy that lets model selection adapt to task difficulty, budget, and service reliability.
2. Define Goals and Task Tiers First
The approach in this article: classify tasks into tiers, configure candidate models per tier, route by priority, and automatically fall back on failure. Before choosing models, clarify three things.
- Quality requirements: What does failure cost? Modifying production code or handling authentication and payment logic demands a high bar. Generating boilerplate or summarizing documentation can tolerate lower-cost results.
- Cost ceiling: The daily and monthly budget per project, and the budget per task.
- Availability requirements: When the service is interrupted or times out, can the task be deferred, or must it switch models immediately?
You usually cannot optimize all three at once. Higher quality often means higher unit prices or longer latency. Cutting context to save money can cause multi-turn rework. So classify tasks by tier and pick a model that is just good enough for each tier.
| Tier | Typical Use Cases | Selection Principle |
|---|---|---|
| Flagship tier | Architecture design, hard bug diagnosis, critical code review | Quality first, cost second |
| Light tier | Code completion, single-file edits, log analysis, doc summaries | Cost and speed first, quality just good enough |
| Fallback tier | Takes over when the primary model is rate-limited, times out, or produces malformed output | Availability first; ideally from a different provider than the primary |
Most daily tasks land in the light tier; only a few high-risk tasks go to the flagship tier. The fallback tier does not carry sustained heavy traffic, but it ensures your workflow does not stall entirely when the primary service goes down.
Tier boundaries should be data-driven. Sample each task category and measure the light tier’s pass rate. If it stays below an agreed threshold (for example, 90%—set your own threshold per task type), move that task category up to the flagship tier.
3. Implementing Routing and Fallback in Code
The following example does three things: filters candidate models by task type, retries a limited number of times within a single model, switches to the next candidate on failure, and logs the reason and cost of every attempt. Model names and prices in the example are placeholders—replace them with your own configuration and billing rates.
The example runs on Python 3.9+ using only the standard library. In real usage, the call function would invoke the provider’s SDK internally and pass timeout_s to the SDK’s timeout parameter.
import loggingimport timefrom dataclasses import dataclass, fieldfrom typing import Callablelogging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")log = logging.getLogger("llm_router")class ModelError(Exception):"""Recoverable model error, e.g. rate limiting, timeout, or malformed output."""@dataclassclass ModelEndpoint:name: strtier: str # "flagship" / "light" / "fallback"price_input: float # Price per million input tokens; verify against billingprice_output: float # Price per million output tokens; verify against billingcall: Callable[[str, int, float], dict] # call(prompt, max_output_tokens, timeout_s)timeout_s: float = 60.0@dataclassclass CallResult:model: strtext: strcost: floatattempts: list = field(default_factory=list)TASK_TIER = {"architecture": "flagship","bugfix_critical": "flagship","code_completion": "light","log_analysis": "light","doc_summary": "light",}def route(task_type: str, pool: list[ModelEndpoint]) -> list[ModelEndpoint]:"""Return an ordered candidate list: same-tier models first, fallback tier last."""if task_type not in TASK_TIER:raise ValueError(f"Unknown task type: {task_type}")target = TASK_TIER[task_type]primary = [ep for ep in pool if ep.tier == target]fallback = [ep for ep in pool if ep.tier == "fallback"]candidates = primary + fallbackif not candidates:raise RuntimeError("Candidate model pool is empty")return candidatesdef call_cost(ep: ModelEndpoint, input_tokens: int, output_tokens: int) -> float:"""Cost per call = input_tokens/1e6 * input price + output_tokens/1e6 * output price."""return (input_tokens / 1_000_000) * ep.price_input + (output_tokens / 1_000_000) * ep.price_outputdef run_task(task_type: str,prompt: str,pool: list[ModelEndpoint],validate: Callable[[str], bool] = lambda text: bool(text.strip()),max_output_tokens: int = 2048,retries_per_model: int = 2,) -> CallResult:attempts = []for ep in route(task_type, pool):for i in range(retries_per_model):started = time.monotonic()try:resp = ep.call(prompt, max_output_tokens, ep.timeout_s)text = resp["text"]if not validate(text):raise ModelError("Output failed validation")cost = call_cost(ep, resp["input_tokens"], resp["output_tokens"])attempts.append({"model": ep.name, "ok": True, "cost": cost})log.info("Task %s completed by %s, cost %.6f", task_type, ep.name, cost)return CallResult(ep.name, text, cost, attempts)except ModelError as e:reason = str(e)except Exception as e: # Log only exception type and message, never prompt contentreason = f"{type(e).__name__}: {e}"elapsed = time.monotonic() - startedattempts.append({"model": ep.name, "ok": False, "reason": reason})log.warning("Model %s attempt %d failed: %s (elapsed %.2fs)", ep.name, i + 1, reason, elapsed)if i < retries_per_model - 1:time.sleep(min(2 ** i, 8)) # Exponential backofflog.warning("Model %s exhausted retries, switching to next candidate", ep.name)raise RuntimeError(f"Task {task_type} failed on all candidate models: {attempts}")def _always_rate_limited(prompt, max_output_tokens, timeout_s):raise ModelError("429 rate limited")def _stable(prompt, max_output_tokens, timeout_s):# In a real implementation, call the provider SDK here and return the# actual token usage reported by the providerreturn {"text": "Simulated review conclusion", "input_tokens": 3200, "output_tokens": 420}if __name__ == "__main__":pool = [ModelEndpoint("flagship-a", "flagship", 15.0, 75.0, _always_rate_limited),ModelEndpoint("light-b", "light", 0.5, 2.0, _stable),ModelEndpoint("fallback-c", "fallback", 1.0, 4.0, _stable),]result = run_task("architecture", "Please review this refactoring plan", pool)print(result.model, round(result.cost, 6))
When you run this, flagship-a gets rate-limited twice, the program switches to fallback-c, completes the task, and prints fallback-c along with the cost.
A few basic requirements for handling keys: read API keys from environment variables, e.g. os.environ["LLM_API_KEY"], never hardcode them, and never commit them to configuration repositories. Logs should record only the model name, error type, and elapsed time—never print prompt bodies or keys. Sanitize error messages before writing them to logs.
4. Cost Accounting and Budgeting
The cost of a single task is the sum of all model call fees. Every turn of an agent loop counts, including failed calls and rework calls, because they all generate charges.
Cost per task = Σ [ input_tokens_i ÷ 1,000,000 × input price + output_tokens_i ÷ 1,000,000 × output price ]
Two points about the accounting method. First, token counts should come from the usage fields returned by the provider and be correlated with request logs. Second, unit prices should come from that month’s bill for the corresponding model. Some providers price cached input tokens separately, in which case inputs must be split into cache-hit, cache-miss, and output components and calculated separately.
Estimate monthly budget by tier:
def monthly_budget(daily_tasks: dict[str, float], avg_cost: dict[str, float], days: int = 30) -> float:"""Estimate monthly cost by tier. avg_cost should include failed and rework calls."""return sum(daily_tasks[tier] * avg_cost[tier] * days for tier in daily_tasks)print(monthly_budget({"light": 200, "flagship": 10}, {"light": 0.8, "flagship": 6.5}))
Here avg_cost should come from real log data averaged per tier, not hand-written ideal values. Reconcile your estimates against actual bills monthly, and when the deviation is large, review your routing rules and rework rates.
5. Engineering Techniques to Reduce Token Consumption
The following techniques are ordered by return on investment and can be adopted one by one.
- Context trimming: Keep only the files and conversation relevant to the current step; remove historical outputs for problems already solved.
- Rolling summarization: After the conversation exceeds a certain number of turns, compress earlier content into a brief state summary of a few hundred words and replace the original records.
- Prompt caching: Place stable content such as system prompts and tool descriptions at the front of the request, keeping the prefix consistent so providers can reuse the cache. Whether this earns a billing discount depends on the provider’s documentation.
- Chunked retrieval: Don’t send large files wholesale—use retrieval or a symbol index to locate relevant fragments first.
- Trim tool outputs: For test logs, keep only failing cases and error stacks; truncate overly long output and note where content was omitted.
- Constrain output: Ask the model to output a diff or JSON with specified fields rather than rewriting entire files, and set
max_output_tokens. - Set turn and budget limits: Give the agent loop a maximum number of turns and a per-task budget. When limits are exceeded, stop execution and escalate to a human.
6. Evaluation and Pre-Launch Checklist
Evaluation must consider quality, cost, and stability together—looking at unit price alone is meaningless. Track these metrics:
- Pass rate: The share of tasks whose outputs pass validation and are accepted by tests or review.
- Rework rate: The share of tasks that need reruns or manual fixes.
- Average cost per task: Measured per tier, including failed and rework calls.
- Fallback trigger rate: The share of calls that end up in the fallback tier.
- P95 latency: The time within which 95% of tasks complete.
Your sample set determines whether evaluation is trustworthy. For each task category, compile 50–100 real historical tasks, annotate expected results, and cover easy, hard, and edge cases. Every time you change routing rules or swap models, rerun the same sample set and compare these metrics.
Before going live, check the following:
- API keys are injected via environment variables, not written into code or committed to configuration repositories.
- Logs do not print prompt bodies or keys, and error messages are sanitized.
- A daily budget cap is configured, with execution stopped once exceeded.
