LLM Cost Optimization in Practice: Tiered Routing and Off-Peak Scheduling

    This article explains how to control large language model API costs. It covers measuring token usage, classifying tasks by complexity, latency, and fault tolerance, routing requests to the cheapest model tier that meets quality requirements, scheduling non-urgent jobs off-peak, and enforcing budgets backed by evaluation sets.

    Introduction

    As large language models keep improving, developers call them more often in their daily work. Once call volume grows, cost quickly becomes a problem. A simple question-and-answer exchange may use only a few thousand tokens, while an agent task involving multi-step reasoning, tool calls, and repeated corrections can consume hundreds of thousands or even millions of tokens in a single run. Cost management therefore shifts from a financial concern to an engineering problem, and model calls need to be managed the way compute resources are managed.

    This article covers the following approach: first analyze where costs come from, then classify tasks, choose a model tier for each level, schedule non-urgent tasks off-peak, and finally use budgets and evaluation sets to protect quality.

    1. Where the Costs Come From

    1.1 Billing Is Based on Tokens

    Most model services meter usage by token, and input and output tokens are billed separately. Output prices are generally higher than input prices, but the exact figures depend on the provider’s pricing documentation. To control costs, you first need to understand how many input and output tokens each call uses. Input includes the system prompt, conversation history, retrieved documents, and tool return values. Output includes generated text and structured results. When any part grows, the bill rises directly.

    1.2 The Effect of Context Accumulation

    In multi-turn conversations, each request usually carries all of the previous history. If each turn adds a fixed amount of content, the input length of turn n is roughly proportional to n, and the cumulative input grows approximately quadratically with the number of turns. This means longer conversations make every later turn more expensive. Periodically compressing the history and keeping only the key information is an effective way to reduce this cost.

    1.3 Amplification in Agent Loops

    An agent typically goes through a cycle of planning, calling tools, observing results, and deciding again. Each step resends the previous context, and raw tool output is counted as input. If a tool returns thousands of lines of logs or an entire web page, the cost of each step rises quickly. For agents, the main optimization target is often not the model itself but how the context is organized.

    1.4 Retries and Failure Costs

    Failed requests, outputs that do not match the required format, and re-runs after manual intervention all create extra consumption. Failure costs are often overlooked because each one looks small, but together they can exceed the cost of normal calls. Tracking the failure rate and the number of retries is an important way to tell whether an optimization is working.

    2. Measure First, Then Optimize

    Optimization without data is essentially guesswork. Record the following fields for every model call: task type, model tier, input tokens, output tokens, latency, whether the call succeeded, and whether it was retried. After two to four weeks of data, you can see which tasks account for most of the cost.

    1. import time
    2. from dataclasses import dataclass, asdict
    3. @dataclass
    4. class UsageRecord:
    5. task_type: str
    6. tier: str
    7. input_tokens: int
    8. output_tokens: int
    9. latency_ms: int
    10. success: bool
    11. retried: bool
    12. timestamp: float
    13. usage_log: list[UsageRecord] = []
    14. def record_usage(task_type, tier, input_tokens, output_tokens,
    15. latency_ms, success, retried=False):
    16. usage_log.append(UsageRecord(
    17. task_type=task_type,
    18. tier=tier,
    19. input_tokens=input_tokens,
    20. output_tokens=output_tokens,
    21. latency_ms=latency_ms,
    22. success=success,
    23. retried=retried,
    24. timestamp=time.time(),
    25. ))
    26. def summarize_by_task():
    27. summary = {}
    28. for r in usage_log:
    29. item = summary.setdefault(r.task_type, {"tokens": 0, "calls": 0, "failures": 0})
    30. item["tokens"] += r.input_tokens + r.output_tokens
    31. item["calls"] += 1
    32. if not r.success:
    33. item["failures"] += 1
    34. return summary

    Summaries usually show a clear 80/20 pattern, where a small number of task types consume most of the tokens. Optimization should start with these high-consumption tasks.

    3. Task Classification

    Task classification is the prerequisite for tiered routing. To decide which tier a task belongs to, consider four dimensions: complexity, fault tolerance, latency requirements, and data sensitivity.

    Task Type Complexity Latency Requirement Fault Tolerance Suggested Tier
    Text classification, keyword extraction Low Low High Light
    Log summarization, format conversion Low Medium High Light
    Code completion, single-function explanation Medium High Medium Standard
    Code review, solution comparison High Medium Medium Standard or flagship
    Complex multi-step agent tasks High Low Low Flagship

    Complexity determines how much reasoning ability the model needs. Latency requirements determine whether a task can be queued or run asynchronously. Fault tolerance determines how much damage an incorrect output can cause. For example, content shown to external users has lower fault tolerance than an internal draft. Data sensitivity determines whether a task can use certain external services, which depends on compliance requirements.

    Each team should maintain its own classification table based on its own tasks, rather than copying someone else’s results.

    4. Designing Tiered Routing

    The core principle of tiered routing is to use the lowest-cost tier that meets the quality requirement by default, and to escalate to a higher tier only when a call fails or confidence is insufficient. This keeps the average cost under control while still delivering results on difficult tasks.

    1. from typing import Callable
    2. TIERS = ["light", "standard", "flagship"]
    3. def route_with_fallback(
    4. prompt: str,
    5. start_tier: str,
    6. call_model: Callable[[str, str], dict],
    7. passes_quality_gate: Callable[[dict], bool],
    8. max_escalations: int = 2,
    9. ) -> dict:
    10. idx = TIERS.index(start_tier)
    11. attempts = 0
    12. while True:
    13. tier = TIERS[idx]
    14. result = call_model(tier, prompt)
    15. attempts += 1
    16. if passes_quality_gate(result):
    17. result["tier"] = tier
    18. result["attempts"] = attempts
    19. return result
    20. if idx == len(TIERS) - 1 or attempts > max_escalations:
    21. result["tier"] = tier
    22. result["attempts"] = attempts
    23. result["needs_review"] = True
    24. return result
    25. idx += 1

    The key to this code is the quality gate function. It can be a format check, a unit test, a rule check, or a small model that scores the output. The more specific the gate, the more reliable the escalation logic. If the gate is too loose, many low-quality results will pass through. If it is too strict, escalations become frequent, and the cost can actually go up.

    The routing logic should also set an escalation limit. If a task still fails at the highest tier, send it to human review instead of retrying indefinitely.

    5. Off-Peak and Asynchronous Scheduling

    Some services have different pricing or different levels of concurrent resource pressure at different times of day. Batch tasks that do not need an immediate response, such as offline document processing, nightly index building, and historical data cleaning, can run during periods with more available capacity or lower prices.

    There are two points to watch when implementing this. First, check whether time-based pricing exists, and follow the rules published by the service provider rather than assuming based on experience. Second, keep the scheduling itself simple. If you spend a lot of effort studying time-of-day patterns to chase the lowest price, the scheduling strategy becomes the main job and defeats the purpose of improving efficiency.

    The following is a simple queue-based example. Tasks are queued by priority, and non-urgent tasks wait for a designated time window before running:

    1. import heapq
    2. from datetime import datetime
    3. PRIORITY_REALTIME = 0
    4. PRIORITY_BATCH = 1
    5. job_queue: list = []
    6. def submit(job_id: str, priority: int, payload: dict):
    7. heapq.heappush(job_queue, (priority, job_id, payload))
    8. def run_pending(is_batch_window: Callable[[datetime], bool], now: datetime):
    9. while job_queue:
    10. priority, job_id, payload = job_queue[0]
    11. if priority == PRIORITY_BATCH and not is_batch_window(now):
    12. break
    13. heapq.heappop(job_queue)
    14. execute(job_id, payload)
    15. def execute(job_id: str, payload: dict):
    16. print(f"executing {job_id}")

    Real-time tasks always take priority, and batch tasks are only pulled and executed within the designated window. The team defines the window based on business needs.

    6. Budget Control

    A system without budget constraints will see costs grow without limit as usage increases. Budget control generally works at three levels: per-task budgets, team budgets for each day or month, and per-user quotas.

    Per-task budgets prevent agents from getting stuck in loops. For example, you can limit the maximum number of steps, the maximum input length, and the maximum output length. When a limit is exceeded, the task should stop and return its current progress instead of continuing to consume resources.

    1. class BudgetExceeded(Exception):
    2. pass
    3. class BudgetGuard:
    4. def __init__(self, token_limit: int):
    5. self.token_limit = token_limit
    6. self.used = 0
    7. def charge(self, input_tokens: int, output_tokens: int):
    8. self.used += input_tokens + output_tokens
    9. if self.used > self.token_limit:
    10. raise BudgetExceeded(
    11. f"used {self.used} tokens, limit {self.token_limit}"
    12. )
    13. def remaining(self) -> int:
    14. return max(0, self.token_limit - self.used)

    Budgets should be checked before a call, not discovered after an overrun. For requests where the input length can be estimated, calculate the expected consumption before sending the request. If it exceeds the remaining allowance, reject the request or downgrade it to a cheaper tier.

    Budget alerts should also be tiered. Send a reminder at 70% usage, restrict non-critical tasks at 90%, and keep only real-time critical tasks when the limit is reached. The exact thresholds can be adjusted based on team size.

    7. Engineering Techniques for Reducing Per-Call Cost

    Routing and budgets answer the question of where the money is spent. The techniques below address how much each call costs.

    Keep the context lean. Include only the fragments relevant to the current question in each request. Retrieval can use a relevance threshold, and content below that threshold can be discarded.

    Truncate and summarize tool output. Raw data returned by tools should be trimmed or summarized before it is passed back to the model. For example, keep only error-level log entries and their surrounding context, or keep only the body text and title of a web page.

    Constrain output length. Stating the output format and word or length range in the prompt can significantly reduce unnecessary output tokens. Structured output, such as data with fixed fields, is also more compact than free text and easier to validate automatically.

    Reuse results. Cache responses for requests with identical inputs or highly similar meaning. Some services support reusing repeated prompt prefixes, and the applicable rules should be confirmed in the service provider’s documentation.

    Streamline prompt templates. Long-running prompt templates tend to accumulate redundant instructions. Reviewing them regularly and removing ineffective instructions can add up to meaningful savings across a large number of calls.

    Limit agent steps. Set a maximum number of iterations for agents and record progress at each step. If two consecutive steps make no real progress, stop and request human intervention.

    8. Quality Safeguards

    Reducing cost only makes sense if result quality does not suffer. Models at different tiers perform very differently on different tasks, so you cannot judge which tier is sufficient based on unit price or reputation.

    For each task type, build an evaluation set of 30 to 50 representative inputs, and define a verifiable reference answer or scoring rule for each input. After each change to the routing strategy, run the evaluation set and compare each tier’s pass rate, average token consumption, and average latency.

    The value of an evaluation set is that it turns “good enough, I think” into “the data shows it is good enough.” A task type should only be routed to a tier by default after that tier reaches the pass-rate threshold set by the team. The flagship tier should remain the fallback for complex or high-risk tasks.

    9. Common Misconceptions

    Misconception 1: Treating cost saving as the only goal. If you repeatedly retry or make frequent manual corrections to save money, the time cost can far exceed the savings on the bill. Cost evaluation should include human effort.

    Misconception 2: Looking only at unit price, not total volume. A lower-priced tier with a high failure rate and many retries may not consume less overall. The core metric should be the total consumption per successfully completed task.

    Misconception 3: One model for everything. Many teams use the same model for all tasks. This either wastes resources on simple tasks or produces weak results on complex ones. Tiered routing is a more reasonable choice.

    Misconception 4: Ignoring output length. Many prompts do not limit output, so the model generates lengthy explanations. When only a conclusion is needed, a clear length constraint is often the cheapest optimization.

    Misconception 5: Optimizing without monitoring. Without logging and aggregation, you cannot tell whether an optimization is working or find the cause of a sudden cost spike.

    10. Practical Steps

    Step 1: Record two to four weeks of call data, establish a cost baseline, and identify the task types with the highest consumption.

    Step 2: Classify tasks and define the complexity, fault tolerance, and latency requirements for each category.

    Step 3: Set a default tier and escalation rules for each task category, and validate them with an evaluation set.

    Step 4: Set budgets at three levels (task, team, and user), and configure alert thresholds.

    Step 5: Review monthly, checking pass rates, cost per successful task, and abnormal consumption, then adjust the classification and routing rules accordingly.

    There is no one-time solution to LLM cost management. It is an ongoing iterative process: measure first, then tier, then validate, and finally use budgets to hold the line. By keeping this cycle going, a team can find the balance between effectiveness and cost that suits its own needs.