🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Controlling LLM Costs in Production Systems

AI Safety & GuardrailsCost OptimizationđŸŸĸ Free Lesson

Where LLM spend actually goes

LLM cost is unusual in that it scales with usage in near-linear, metered increments, which makes it both terrifying and unusually tractable. A traditional service's cost is dominated by provisioned capacity and moves in steps; an LLM application's cost is dominated by tokens and moves with every request. That means the levers are known precisely — input tokens, output tokens, model choice, request volume — and most teams discover that a small number of patterns drive the majority of the bill.

The usual distribution: a large share of requests are trivial (reformattings, greetings, lookups already cached somewhere), a moderate share are routine, and a small share are genuinely complex. Sending all three tiers to the same frontier model is the most common and most expensive mistake. Output tokens typically cost three to five times input tokens, so chatty, verbose answers are disproportionately expensive; a "respond in one paragraph" instruction is a cost control as much as a style choice.

The second structural fact is that cost and quality are not simply opposed. Routing a simple classification to a small model, caching a semantically equivalent question, and compressing a bloated system prompt all reduce spend while leaving quality untouched or even improving it. The goal is not to spend less at any cost; it is to stop paying frontier-model prices for frontier-model work that was never requested.

Reading a token bill like an engineer

Start with arithmetic. Cost per request equals input tokens divided by a million times the input price, plus output tokens divided by a million times the output price. Every request should log its model, input token count, output token count, and calculated cost, keyed by endpoint and by tenant. Without that log you are managing a budget by vibes.

Model classInput per 1M tokensOutput per 1M tokensAppropriate for
Frontier (GPT-4 class)8–15Hard reasoning, code, agents
Mid-tier (Sonnet, 4o class)3–10General chat, extraction
Small (Haiku, mini, 8B)0.30–1.50Classification, routing, rewriting
Open-weights self-hostedHardware amortisedHardware amortisedHigh steady-state volume

Those numbers are illustrative and move quarterly; the ratios are what to remember. A frontier-to-small price gap of twenty to fifty times means a routing layer that sends even a quarter of traffic to a small model can cut the bill in half before any caching is applied.

Track four derived metrics per endpoint: cost per request, cost per successful task (failed requests still cost money), cache hit rate, and cost per active user. The last one aligns engineering decisions with the business conversation; "we reduced cost per active user from eleven cents to four" is a sentence a finance team can act on.

python
from collections import defaultdict
from dataclasses import dataclass


@dataclass
class UsageRecord:
    model: str
    endpoint: str
    tenant: str
    input_tokens: int
    output_tokens: int
    cost_usd: float
    success: bool


class CostLedger:
    def __init__(self, pricing: dict[str, dict[str, float]]):
        self.pricing = pricing
        self.records: list[UsageRecord] = []

    def log(self, model: str, endpoint: str, tenant: str,
            input_tokens: int, output_tokens: int, success: bool = True) -> UsageRecord:
        price = self.pricing[model]
        cost = (input_tokens / 1e6 * price["input"]
                + output_tokens / 1e6 * price["output"])
        record = UsageRecord(model, endpoint, tenant, input_tokens,
                             output_tokens, cost, success)
        self.records.append(record)
        return record

    def by_endpoint(self) -> dict[str, dict]:
        totals = defaultdict(lambda: {"cost": 0.0, "requests": 0, "failures": 0})
        for r in self.records:
            bucket = totals[r.endpoint]
            bucket["cost"] += r.cost_usd
            bucket["requests"] += 1
            bucket["failures"] += 0 if r.success else 1
        for bucket in totals.values():
            bucket["cost_per_request"] = (
                bucket["cost"] / bucket["requests"] if bucket["requests"] else 0.0
            )
        return dict(totals)

Log the record at the client wrapper, not in each feature's code path, so every model call is metered even when a new endpoint forgets to report.

Model routing: cheapest model that can do the job

Routing is a classification problem layered on top of a registry. Each model entry records price, capabilities, context window, and any compliance flags. Each request is classified — by rules, by a small model, or by both — into a complexity tier, and the router selects the cheapest model whose capabilities cover the tier.

Start with rules; they are transparent and cheap. Short inputs with classification-shaped intents route small. Requests requiring multi-step reasoning, long documents, or code generation route to the frontier tier. Ambiguity routes up, never down. Then layer a small-model gatekeeper that rewrites or rejects requests that do not belong at all, which protects the expensive tier from junk.

python
from dataclasses import dataclass


@dataclass(frozen=True)
class ModelSpec:
    name: str
    input_per_m: float
    output_per_m: float
    tier: str            # small | mid | frontier
    max_context: int


