FORTILABS AI LAB • AI INFRASTRUCTURE

Enterprise LLM costs rarely come from one expensive API call. They accumulate across repeated questions, oversized system prompts, unnecessary context, premium models handling routine tasks, and generated output that is longer than users need. The solution is not simply to switch to a cheaper model. It is to build an inference architecture that avoids redundant work, sends less unnecessary context, and selects the right model for each request.

THE SHORT ANSWER

Reduce LLM API spending by combining three complementary controls: semantic caching for reusable answers, prompt compression for unnecessary input tokens, and model routing for requests that do not need a premium model. Add provider-side prompt caching for repeated exact prefixes. Measure actual cost per accepted result, not just tokens saved or cache-hit rate. A 60% reduction is a possible target in workloads with substantial redundancy and model-tier flexibility, not a guaranteed outcome.

Editorial note: This article presents architecture patterns, illustrative calculations, and implementation guidance. The savings examples are hypothetical, not measured FortiLabs benchmarks or claims about a particular enterprise deployment. Model prices, caching rules, and provider capabilities change; verify current documentation and pricing before implementation.

1. Why enterprise LLM bills grow

A proof of concept might process a few hundred prompts per day. An enterprise deployment can process thousands or millions of requests across support, internal search, document processing, coding assistance, analytics, and workflow automation.

At that scale, small inefficiencies become recurring infrastructure costs.

Five common sources of waste

Cost driver Typical behavior Potential optimization
Repeated questions Different users ask substantially similar questions and trigger fresh inference. Semantic caching with strict eligibility rules.
Repeated context Large system instructions, tool definitions, and reference material are sent repeatedly. Stable prompt prefixes and provider-side prompt caching.
Oversized prompts Entire documents, chat histories, and retrieved passages are included when only a fraction is relevant. Retrieval refinement, summarization, and prompt compression.
Premium-model overuse Simple extraction, classification, and formatting tasks use the same model as complex reasoning. Task-aware model routing.
Unnecessary output Responses contain long explanations or repeated information users do not need. Output limits, structured responses, and task-specific verbosity.

These inefficiencies are related, but they are not interchangeable. A semantic cache avoids an inference call when a safe reusable answer exists. Prompt caching reduces the cost of processing a repeated exact prefix. Compression reduces the amount of input sent. Model routing changes which model processes the request.

Applying all four indiscriminately can create new problems. A cache can return stale information. Compression can remove critical details. A cheaper model can make more mistakes. A prompt cache can have a poor hit rate if the prompt structure changes on every request.

The objective is therefore not to minimize token count at any cost. It is to minimize the cost of producing an acceptable, correct result.

2. Understand the real LLM cost model

Before optimizing, separate the components of the bill. A simplified API cost equation is:

Request cost =
    (uncached input tokens × input rate)
  + (cached input tokens × cached input rate)
  + (output tokens × output rate)
  + tool and auxiliary charges

Actual billing depends on the provider, model, API features, and pricing tier. Some services also charge separately for tools, image processing, audio, storage, or other capabilities.

Input and output tokens have different economics

Input and output token rates are often different. A long generated answer can be expensive even when the prompt is relatively small. Conversely, a document-analysis application may spend most of its budget processing large input contexts.

For this reason, measure at least:

  • Uncached input tokens.
  • Cached input tokens.
  • Output tokens.
  • Model and provider used.
  • Tool and auxiliary charges.
  • Cost per request and cost per successful task.

Example: a hypothetical API workload

Assume an application processes 1,000,000 requests per month. For illustration, suppose each request uses 2,000 input tokens and 500 output tokens, with these hypothetical rates:

  • Input: $2.00 per million tokens.
  • Output: $8.00 per million tokens.

Monthly usage would be:

Input tokens:
1,000,000 × 2,000 = 2,000,000,000

Output tokens:
1,000,000 × 500 = 500,000,000

Input cost:
2,000 × $2.00 = $4,000

Output cost:
500 × $8.00 = $4,000

Total:
$8,000 per month

This simplified example excludes cache pricing, tools, taxes, infrastructure, and provider-specific billing details. Its purpose is to show how input and output costs can each contribute materially to the bill.

Start with a cost baseline

Do not begin by deploying a cache or changing models. First identify which request categories consume the most money, how much context they send, how often they repeat, and which tasks actually require premium reasoning.

Use cost per accepted result

Suppose a cheaper model costs 70% less per call but requires more retries and produces more incorrect results. Its apparent API savings may disappear.

A better metric is:

Cost per accepted result =
    Total inference and optimization cost
    --------------------------------------
    Number of results passing quality checks

Include the costs of cache infrastructure, embedding generation, routing classifiers, retries, human review, and downstream correction where those costs are material.

3. The three-layer optimization architecture

A robust optimization system should sit between the application and model providers. It should decide whether a request can be answered from a safe cache, whether its context can be reduced, and which model is appropriate.

Application request Authenticated user, tenant, task, context and response requirements
Request policy and eligibility checks Privacy classification, freshness requirements, task type and cost budget
Semantic cache Safe reusable answers
Prompt optimizer Context reduction
Model router Cost-quality selection
Provider prompt cache Reuse eligible exact prompt prefixes where supported
Model inference and validation Schema checks, quality evaluation and policy enforcement
Response and telemetry Return result, update eligible cache and record actual cost

The three optimization layers operate at different points:

  1. Semantic caching can bypass model inference for eligible requests.
  2. Prompt compression reduces the context that reaches the model.
  3. Model routing chooses a suitable model for the remaining work.

Provider-side prompt caching is an additional optimization inside the model-inference path. It is not the same thing as storing and returning an earlier answer.

Why ordering matters

Apply inexpensive request validation and privacy checks before cache lookup. If the request is not eligible for reuse, continue to context preparation and model selection.

After inference, validate the response before storing it. Never let an unvalidated model response automatically become a reusable answer for future users.

4. Semantic caching: avoid repeated inference

Traditional caching works best when requests are identical or share a stable key. But users rarely phrase the same question in exactly the same way.

Consider these requests:

  • How do I reset my company password?
  • What’s the process for changing my work account password?
  • I forgot my login password. How can I create a new one?

The wording differs, but the underlying intent may be the same. A semantic cache uses embeddings or another similarity representation to identify requests that are sufficiently related to previously processed requests.

How semantic caching works

  1. Normalize the incoming request and extract relevant metadata.
  2. Generate an embedding or semantic representation.
  3. Search eligible cache entries using similarity and metadata filters.
  4. Check whether the candidate answer is valid for the current user, tenant, context, and freshness requirements.
  5. Return the cached answer only if the match passes the configured acceptance policy.
  6. Otherwise, continue to normal model inference.
  7. Validate the new answer and store it only if it is safe and reusable.

Semantic similarity is not semantic equivalence

This is the most important limitation.

Two questions can have similar embeddings while requiring different answers. For example:

  • What is the refund policy for a standard customer?
  • What is the refund policy for an enterprise customer?

The questions are closely related, but the answer may depend on subscription level, contract terms, region, purchase date, or account status.

A similarity score alone cannot establish that returning an earlier answer is correct.

Build a cache key with more than the question

A useful semantic cache entry should include the dimensions that determine whether an answer can be reused.

{
  "tenant_id": "tenant-042",
  "knowledge_version": "support-kb-2026-11",
  "task_type": "general_policy_question",
  "locale": "en",
  "permission_scope": "public_support",
  "query_embedding": "...",
  "answer": "...",
  "created_at": "...",
  "expires_at": "...",
  "validation_status": "approved"
}

This is an illustrative data structure. The exact fields depend on the application and its data boundaries.

At lookup time, filter candidates by tenant, authorization scope, task category, locale, knowledge version, and freshness before evaluating semantic similarity.

Use thresholds based on risk

A single global similarity threshold is rarely appropriate.

For example:

Request category Cache policy Reason
Stable public FAQ Potentially cacheable with validated intent matching. Answers may remain valid across many users.
Internal documentation Cache within tenant and permission scope. Access and document versions matter.
Account-specific support Usually bypass shared semantic caching. Answers depend on live user records.
Live pricing or availability Require fresh source data or bypass answer cache. Stale answers can cause financial or operational errors.
Medical, legal, or high-impact decisions Use strict policy; generally avoid automatic answer reuse. Small contextual differences can materially change the answer.

Semantic cache architecture

A practical implementation often combines a vector index with a conventional metadata store:

  • Embedding model: converts eligible queries into vectors.
  • Vector index: retrieves semantically similar entries.
  • Metadata filters: enforce tenant, task, version, and access constraints.
  • Answer store: stores validated responses and supporting metadata.
  • Policy layer: decides whether a candidate can be reused.
  • Expiration and invalidation: removes or disables stale entries.

For a small application, a dedicated vector database may be unnecessary. A database with vector-search capabilities or a hybrid retrieval system may be sufficient. Select infrastructure based on query volume, latency requirements, filtering needs, and operational complexity.

Do not cache everything

Semantic caching is most useful when requests repeat, answers remain stable, and the system can establish that the current context matches the original answer’s scope.

It is a poor fit for requests involving unique user data, rapidly changing facts, personalized decisions, or actions that must be executed independently for each request.

5. Provider-side prompt caching

Semantic caching and provider prompt caching solve different problems.

Semantic caching returns a previously stored answer when an eligible new request is sufficiently equivalent. Provider-side prompt caching reuses processing for an identical or matching prompt prefix while still generating a new answer.

Why prompt structure matters

Many enterprise requests contain a large amount of repeated material:

  • System and developer instructions.
  • Tool definitions.
  • Formatting requirements.
  • Stable policy documents.
  • Shared reference material.
  • Earlier conversation context.

If the provider supports prompt caching, repeated eligible prefixes may receive a lower input-token rate and reduced prompt-processing latency.

The key requirement is usually stable, reusable prompt structure. If dynamic content is inserted before the shared material, the common prefix may disappear.

Structure prompts from stable to dynamic

A useful ordering is:

[Stable system instructions]
[Stable tool definitions]
[Stable policy and reference material]
[Session-specific context]
[Current user request]

Keep frequently reused content at the beginning. Put changing content later. Avoid rebuilding identical instructions with different whitespace, ordering, timestamps, or irrelevant request identifiers.

Provider-specific behavior must be verified

Prompt caching is not one universal protocol. Providers differ in supported models, minimum cacheable prefixes, retention behavior, cache-write pricing, and explicit breakpoint controls.

For example, OpenAI documents automatic and explicit prompt caching, usage fields, and model-dependent cache retention in its Prompt Caching guide. Its API pricing page describes model-specific cached-input and cache-write rates.

Anthropic documents its own cache-control approach, including cache breakpoints and retention options, in its Prompt Caching documentation.

Google’s Gemini API also documents context caching for reusable context. See Gemini context caching.

Calculate the economics before enabling long retention

Some providers charge more to write or store a cached prefix than to process ordinary input. The benefit comes from repeated reads at a reduced rate.

Use the provider’s actual pricing to calculate the break-even point:

Cost without caching =
    number_of_requests × prefix_tokens × input_rate

Cost with caching =
    cache_write_cost
  + cached_reads_cost
  + any uncached prefix processing

Longer retention may improve reuse but can increase write cost or raise data-retention considerations. Measure the actual usage fields returned by the provider instead of assuming that a configured cache automatically produces savings.

Do not confuse a cache hit with a saved API call

Provider-side prompt caching still generates a new model response. It reduces the cost of eligible input processing; it does not eliminate output generation or guarantee a particular percentage reduction in total request cost.

6. Prompt compression: send less context

Enterprise applications often send too much information to a model. A request may include an entire conversation, multiple retrieved documents, repeated policy text, and tool outputs even when only a small portion is relevant.

Prompt compression reduces the amount of input without removing information required for the task.

Start with context selection, not aggressive compression

The safest optimization is often to avoid sending irrelevant material in the first place.

  1. Retrieve only documents relevant to the current question.
  2. Remove duplicate passages.
  3. Limit conversation history to relevant turns.
  4. Summarize completed tool interactions.
  5. Keep stable instructions outside repeated dynamic content.
  6. Apply token-aware compression only after these steps.

Sending fewer irrelevant documents is generally easier to validate than aggressively rewriting a document that contains critical facts.

Four practical compression techniques

1. Remove redundant instructions

System prompts often accumulate duplicate rules, repeated examples, and outdated requirements. Review them for conflicting or unnecessary content. Keep the authoritative version concise and version-controlled.

2. Summarize conversation history

For long-running sessions, preserve decisions, constraints, unresolved questions, and relevant facts in a structured summary rather than repeatedly sending every previous message.

Do not discard exact values, identifiers, legal wording, or user-provided constraints that the next stage needs. A summary should preserve task-critical information, not simply reduce length.

3. Compress retrieved context

Use query-aware extraction to retain the passages that directly support the current task. Preserve source identifiers and enough surrounding context to avoid changing the meaning of a statement.

4. Use token-aware prompt compression

Research systems such as LLMLingua explore methods for identifying and removing less useful prompt tokens. Microsoft Research describes the LLMLingua family and its experiments in its LLMLingua research project.

These techniques can be useful for long-context workloads, but reported compression ratios and benchmark improvements are not universal production guarantees. Test compression on the actual model, data, and task distribution.

Preserve structure and meaning

A compressed prompt should retain the information that controls the answer:

  • Entity names and relationships.
  • Numbers, units, dates, and thresholds.
  • Negations and exceptions.
  • Conditions and dependencies.
  • Source attribution and evidence boundaries.
  • Permissions and safety constraints.
  • Output schema and required fields.

For example, compressing “Users with an active enterprise contract are eligible, except accounts suspended for non-payment” into “Enterprise users are eligible” changes the policy. The shorter version is not an acceptable compression.

Compression should be task-aware

Different tasks need different levels of fidelity. A document classification task may tolerate a compact representation. Legal clause analysis may require exact wording. Code review may require the relevant source lines and surrounding control flow rather than a generated summary.

Build separate compression policies for task categories. Do not apply a single aggressive compression ratio to every request.

7. Model routing: match cost to task complexity

Many applications use one flagship model for every request. This is convenient, but it can be unnecessarily expensive.

Extracting a date, classifying a support ticket, rewriting a short paragraph, and reasoning through a complex technical problem do not necessarily require the same model capabilities.

Model routing selects an appropriate model based on task requirements, expected quality, latency, cost, and policy constraints.

A task-aware routing policy

Task type Initial route Escalation condition
Simple classification Small, low-cost model. Low confidence or schema failure.
Entity extraction Small model with structured output. Ambiguous or complex source material.
Routine summarization Efficient general-purpose model. High-stakes or unusually long context.
Complex reasoning Capable reasoning model. Specialized tools or human review required.
High-impact decisions Policy-approved model and verification path. Mandatory human review where required.

This is a routing policy template, not a ranking of specific commercial models. Test the actual candidates against your own workload before assigning them to production tiers.

How a router makes its decision

A routing layer can use several signals:

  • Task category and requested output format.
  • Input length and context complexity.
  • Required reasoning depth.
  • Quality requirements and risk classification.
  • Latency service-level objectives.
  • Model availability and current provider health.
  • Historical evaluation results for similar requests.

Start with a deterministic rules-based router where task categories are predictable. Add a learned classifier or routing model only when the extra complexity improves cost-quality performance.

Confidence-based escalation

A small model can handle routine requests and escalate difficult ones. However, model-generated confidence is not automatically calibrated or trustworthy.

Use measurable escalation signals, such as:

  • Schema validation failure.
  • Missing required fields.
  • Unresolved ambiguity.
  • Conflict between extracted facts.
  • Failure to satisfy explicit acceptance criteria.
  • Evaluation score below a validated threshold.

When a request is escalated, send the relevant original context and validation feedback. Do not blindly send an incomplete or distorted summary to the more capable model.

Use routing research as a starting point

Research such as RouteLLM explores cost-effective routing between models with different capabilities. Its results illustrate how a routing policy can trade off quality and cost, but the right thresholds depend on the evaluation data and model pair.

See the RouteLLM project and its associated research materials. Treat published benchmark results as research evidence, not a guarantee for a different enterprise workload.

Do not route only by the cheapest price

A cheaper model may have lower first-pass accuracy, require more retries, or fail to follow a structured output contract. Compare total cost per accepted result, not price per million tokens in isolation.

8. A worked 60% cost-reduction scenario

Can the three techniques reduce a monthly API bill by 60%? They can in a workload with enough repeated requests, reusable prompt prefixes, large reducible contexts, and tasks that can move to lower-cost models without unacceptable quality loss.

The following scenario demonstrates how the arithmetic can work. It is entirely illustrative and does not represent measured results from FortiLabs or a real customer.

Starting baseline

Assume a workload costs $100,000 per month, broken down as follows:

Cost category Monthly cost Share
Input tokens$55,00055%
Output tokens$35,00035%
Other API and tool charges$10,00010%
Total$100,000100%

Apply the optimizations sequentially

Assume the workload has a meaningful volume of eligible repeated questions, repeated prompt prefixes, and routine tasks that can safely use less expensive models.

Optimization Illustrative effect Remaining monthly cost
Baseline No optimization. $100,000
Semantic caching Eligible requests avoid repeated inference. $75,000
Prompt compression and prefix caching Reduces the cost of remaining input processing. $62,000
Model routing Routine work moves to lower-cost models. $40,000

In this scenario:

Baseline monthly cost:  $100,000
Optimized monthly cost:  $40,000

Monthly savings:         $60,000

Cost reduction:
($100,000 - $40,000) / $100,000 × 100

                         = 60%

The percentages are not additive. Each optimization acts on the remaining workload, and the exact effect depends on how the techniques overlap.

Account for optimization overhead

The $40,000 figure represents the modeled inference and API cost after optimization. A real deployment also needs to account for:

  • Embedding generation and vector search.
  • Cache storage and invalidation.
  • Routing and evaluation infrastructure.
  • Additional validation and retry calls.
  • Engineering, monitoring, and operational costs.

If these add $4,000 per month, the all-in cost becomes $44,000 and the net reduction is 56%, not 60%.

This is why enterprise teams should report both inference-only savings and all-in operating savings.

The 60% target is workload-dependent

An application with mostly unique, short, real-time requests may see much smaller savings. A support or document workflow with repeated questions, long stable context, and many routine tasks may have substantially more optimization potential.

9. Implementation architecture and example

The optimization layer should be implemented as a controlled service rather than scattered across individual application endpoints.

Recommended request lifecycle

  1. Authenticate the caller and resolve tenant scope.
  2. Classify the request and determine whether it is cache eligible.
  3. Check an exact-result cache where applicable.
  4. Check the semantic cache using metadata filters and a risk-appropriate threshold.
  5. Prepare the prompt and remove irrelevant context.
  6. Use provider prompt caching for stable reusable prefixes where supported.
  7. Route the request to a model that meets the task’s quality and latency requirements.
  8. Validate the response against schema and quality checks.
  9. Escalate or retry only under an explicit policy.
  10. Store eligible validated results and record actual usage and cost.

Framework-neutral Python routing example

The following simplified example shows the control flow. It intentionally leaves provider SDK calls, vector search, authentication, and persistent storage behind interfaces rather than pretending they can be implemented safely with a few lines of demonstration code.

from dataclasses import dataclass
from enum import StrEnum


class TaskType(StrEnum):
    CLASSIFICATION = "classification"
    EXTRACTION = "extraction"
    SUMMARIZATION = "summarization"
    COMPLEX_REASONING = "complex_reasoning"


@dataclass
class Request:
    tenant_id: str
    task_type: TaskType
    prompt: str
    sensitive: bool = False
    requires_fresh_data: bool = False


@dataclass
class Route:
    model: str
    max_output_tokens: int
    allow_semantic_cache: bool


def select_route(request: Request) -> Route:
    if request.task_type == TaskType.CLASSIFICATION:
        return Route(
            model="small-model",
            max_output_tokens=300,
            allow_semantic_cache=True,
        )

    if request.task_type == TaskType.EXTRACTION:
        return Route(
            model="small-model",
            max_output_tokens=800,
            allow_semantic_cache=False,
        )

    if request.task_type == TaskType.SUMMARIZATION:
        return Route(
            model="efficient-general-model",
            max_output_tokens=1200,
            allow_semantic_cache=False,
        )

    return Route(
        model="reasoning-model",
        max_output_tokens=3000,
        allow_semantic_cache=False,
    )


def semantic_cache_eligible(request: Request) -> bool:
    return (
        not request.sensitive
        and not request.requires_fresh_data
        and request.task_type == TaskType.CLASSIFICATION
    )


def process_request(request: Request):
    # 1. Authenticate and authorize before this function.

    # 2. Check cache only when policy permits it.
    if semantic_cache_eligible(request):
        cached = semantic_cache_lookup(
            tenant_id=request.tenant_id,
            task_type=request.task_type,
            query=request.prompt,
        )

        if cached is not None:
            return cached

    # 3. Select a model based on task requirements.
    route = select_route(request)

    # 4. Reduce irrelevant context before inference.
    optimized_prompt = prepare_prompt(request.prompt)

    # 5. Invoke the selected provider model.
    response = call_model(
        model=route.model,
        prompt=optimized_prompt,
        max_output_tokens=route.max_output_tokens,
    )

    # 6. Validate before accepting or caching.
    validated = validate_response(
        response=response,
        task_type=request.task_type,
    )

    if not validated:
        raise ValueError("Model response failed validation")

    # 7. Cache only eligible, validated, reusable results.
    if route.allow_semantic_cache:
        semantic_cache_store(
            tenant_id=request.tenant_id,
            task_type=request.task_type,
            query=request.prompt,
            response=response,
        )

    # 8. Record token usage, latency and actual cost.
    record_usage(request, route, response)

    return response

The function names such as semantic_cache_lookup, call_model, and validate_response represent application services that must be implemented. They are not built-in Python functions.

Production considerations

  • Use a durable cache store with expiration and invalidation.
  • Enforce tenant and permission filters at the data layer.
  • Version prompts, routing policies, and cache entries.
  • Keep provider credentials in a secure secret manager.
  • Set explicit timeouts and retry budgets.
  • Record provider usage fields instead of estimating all token counts.
  • Use fallback routes when a provider is unavailable, but preserve quality requirements.
  • Run shadow evaluations before allowing a new model to handle production traffic.

10. Security, privacy, and correctness risks

Cost optimization introduces new data paths. A semantic cache can expose information across tenants if its filters are wrong. A compression service can send sensitive documents to an additional model. A router can move requests to a provider with different retention or regional-processing terms.

These risks must be part of the architecture from the beginning.

Cross-tenant cache leakage

Never assume that a semantically similar request can safely reuse another customer’s answer. Enforce tenant and authorization boundaries before candidate retrieval and again before returning a result.

For sensitive systems, use separate namespaces or physical stores where required by the security model. Do not rely on a tenant ID added after a global nearest-neighbor search.

Stale information

Answers that depend on pricing, inventory, account state, policy changes, or current external facts need freshness controls. Use short time-to-live values, version-aware invalidation, or no answer caching at all.

Prompt injection and untrusted content

Cached answers and compressed documents may contain instructions or text that originated from untrusted sources. Treat retrieved material as data, not authority. Preserve source boundaries and do not let compressed content override system policies or tool permissions.

Provider and regional boundaries

Routing requests across providers can change where data is processed, how long it is retained, and which contractual controls apply. Maintain an approved provider and model registry that includes:

  • Data-processing terms.
  • Regional availability and residency requirements.
  • Retention and training policies.
  • Supported security controls.
  • Approved task and data classifications.
  • Model version and deprecation information.

Quality regression

Compression and routing can silently reduce answer quality. Keep a representative evaluation set and compare factual accuracy, task completion, structured-output validity, and policy compliance before expanding traffic.

For high-impact tasks, use human review or independent verification where appropriate. A lower token bill is not a successful optimization if it creates more downstream errors.

11. Measuring savings without fooling yourself

Cost dashboards should distinguish between gross token savings, reduced provider charges, and net business savings.

Measure each optimization independently

Technique Core metric Quality or risk metric
Semantic caching Eligible cache-hit rate and avoided inference cost. Wrong-answer reuse, stale-result rate, and cache invalidation failures.
Provider prompt caching Cached input tokens and actual cached-input charges. Cache misses, write overhead, and latency.
Prompt compression Input tokens removed and net input cost reduced. Task accuracy, evidence retention, and schema validity.
Model routing Spend by model tier and cost per accepted result. Quality regression, escalation rate, and retries.

Track the right metrics

  • Cost per request: total provider charges divided by request count.
  • Cost per accepted result: total relevant costs divided by successfully accepted results.
  • Semantic cache hit rate: eligible requests served from semantic cache divided by eligible lookup requests.
  • Provider cache-hit ratio: cached input tokens divided by total input tokens, using provider usage definitions.
  • Compression ratio: tokens after compression divided by tokens before compression.
  • Routing distribution: percentage of requests handled by each model tier.
  • Escalation rate: percentage of requests moved to a more capable model or human review.
  • Quality pass rate: percentage of results passing defined evaluation criteria.
  • Latency: median and tail latency, including cache lookup and routing overhead.

Use controlled experiments

Deploy optimizations gradually. Compare a baseline cohort with an optimized cohort using similar request types, traffic volumes, and time windows.

For model routing, run shadow evaluations or a controlled traffic split. For compression, compare original and compressed prompts on a representative test set. For semantic caching, manually inspect false-positive matches and measure whether reused answers remain correct.

Do not compare a quiet week with a high-traffic week and attribute every difference to the optimization. Account for workload mix, seasonality, provider price changes, and changes in output length.

Calculate net savings

Net savings percentage =
    (Baseline all-in cost - Optimized all-in cost)
    ---------------------------------------------- × 100
                 Baseline all-in cost

Include API charges, cache infrastructure, embeddings, evaluation, additional retries, and other material operating expenses. Keep one-time engineering investment separate from recurring operating savings, but include it in a payback analysis.

12. A practical enterprise rollout plan

Do not introduce semantic caching, compression, and model routing in one uncontrolled release. Implement them in stages so each change can be evaluated and rolled back independently.

Phase 1: establish the baseline

  • Collect token and cost telemetry by task category.
  • Identify the highest-cost endpoints and workflows.
  • Measure request repetition and prompt-prefix reuse.
  • Build a representative quality evaluation set.
  • Document data classifications and provider constraints.

Phase 2: optimize prompt structure

  • Remove duplicate system instructions.
  • Move stable content before dynamic content.
  • Enable supported provider prompt caching.
  • Inspect cache usage fields and real billing effects.
  • Reduce irrelevant retrieval and conversation history.

Phase 3: introduce semantic caching

  • Start with stable, low-risk request categories.
  • Apply tenant, permission, and knowledge-version filters.
  • Set conservative similarity thresholds.
  • Use expiration and invalidation policies.
  • Review false-positive matches before expanding coverage.

Phase 4: introduce model routing

  • Benchmark approved models on real tasks.
  • Start with deterministic routing rules.
  • Use a controlled traffic split or shadow evaluation.
  • Add explicit escalation conditions.
  • Monitor quality, latency, and cost per accepted result.

Phase 5: optimize and govern continuously

  • Review model pricing and availability changes.
  • Re-evaluate cache thresholds and expiration policies.
  • Test new prompt and compression versions.
  • Audit provider and data-residency requirements.
  • Track all-in savings and quality regressions.

Every optimization should have an owner, a measurable objective, a rollback mechanism, and a documented acceptance criterion.

13. Production checklist

COST VISIBILITY

  • Input, cached input, and output usage are measured separately.
  • Costs are grouped by workflow, tenant, model, and provider.
  • Cost per accepted result is tracked.

SEMANTIC CACHING

  • Only eligible request categories can use answer caching.
  • Tenant and permission filters apply before retrieval.
  • Similarity thresholds are evaluated by task risk.
  • Freshness, expiration, and invalidation are implemented.
  • Cached responses pass validation before storage.

