LLM cost control is the work of measuring, reducing and governing the cost of each AI task, not just reviewing a provider invoice at month end. Six patterns make the biggest difference: cache repeated prompts, route simple tasks to smaller models, trim context, reuse suitable answers, cap tenant consumption and move non-urgent work to batch processing. Start with a baseline for cost per successful task, then apply these controls without weakening quality or service.
Token spend becomes a product cost as soon as customers rely on AI features. A feature can look inexpensive in a demo, then become a material cost of goods sold when it repeats long prompts, sends irrelevant context, or retries tool calls. That directly affects the gross margin of an AI-enabled product. We work with teams on AI strategy and solutioning to connect those technical choices to product economics and business priorities.
The patterns below are architectural controls, not a promise of a particular saving. Provider prices, cache rules and model capabilities change, so verify the current terms before you budget. The figures in the worked example are a transparent scenario using the supplied token volumes and input and output rates, not a forecast for your workload.
1. LLM cost control: freeze stable prompt prefixes
A prompt often contains both stable material and changing material. Stable material can include system instructions, examples, tool definitions, schemas and reference documents. Changing material includes the current user question, the latest conversation turn and request-specific data. If you send all of that again on every request, you can pay to process the same large prefix repeatedly.
Prompt caching lets a provider reuse computation for a matching prompt prefix. The exact feature and pricing rules differ by provider and model. Some services apply caching automatically when requests share a sufficiently long prefix. Others require you to identify a cacheable section. Check the current rules in the Anthropic documentation and the OpenAI API pricing documentation, including minimum prefix sizes, cache duration, write charges and read charges.
The engineering lesson is simple: make the reusable part of the request stable and put it first. A useful request order is:
- System instructions that apply to every request.
- Static tool definitions and output schemas.
- Stable reference material used across the session or workload.
- Tenant-specific or session-specific context.
- The current user input.
Do not add a changing timestamp, request identifier or user-specific variable to the front of a prompt if it prevents the stable content after it from matching. Keep the cacheable prefix byte-for-byte consistent where the provider requires exact matching. Treat prompt construction as an interface with tests, not as a string assembled differently in every code path.
Caching is not automatically worthwhile. Work out the break-even point using the provider's current cache-write and cache-read prices. Compare the cost of writing or refreshing the cache plus the cost of subsequent reads with the cost of sending the same prefix uncached. The more often a prefix is reused within its cache lifetime, the stronger the case for caching. A one-off request with a large context may not benefit. A repeated agent workflow with the same tools and instructions may.
Instrument cache behaviour directly. Record input tokens, cached input tokens, cache writes, cache reads, cache hit rate and cost by model and feature. If the hit rate is low, inspect the prompt versions and ordering before concluding the provider feature is ineffective. A dynamic value in the wrong place can quietly defeat the design.
A cache is also a data boundary to review. Decide what content is eligible to persist, for how long and under what provider terms. Do not assume that a cache is equivalent to your own application store or that it has the retention characteristics you need. For regulated workloads, include the provider configuration, data path and cache behaviour in the architecture and risk review.
2. Route simple work to a smaller model, with a safe escalation path
Not every AI task needs the same level of reasoning. A model that can draft a complex answer or inspect code may be unnecessary for classifying a support request, extracting a date or labelling a document. Sending every request to the most capable model makes the expensive path the default, even when the task is routine.
Create a routing policy based on the task, not a vague claim that one model is better. For each feature, define the minimum capability needed: classification, structured extraction, summarisation, code generation or multi-step reasoning. Then test candidate models against representative inputs, including ambiguous and unusual cases. The OpenAI API pricing page provides current model pricing for its services. Compare that with the current pricing and capabilities of any other providers you use rather than relying on old price comparisons.
A common design has three tiers:
| Tier | Work that may fit | Control |
|---|---|---|
| Small or low-cost model | Classification, routing, simple extraction and short rewrites | Use only after evaluation shows acceptable accuracy |
| Mid-tier model | Standard question answering, summarisation and routine code assistance | Default for supported tasks with moderate complexity |
| High-capability model | Difficult reasoning, complex synthesis or high-impact decisions | Escalate when a task meets defined complexity or risk criteria |
A small language model can be a local model, a hosted smaller model or a low-cost model available through an API. Parameter count alone does not tell you whether a model will handle your task. Language, context length, structured-output support, latency, hosting cost and the consequence of an error all matter. Research such as the 2026 study on language model routing can inform your evaluation, but your own task distribution and quality bar should decide the production route.
Set explicit escalation rules. A router might send a request to a stronger model when the input is ambiguous, the required output fails validation, the task involves several dependent steps, or the first model's answer does not meet a defined quality check. Do not rely on a small model merely to announce its confidence. Confidence scores can be poorly calibrated. Validate the actual result against schemas, policy checks or task-specific tests.
For high-impact use cases, keep a human review step where required. A routing policy should not send a sensitive decision to a weaker model just because it is cheaper. The goal is to pay for the capability the task needs, not to make every task as cheap as possible.
Measure cost per successful task, not cost per call. If a cheaper model fails more often and triggers retries or human rework, its apparent saving may disappear. Compare accuracy, completion rate, retries, latency and total cost on the same evaluation set. Then set model routing rules in code or a gateway, version them and monitor changes after deployment.
3. Prune context before it reaches the model
Context is not free. Every irrelevant document chunk, unused JSON field, repeated conversation turn or raw HTML fragment adds input tokens. It can also distract the model from the useful information. Context pruning reduces both avoidable spend and the chance that important evidence gets buried.
Start at the source. If an internal API returns a large object, construct a small, typed payload containing only the fields needed for the task. Drop null fields, internal identifiers and duplicated values unless the model genuinely needs them. If your system retrieves web pages, remove navigation, styling, scripts and other boilerplate before storing or sending the content. A clean representation is easier to inspect and cheaper to process.
For retrieval-augmented generation, or RAG, avoid sending every vaguely related passage. Retrieve candidate chunks, rank them against the question and pass only the evidence that contributes to the answer. A reranker is a second-stage model or algorithm that sorts retrieved passages by relevance. It can improve selection when a basic vector search returns many loosely related results, but it adds its own runtime cost. Evaluate whether the reduced generation cost and improved answer quality justify it.
Do not select a similarity threshold by copying a number from a blog post. Similarity scores depend on the embedding model, data and query type. Build a labelled evaluation set and compare thresholds against missed evidence, irrelevant context and final answer quality. In some use cases, retrieving fewer chunks is safe. In others, a missing exception or qualification could make the answer wrong.
Conversation history is another source of gradual bloat. Summarise older turns into a compact state when the task allows it, while retaining the details needed for continuity. Keep the latest turns intact if they contain immediate instructions or references. Test summaries against tasks that depend on earlier details. A shorter conversation is not an improvement if it forgets a commitment, constraint or user preference.
Useful controls include:
- Set maximum input size by feature and reject or shorten requests that exceed it.
- Record token counts for retrieved content separately from system instructions and user input.
- Strip boilerplate at ingestion rather than repeating cleanup on every request.
- Deduplicate passages and facts before assembling context.
- Track answer quality when changing chunk size, retrieval count or summarisation rules.
The important metric is not simply tokens removed. Track whether the model still answers correctly, cites the right evidence and handles edge cases. Pruning is a quality-controlled transformation. It should have tests and an owner, just like a change to a database schema or API contract.
4. Use semantic caching for genuinely repeatable answers
Prompt caching and semantic caching solve different problems. Prompt caching reuses computation when a request has a matching prefix. Semantic caching checks whether a new question is sufficiently similar to a question the system has answered before, then may return the earlier answer. It can help when users phrase the same request differently, but it carries a greater risk of returning a stale or contextually wrong response.
A typical semantic cache stores an embedding of the question, relevant scope information and the answer. An embedding is a numerical representation of text used to find semantically similar items. On a new request, the system creates an embedding, searches for a close match and either returns a valid cached response or calls the model. The Redis guide to semantic caching describes this general pattern.
Do not treat similarity as proof that two questions deserve the same answer. The question What is the parental leave policy? may be close to How much leave can a contractor take? in vector space, but the distinction matters. A cache key should account for relevant context such as tenant, user permissions, product version, jurisdiction, language and source-document version. If the answer depends on live account data or a recent policy change, the cache needs a suitable invalidation rule or should not be used.
Start with low-risk, stable, repeated content. Examples may include public product guidance or common internal help questions where the source and answer do not vary by user. Keep high-impact advice, personalised account information and time-sensitive answers out of the cache unless you can prove that scope and freshness are handled correctly.
Set a conservative similarity threshold using a test set of both paraphrases and near-miss questions. Test whether the cache returns the right answer for the right tenant and refuses to reuse an answer when key details differ. Include adversarial cases where only one word changes the meaning. Monitor cache hits, cache misses, incorrect hits, answer freshness and the cost of embedding and storage. A high hit rate is not success if users receive the wrong response.
Use a time-to-live based on how quickly the underlying answer can change. Invalidate entries when the source material changes, and consider storing provenance so the system can explain which document or version supported a cached answer. The cache should be an optimisation layer with a clear bypass path, not a second source of truth.
5. Set per-tenant budgets, rate limits and concurrency caps
In a multi-tenant product, one customer's usage should not consume the capacity or margin intended for everyone else. A looping agent, faulty integration or unexpected batch can create a sharp rise in calls. Provider rate limits protect the provider's service, but they do not enforce your commercial plan or your internal gross margin target.
Put usage controls in a gateway or shared service where every model call passes through them. The MLflow guidance on provider quota management covers the need to manage provider quotas in LLM applications. The same control plane should also apply your own customer and feature limits.
Use several limits together:
- Request rate: requests allowed over a time period, to protect the application and provider quotas.
- Token rate: estimated or actual tokens allowed over a rolling period, to prevent a burst of long prompts from bypassing a request-count limit.
- Concurrency: the number of requests or agent runs that can be active at once for a tenant.
- Spend budget: the maximum internal model cost allowed in a billing period or for a particular workflow.
- Task limit: maximum steps, retries, tool calls or elapsed time for an agent run.
Use a shared state store for enforcement across application instances. A token bucket is a common approach: tokens accumulate up to a limit and each request consumes capacity. A sliding window can give a more precise view of usage over time. Choose based on the behaviour you need, and test concurrent requests so two application instances cannot both approve spend that crosses the same tenant's cap.
Budget against gross margin, not just the provider's advertised plan. For example, if a subscription is priced at $200 per month and your target gross margin is 75%, the maximum total cost of goods sold would be $50 per month. That $50 is not automatically the model budget. Hosting, storage, support and other variable costs also use the COGS allowance. Define a separate AI allowance after accounting for those costs.
Make limits useful to customers and support staff. At a warning threshold, alert the account owner or administrator and consider moving eligible tasks to a lower-cost model. At a hard limit, stop new non-essential work, queue it, or return a clear response that explains when service can resume. Do not silently produce lower-quality results without telling the customer. For internal systems, alert the on-call team and halt the affected workflow safely.
A limit must also stop runaway agents. Set a maximum number of steps, tool calls, retries and total tokens per run. Add idempotency controls so a retried event does not start duplicate work. A circuit breaker can stop repeated calls when an upstream provider is failing. Log the tenant, feature, model, tokens, estimated cost and reason for denial, while protecting sensitive prompt content.
Review the controls against your contracts and service commitments. If customers buy a defined usage allowance, make sure the measurement and overage policy are clear. If you serve regulated organisations, include usage spikes, provider dependency and interruption behaviour in the operational risk design. Our work on AI agents and automation includes designing bounded workflows that can be observed and stopped when they exceed their intended limits.
6. Move non-urgent work to batch processing
Many AI jobs do not need an answer while a person waits. Nightly document extraction, retrospective classification, evaluation runs and bulk summarisation can often run asynchronously. Sending these jobs through a real-time endpoint pays for an interactive service pattern when the business does not need interactive latency.
Separate the synchronous path from the background queue. A user-facing request may need a response immediately. A nightly job can be queued, processed in batches and reported when complete. Make the distinction explicit in the product and workflow design, including how the user sees progress, failure and retry status.
Provider batch offerings change, including eligible models, price reductions, processing windows and file formats. Check the current terms in the OpenAI API pricing documentation and the relevant provider documentation before assuming a discount or completion time. A discount only helps if the workload qualifies and the asynchronous turnaround is acceptable.
Batch jobs need production controls too. Assign each task a stable identifier, store inputs and outputs, record model and prompt versions, and make processing idempotent. If a job fails partway through, retry only the failed items rather than resubmitting everything. Validate outputs before using them in downstream systems. If a batch modifies records or triggers customer communications, include review and approval steps suited to the impact.
Batch processing may also combine well with prompt caching when many requests share a stable prefix. Do not assume that discounts stack or that a provider applies them in a particular order. Verify the actual billing rules and test the resulting invoice data. Track batch cost per completed item and compare it with the equivalent real-time workflow.
A practical first candidate is a workload with a known input set, repeatable instructions and no need for immediate results. Run it on a sample, inspect failure modes, then compare end-to-end cost and completion time. The aim is to select the cheapest service pattern that meets the deadline, not to force all AI work into a single endpoint.
How do you measure whether the six patterns protect margin?
Start with a baseline for each AI feature. Record requests, input and output tokens, model, retries, cache activity, latency and estimated provider cost. Join that data to the product's tenant and workflow identifiers, subject to privacy controls. Without this breakdown, the invoice tells you what you spent but not which feature caused the spend or whether the feature created value.
The useful unit is usually cost per successful task, with a clear definition of success. For a support answer, that might mean the answer passed required checks and did not need a second model call or human correction. For document extraction, it might mean all required fields passed validation. Track the cost of failures and retries as well as successful completions.
Here is a transparent baseline calculation using the scenario and rates in the research brief. It is illustrative only. Validate model prices, currency, taxes and provider terms before using it in a business case.
| Input | Assumption | Calculation | Monthly cost |
|---|---|---|---|
| Interactions | 500,000 | Given scenario | Not a cost |
| Input tokens | 4,000 per interaction | 500,000 x 4,000 = 2,000 million tokens | At $3.00 per million: $6,000 USD |
| Output tokens | 500 per interaction | 500,000 x 500 = 250 million tokens | At $15.00 per million: $3,750 USD |
| Total model spend | Input plus output | $6,000 + $3,750 | $9,750 USD |
The rates above are the scenario's stated rates for Claude 3.5 Sonnet. Because model pricing changes, check current provider pricing before making a decision. The calculation excludes embeddings, storage, retries, gateway infrastructure, taxes, discounts and human review. It also assumes every interaction uses exactly the stated token volumes. Real workloads vary.
Use the baseline to prioritise experiments. For example, inspect whether a stable prompt prefix is repeated often enough to test caching. Measure how much of the input consists of retrieved content or raw structured data. Identify which task categories could pass an evaluation on a cheaper model. Find tenants or workflows that account for a disproportionate share of usage. Then test one change at a time against both quality and cost.
A useful operating dashboard shows:
- Cost per successful task by feature, tenant and model.
- Input and output tokens per successful task.
- Cache hit rate and cached tokens, where applicable.
- Model routing distribution and escalation rate.
- Retry, timeout and tool-call rates for agents.
- Usage against tenant budgets and provider limits.
- Quality checks, user corrections and human-review rates.
Do not optimise against token volume alone. A longer answer may be justified if it resolves the task without a second interaction. A more capable model may be cheaper overall if it avoids retries and manual corrections. Review cost with latency, quality and customer impact together.
Wrap-up: make cost a runtime control
The six patterns tackle different sources of waste. Prompt caching reduces repeated computation for stable prefixes. Model routing matches capability to task. Context pruning removes unnecessary input. Semantic caching can reuse answers when the question and its context truly match. Tenant quotas limit exposure. Batch processing avoids paying for interactive service when work can wait.
Apply them in that order only if the evidence supports it. First instrument the workload, then choose the largest controllable cost driver. Add quality tests and safe fallbacks before changing model or context behaviour. Put tenant and agent limits in place early because they protect the product even before optimisation work is complete.
For teams building or revising an AI system, PADISO's platform engineering service can help connect gateway design, observability and application architecture. The first step is to map model calls to features and tenants, then establish a cost and quality baseline. If you want to assess your broader operating readiness, take the AI readiness test.