Controlling LLM Token Costs in Practice: From API Calls to Architecture

    This article explains how to control token costs in large language model applications. It covers where tokens are consumed, how pay-as-you-go and subscription billing compare, call-level measures such as context trimming and semantic caching, architecture choices such as model routing and batch processing, and how to track costs and usage through monitoring.

    LLM applications often consume tokens faster than expected after launch. A weekly quota can run out in a few days, and teams then fall into “token anxiety.” Runaway consumption usually has no single cause. Several factors compound. This article covers five areas: where tokens are spent, billing models, call-level optimization, architecture design, and usage monitoring. Each section offers practices that can be applied step by step.

    1. Finding Where Tokens Are Spent

    The cost of each request depends on both input tokens and output tokens. Input tokens include the system prompt, conversation history, retrieved documents, and tool results. Many teams focus only on output and overlook that input grows linearly with the number of conversation turns.

    Common sources of waste fall into three categories:

    • Full conversation history is sent back with every request, so the context grows with each turn.
    • Prompts are verbose, and the same rules repeat in every request.
    • Frequently asked questions still go through a full model call every time.

    Start by measuring input and output tokens by API endpoint, feature module, and tenant. Identify the largest contributors, then decide the order of optimization.

    2. Choosing Between Pay-as-You-Go and Tiered Subscriptions

    Major providers generally offer two billing models.

    Pay-as-you-go billing charges only for what you use, which suits businesses with volatile traffic or those still in the exploration stage. Its drawbacks are higher unit prices and no spending cap, so abnormal calls can cause billing spikes.

    Tiered subscriptions and prepaid quotas offer lower unit costs and more predictable spending, which suits businesses with stable, high baseline traffic. Their drawbacks are that unused quota can go to waste, and the quota may run out during peak periods.

    When choosing, consider two metrics: the ratio of average daily usage to peak usage, and how stable the baseline usage is. When the baseline is stable and high, a common hybrid approach covers the baseline with a subscription and handles overflow with pay-as-you-go billing. Check the provider’s latest pricing for actual prices, and run a cost estimate based on historical usage before deciding.

    3. Call-Level Optimization

    3.1 Context Trimming

    Optimizing prompts is the most direct method. Prompts should use structured instructions and drop repeated descriptions and irrelevant examples. For multi-turn conversations, limit the amount of history passed in.

    A common approach keeps the most recent N turns verbatim and compresses earlier content into a summary or an entity table. Summaries also consume tokens and lose detail, so keep key facts such as user preferences, confirmed parameters, and unresolved issues.

    1. def build_context(history, max_turns=5, summarize=None):
    2. """Keep the most recent max_turns turns verbatim and compress older turns into a summary."""
    3. if len(history) <= max_turns:
    4. return history
    5. older, recent = history[:-max_turns], history[-max_turns:]
    6. messages = list(recent)
    7. if summarize is not None:
    8. summary = summarize(older) # The summary also consumes tokens and must be counted in the budget.
    9. messages.insert(0, {"role": "system", "content": f"Conversation summary: {summary}"})
    10. return messages

    When trimming, watch for several issues. Do not separate a tool call request from its tool result, or the model may return errors or hallucinate. Token counts differ from character counts, so base budgets on the tokenizer’s counts, and note that different models use different tokenizers. The system prompt must be counted in the budget as well.

    3.2 Semantic Caching

    For frequently repeated questions, a cache can skip the model call. Caching comes in two forms: exact matching and semantic matching. Exact matching only hits on identical requests. It is safe but has a low hit rate. Semantic caching matches similar questions using vector similarity. It achieves higher hit rates but requires additional design.

    A semantic cache must handle at least the following:

    1. Cache key: besides the question text, include the model name and version, a hash of the system prompt, parameters that affect output such as temperature, and the tenant identifier. Without these fields, answers for different scenarios can get mixed up.
    2. Similarity threshold: do not set the threshold by intuition. Use manually labeled pairs of similar questions on a validation set to compare the false-hit rate with the hit rate, then choose an acceptable balance.
    3. Invalidation and consistency: when the knowledge base is updated, the prompt changes, or the model is upgraded, related cache entries must be invalidated. Set expiration times, and clear entries proactively when the data source changes.
    4. Privacy boundaries: requests containing personal information, order numbers, or internal data should not be written to a shared cache. Redact them before writing, and isolate cache space by tenant.

    Confirm the cache hit rate with production data. Do not assume a fixed percentage of tokens will be saved before evaluating the benefit.

    4. Architecture-Level Cost Control

    4.1 Model Routing

    Not every task needs a flagship model. Tasks such as classification, intent recognition, and format conversion can usually go to smaller models. Complex reasoning and long-form generation require flagship models.

    1. def route_model(query, threshold):
    2. score = evaluate_complexity(query) # Complexity score; requires offline calibration
    3. if score > threshold:
    4. return call_flagship(query)
    5. return call_lightweight(query)

    Do not apply the example threshold directly. A sound approach is to:

    • Run a labeled sample set through both the small model and the flagship model, and compare quality and cost;
    • Select the lowest-cost threshold that still meets quality requirements;
    • Validate with A/B testing before launch, and keep monitoring the escalation rate.

    Routing also needs a fallback. If the small model’s output fails format validation, has low confidence, or the user asks for a retry, escalate the request to the flagship model. A high escalation rate means the threshold is too aggressive and needs adjustment.

    Whether routing reduces cost depends on three factors: the share of simple requests in total volume, the small model’s quality on those requests, and the extra overhead from escalations and retries. Estimate all three using actual data.

    4.2 Asynchronous Batch Processing

    Batch processing suits tasks that don’t need real-time responses, such as data cleaning, log analysis, and bulk labeling. It does not suit interactive conversations, because users will not accept waiting in a queue.

    Recommended implementation steps:

    1. Enqueue tasks with idempotency keys to avoid duplicate submissions.
    2. Aggregate tasks by fixed size or time window, and submit them to the batch API.
    3. Retry rate limits and transient errors with exponential backoff.
    4. Move tasks that fail repeatedly to a dead-letter queue for manual handling.
    5. Record token usage and latency for each batch to support later review.

    If the provider offers batch discounts, first confirm which models the discount applies to and how it is billed, then include it in the cost model.

    5. Cost Accounting and Usage Monitoring

    Optimization results need to be quantified. Build the accounting table below and update it regularly.

    Metric Meaning Data Source
    Input and output unit prices Price per 1K tokens for each model Provider pricing page
    Cache hit rate Share of cache-hit requests in total requests Cache service logs
    Small-model routing share Share of requests routed to the small model Routing logs
    Escalation rate Share of small-model requests escalated to the flagship model Routing logs
    Batch share and discount Share of tokens processed in batches, and the discount rate Task system and billing

    Monthly cost can be roughly estimated with the following formula:

    Monthly cost ≈ total requests × (1 − cache hit rate) × [small-model share × small-model cost per request + (1 − small-model share) × flagship-model cost per request + escalation rate × small-model share × flagship-model cost per request]

    This is only an estimate. Actual billing governs.

    For monitoring, use the log services and alerting features that cloud providers offer to collect metrics such as call volume, token consumption rate, error rate, and escalation rate. Beyond setting usage thresholds, monitor the consumption rate as well. Projecting when the quota will run out at the current rate catches problems earlier than percentage-based alerts alone. For example, an alert can be triggered when daily consumption reaches 70% of the quota.