PROMPT OPTIMIZATION

  • Stable prompt prefixes are kept consistent.
  • Dynamic content appears after reusable context.
  • Provider caching behavior and write costs are measured.
  • Compression preserves critical facts and constraints.
  • Prompt changes are version-controlled.

MODEL ROUTING

  • Models are benchmarked on representative enterprise tasks.
  • Routing considers quality, latency, risk, and cost.
  • Escalation conditions are explicit and tested.
  • Provider outages and fallback behavior are handled.

SECURITY AND GOVERNANCE

  • Cache isolation and data boundaries are enforced.
  • Provider retention and residency terms are reviewed.
  • Sensitive requests bypass inappropriate caching.
  • Logs and cached data follow retention policies.
  • Quality regressions have monitoring and rollback paths.

14. Frequently asked questions

Can enterprises really reduce LLM API costs by 60%?

It is possible for workloads with substantial repeated requests, large reusable prompt prefixes, reducible context, and many tasks that can use less expensive models. It is not a universal guarantee. Measure the workload and calculate net savings after infrastructure and quality costs.

What is the difference between semantic caching and prompt caching?

Semantic caching stores and reuses previously validated answers for sufficiently similar eligible requests. Provider-side prompt caching reuses processing for a matching prompt prefix while the model still generates a new response.

Does semantic caching eliminate LLM API calls?

For eligible cache hits, it can avoid the model inference call needed to produce the cached answer. However, the system may still incur embedding, vector-search, storage, and validation costs.

Does prompt compression reduce answer quality?

It can if important facts, exceptions, relationships, or instructions are removed. Use task-aware compression, preserve source context, and evaluate compressed prompts against the original on representative data.

Should every request use the cheapest available model?

No. Model selection should reflect task complexity, quality requirements, latency, and risk. A cheap model that frequently fails or requires expensive correction can cost more overall.

Should sensitive enterprise requests be semantically cached?

Only when the application can prove that reuse is permitted and that the cached answer is valid for the same authorization and data scope. Account-specific, confidential, or high-impact requests often require bypassing shared semantic answer caches.

Which optimization should be implemented first?

Start with cost visibility and prompt-structure improvements. They are usually easier to measure and can improve provider prompt-cache reuse. Then introduce semantic caching for suitable repetitive tasks and model routing after benchmarking candidate models.

How do you know whether an optimization is actually saving money?

Compare all-in costs across controlled, comparable workloads. Include embeddings, cache infrastructure, retries, evaluation, and human review. Track quality and cost per accepted result alongside token usage.

Conclusion: optimize the inference path, not just the model price

Enterprise LLM cost optimization is an architectural problem. Changing to a cheaper model may reduce the price of one request, but it does not eliminate repeated work, oversized context, poor prompt structure, or unnecessary premium inference.

Semantic caching avoids recomputing eligible answers. Provider-side prompt caching reduces the cost of processing reusable prefixes. Prompt compression removes unnecessary context. Model routing sends each task to a model that meets its actual requirements.

The strongest systems combine these techniques with tenant isolation, freshness controls, quality evaluation, and cost telemetry. They also preserve an escalation path when a cheaper or cached response is not good enough.

The goal is not the fewest tokens or the cheapest model. It is the lowest sustainable cost per correct, accepted result.

References and further reading

  1. OpenAI — Prompt Caching. Provider-side prompt-prefix reuse, cache usage, and retention behavior.
  2. OpenAI — API Pricing. Model-specific input, output, and cached-input pricing.
  3. Anthropic — Prompt Caching. Cache breakpoints, cache lifetimes, and provider-specific behavior.
  4. Google — Gemini Context Caching. Reusing context with Gemini API caching.
  5. Microsoft Research — LLMLingua. Research into prompt compression and reducing less useful tokens.
  6. LongLLMLingua — Improving LLM Efficiency with Query-Aware Compression. Research on long-context compression and information placement.
  7. LMSYS — RouteLLM. Research and tooling for routing requests between models with different capabilities.