class CostAwareRouter:
    def __init__(self, models: list[ModelSpec]):
        self.by_tier = {}
        for m in sorted(models, key=lambda x: x.input_per_m + x.output_per_m):
            self.by_tier.setdefault(m.tier, m)

    def tier_for(self, prompt: str, needs_code: bool = False) -> str:
        words = len(prompt.split())
        reasoning_markers = ("prove", "step by step", "refactor", "debug", "design a")
        if needs_code or words > 400 or any(m in prompt.lower() for m in reasoning_markers):
            return "frontier"
        if words > 80:
            return "mid"
        return "small"

    def select(self, prompt: str, needs_code: bool = False) -> ModelSpec:
        return self.by_tier[self.tier_for(prompt, needs_code)]

    def estimate(self, spec: ModelSpec, in_tokens: int, out_tokens: int) -> float:
        return (in_tokens / 1e6 * spec.input_per_m
                + out_tokens / 1e6 * spec.output_per_m)

Validate routing with an evaluation set scored per tier. If the small model's quality on its assigned slice is within a few points of the frontier model's, the savings are real. If it is not, tighten the rules rather than abandoning routing — the middle ground usually still holds half the traffic.

Caching: exact, semantic, and curated

Exact caching is free money: hash the normalised prompt plus model parameters and return the stored response. It works brilliantly for FAQ-shaped traffic and system-prompt-heavy workloads where many requests differ only trivially.

Semantic caching goes further by matching on embedding similarity, so "what is your refund policy" and "how do I get a refund" share one cached answer. The risk is answering a subtly different question confidently, so set the similarity threshold high (0.95 or above), exclude short queries where similarity is unreliable, and include the user's plan or locale in the key so answers are not shared across contexts that should differ.

Curation is the third layer: a hand-maintained answer set for the highest-volume intents, versioned like code. It removes those requests from the model path entirely and gives you deterministic quality where it matters most.

Prompt and output budgeting

System prompts accumulate. Teams append instructions for tone, format, safety, and six product features, and nobody ever subtracts. Measure the token count of your system prompt weekly; anything above roughly eight hundred tokens deserves an audit for redundancy, because you are paying for those tokens on every single request, forever.

Output limits are the other half. Set a maximum token count per endpoint based on what the UI actually renders, and instruct brevity where the task allows it. Prompt compression techniques — removing filler politeness, abbreviating stable boilerplate, moving rarely used instructions behind a retrieval step — typically recover ten to thirty percent of input tokens with no measurable quality change.

Batching, quotas and chargeback

Asynchronous workloads — summarisation pipelines, nightly enrichment, evaluation runs — qualify for batch discounts at most providers, often around half price. Scheduling non-urgent jobs into the batch window is one of the largest single savings available and requires no quality trade-off at all.

Quotas complete the picture. Per-user daily token budgets, per-endpoint monthly caps, and hard stops with clear degradation behaviour (downgrade to a small model, then refuse politely) turn cost from an emergent property into a governed one. Chargeback by team or feature makes the governance stick: when a product manager sees their feature's line item, prompt bloat tends to resolve itself.

A cost review cadence that sticks

Monthly, review the top ten requests by spend, the cache hit rate by endpoint, and the routing distribution against the evaluation scores. Quarterly, re-price the registry against current provider rates and re-test whether a cheaper model tier now meets quality bars — the answer is almost always yes somewhere, because model quality improves faster than prices fall. Cost management is not a one-time project; it is a meter you keep reading.

Common Mistakes

Sending every request class to the same frontier model

Fix: Classify complexity and route to the cheapest capable tier; re-validate tiers quarterly against an evaluation set.

Skipping semantic caching over fears of stale answers

Fix: Cache at high similarity thresholds, exclude short queries, and key on user context such as plan and locale.

Letting system prompts grow without a token budget

Fix: Measure prompt token counts weekly and audit anything beyond roughly eight hundred tokens for redundancy.

Running async enrichment jobs through the synchronous endpoint

Fix: Schedule non-urgent work in provider batch windows, typically at about half the price.

Key Takeaways

  • Output tokens cost several times input tokens, so verbosity is a cost lever, not just a style choice.
  • Log model, token counts, and calculated cost per request — derived metrics like cost per active user drive real decisions.
  • A routing layer that moves even a quarter of traffic to small models can halve the bill with minimal quality loss.
  • Exact, semantic, and curated caches each remove different slices of traffic from the model path entirely.
  • Audit system prompt token counts and set per-endpoint output limits; both are recurring costs on every request.
  • Batch non-urgent workloads, enforce per-user budgets, and charge spend back to teams to keep the meter honest.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert AI Ops & LLM Ops Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement