Home / Insights / Software Costs and Budgets

Software Costs and Budgets

Cutting LLM Inference Costs: Prompt Caching, Batching, Compression and Smaller Models

Most LLM bills are inflated by the same few patterns: resending identical context, paying real-time prices for work that can wait, and sending every request to the largest model. This guide explains four engineering levers that address those patterns and how to decide which to apply first.

TopicsSoftware Costs and BudgetsGenerative AI and LLMs

Key takeaways

  • Start by measuring where tokens go per workflow: repeated prefixes, long retrieved context, output length and retries usually explain most of the bill.
  • Prompt caching rewards prompts with a long, stable prefix. Put system instructions, tools and reference documents first and keep them byte-identical between calls.
  • Anything that does not need an answer in seconds, such as evaluations, back-office classification and enrichment, belongs on a batch API at a discount.
  • Prompt compression and model routing can save more than caching, but they change what the model sees, so they need an evaluation set and a quality gate before rollout.
  • Treat cost work as a release with acceptance criteria: a baseline, a target cost per successful task and a rollback plan.

When an LLM feature moves from pilot to real traffic, the monthly invoice often grows faster than usage. Teams that budgeted on a per-request estimate discover that every chat turn resends the full system prompt, that retrieval adds several thousand tokens of context to each question, and that nightly jobs run at the same price as interactive requests. None of this is a model problem. It is an engineering problem, and it has engineering answers.

This article is for CTOs, engineering leads and product owners who already run, or are about to run, LLM features in production and need to reduce cost per request without a visible drop in answer quality. It covers four levers in the order we usually apply them: prompt caching, batch processing, prompt compression and context trimming, and smaller models with routing. For each, it explains what the lever actually reduces, what it costs in engineering effort and risk, and how to tell whether it suits your workload. It finishes with a decision table, a rollout plan and a checklist.

Where does an LLM inference bill actually come from?

Before choosing a technique, break the bill down. Most hosted LLM APIs charge separately for input tokens and output tokens, and output tokens are typically priced several times higher than input tokens. That pricing structure means two features with the same number of requests can have very different costs.

The five usual cost drivers

  • Repeated prefix. System instructions, tool definitions, policy text and few-shot examples sent unchanged with every call. In a chat product this block is resent on every turn.
  • Retrieved or uploaded context. Documents pulled in by retrieval-augmented generation (RAG), conversation history and attachments. This is often the largest input component.
  • Output length. Verbose answers, unnecessary explanations and JSON with long field names. Because output is priced higher, trimming it pays off quickly.
  • Model tier. Sending simple classification or extraction to the most capable model available.
  • Waste. Retries after malformed output, timeouts that are re-run, duplicate requests from the front end and abandoned streams.

Measure per workflow, not per month

Log input tokens, cached tokens (where the provider reports them), output tokens, model, latency and outcome for every call, tagged with the workflow that made it. Then compute cost per successful task, for example cost per resolved support question or per correctly extracted invoice.

Cost driverMain leverTypical effortQuality risk
Repeated prefixPrompt cachingLow: reorder and stabilise promptsVery low: the model sees the same text
Non-urgent volumeBatch APILow to medium: job queue and result handlingVery low
Long retrieved contextContext trimming and compressionMediumMedium: the model sees less
Over-specified modelSmaller models, cascades, routingMedium to highMedium to high without evaluation
Output length and wasteOutput limits, structured output, idempotencyLowLow

Action: add token and outcome logging to every LLM call this sprint, and produce a one-page breakdown of the top three workflows by spend before changing anything else.

How does prompt caching work, and how should prompts be structured for it?

Prompt caching lets a provider reuse the computation for the beginning of a prompt that it has seen recently. If the first part of your request is identical to a recent request, that part is processed faster and billed at a lower rate. The model receives exactly the same input, so answer quality is unchanged. That is why we treat caching as the first lever.

What the major providers offer

OpenAI announced automatic prompt caching in October 2024. According to OpenAI’s announcement, it applies to prompts of at least 1,024 tokens on supported models, reuses the longest previously computed prefix, and bills cached input tokens at a 50% discount. Caches are typically cleared after 5 to 10 minutes of inactivity and always within an hour of last use. No code change is needed, and the response reports how many tokens were served from cache.

Anthropic’s approach is explicit: you mark cache breakpoints in the request. Anthropic’s prompt caching material states that writing to the cache costs 25% more than the base input price, while reading from it costs 10% of the base price, and reports up to 90% cost reduction and up to 85% latency reduction for long prompts. Its published examples include a 100,000-token cached document where time to first token fell from 11.5 seconds to 2.4 seconds.

Design rules that make caching work

  1. Order content from most stable to least stable. System instructions, tool schemas and reference material first; retrieved documents next; the user’s latest message last.
  2. Keep the prefix byte-identical. A timestamp, request ID or user name injected into the system prompt breaks the match. Move dynamic values to the end.
  3. Avoid reordering tools or examples. Serialise tool definitions deterministically; a change of key order in generated JSON is enough to miss the cache.
  4. Understand the expiry window. Caching helps traffic that repeats within minutes. A tool used twice a day will rarely hit the cache, so do not count on it in the business case.
  5. Check the cache-write premium. With explicit caching, a prefix that is written but rarely read can cost more than not caching at all.

An illustrative calculation

For example, an internal support assistant might send a 6,000-token block of instructions and policy text, plus about 1,500 tokens of retrieved articles and question, on each call. If most calls arrive within a few minutes of each other during office hours, the 6,000-token block can be served from cache on the majority of calls. Under a provider that bills cached tokens at half price, the input cost of that block roughly halves; under one that bills cache reads at a tenth of the base price, it falls by most of its value after the first write. The output cost does not change, which is why caching alone rarely cuts a total bill by the headline percentage.

Action: audit your three highest-volume prompts for dynamic values in the prefix, restructure them, and track the cached-token ratio in your dashboard. A healthy ratio on chat or agent workloads is a sign the restructuring worked.

Which workloads should move to batch processing?

Many LLM workloads do not need an answer in seconds: nightly classification of tickets, enrichment of product records, generating summaries for a weekly report, running evaluation suites and re-embedding a document library. Paying interactive prices for these is avoidable.

According to OpenAI’s Batch API guide, batch jobs are billed at a 50% discount compared with synchronous calls, complete within a 24-hour window (often sooner) and use a separate rate-limit pool, so they do not compete with your live traffic. The guide lists evaluations, classifying large datasets and embedding content repositories as typical uses. Other major providers offer comparable asynchronous batch options; check each provider’s documentation for its own discount and limits.

How to decide whether a job can be batched

  • Who waits for the result? If a person is looking at a spinner, it is interactive. If the result lands in a database for later use, it is a batch candidate.
  • What is the real deadline? Many jobs described as real-time actually need to be ready by the next morning or the next business day.

Engineering pattern

  1. Write requests to a queue or table with a stable ID per item.
  2. Submit them in batches on a schedule, recording the batch ID.
  3. Poll for completion, then validate each result against a schema before writing it back.
  4. Resubmit failed or invalid items, with a cap on attempts, and alert when the failure rate exceeds a threshold.

Action: list every scheduled or back-office LLM job, record its true deadline, and move anything with a deadline longer than a day to a batch pipeline.

When do prompt compression and context trimming pay off?

If retrieved context dominates your input tokens, caching helps little because that context changes with every question. The alternative is to send less. There are two broad approaches, and the simpler one should come first.

Context trimming (start here)

  • Retrieve fewer, better chunks. Many RAG pipelines send the top ten chunks by default. Measuring answer quality at five or three chunks often shows little difference.
  • Re-rank before sending. A re-ranking step lets you send only the most relevant passages.
  • Summarise long conversation history. Keep recent turns verbatim and replace older turns with a running summary.
  • Strip boilerplate. Navigation text, legal footers and repeated headers from scraped or converted documents add tokens without information.
  • Constrain output. Set maximum output lengths, ask for structured output with short field names, and remove instructions that invite lengthy explanations.

Learned prompt compression

Research has shown that prompts can be compressed algorithmically. The LLMLingua paper (Jiang et al., 2023) describes a coarse-to-fine method that uses a small language model to remove low-information tokens and reports up to 20x compression with little performance loss on the benchmarks studied. In production, results depend on the task: compression tends to work better on verbose natural-language context than on dense material such as contracts, code or tables, where single tokens carry meaning.

Compression adds latency and its own compute cost, makes prompts harder to debug, and produces context that changes on every call, so it gains nothing from prefix caching.

Action: run an experiment on one RAG workflow comparing current retrieval, fewer chunks with re-ranking, and (only if needed) learned compression, scored on the same evaluation set.

Can smaller models and routing replace the largest model?

Model choice is usually the biggest single cost factor, because price differences between tiers within one provider can be an order of magnitude or more. Many production tasks, such as intent classification, field extraction, tagging and short rewrites, do not need the most capable model. The challenge is identifying which requests can safely go to a cheaper one.

Three patterns

  • Static assignment. Each workflow is pinned to the smallest model that passes its evaluation set. Simple and predictable; the right starting point for most teams.
  • Cascade. A small model answers first; if a confidence check, validator or self-assessment fails, the request escalates to a larger model. The FrugalGPT paper by Chen, Zaharia and Zou describes prompt adaptation, model approximation and cascades, and reports matching the best individual model’s performance with up to 98% cost reduction in its experiments.
  • Learned router. A lightweight classifier predicts which model a request needs before any call is made. The RouteLLM paper trains routers on preference data and reports cost reductions of more than two times in certain cases without compromising response quality.

Choosing between them

PatternBest whenLatency impactWhat you need
Static assignmentWorkflows are distinct and well definedNone, often fasterEvaluation set per workflow
CascadeMost requests are easy, a minority are hard, and failure is detectableHigher on escalated requestsA reliable validator or confidence signal
Learned routerOne entry point handles very mixed requests at high volumeSmall overhead for routingLabelled or preference data, ongoing monitoring

Research results are measured on benchmarks, not on your data. Treat the published figures as evidence that the approach can work, not as a forecast of your savings.

Action: for each workflow, run its evaluation set against one or two cheaper models and record pass rates. Pin any workflow where a cheaper model meets the quality threshold before considering cascades or routers.

How should you decide which lever to apply first?

The right order depends on the shape of your traffic. The table below summarises how we usually match levers to workloads.

WorkloadFirst leverSecond leverUsually not worth it
Chat assistant with long system promptPrompt cachingHistory summarisationLearned compression
RAG question answeringFewer, re-ranked chunksSmaller model for simple questionsCaching of retrieved text
Nightly classification or enrichmentBatch APISmaller modelRouter
Agent with tools and multi-step loopsPrompt caching of tools and instructionsStep limits and output limitsAggressive compression
High-volume mixed queries at one endpointStatic assignment by intentCascade or learned routerBatch

For a broader view of cost control across the AI lifecycle, see our articles on reducing LLM token and cloud costs without losing answer quality and measuring cost per successful workflow.

How do you implement cost reductions without breaking quality?

Cost work fails when it is treated as configuration rather than a release: a change to retrieval depth or model tier can silently degrade answers for weeks.

Step-by-step rollout

  1. Baseline. Record cost, latency and quality for each target workflow over at least a week of normal traffic.
  2. Build or refresh the evaluation set. Use real, anonymised requests with expected outcomes, including edge cases and known failures.
  3. Apply zero-risk changes first. Prompt restructuring for caching, output limits, deduplication and batch migration.
  4. Test quality-affecting changes offline. Run trimming, compression and model changes against the evaluation set, ideally as batch jobs.
  5. Release behind a flag. Route a small share of traffic to the new configuration and compare outcome metrics such as task completion, escalation rate and user feedback.
  6. Ramp and monitor. Increase traffic gradually and keep the rollback switch for at least one full business cycle.

Risks and hidden costs

  • Quality drift. Savings are visible on the invoice; quality loss shows up later as support tickets or churn. Track both on the same dashboard.
  • Cache fragility. A well-meant prompt edit can drop the cache hit rate overnight. Alert on sudden changes in cached-token ratio.
  • Engineering time. Routers and compression pipelines need maintenance. Compare the expected monthly saving with the build and run cost.
  • Provider dependency. Optimising heavily for one provider’s caching or batch features makes switching harder. Keep a thin abstraction layer over model calls.

Cost-reduction checklist

  • Token, cache and outcome logging per workflow is in place.
  • Cost per successful task is baselined and has a target.
  • Prompts are ordered stable-first with no dynamic values in the prefix.
  • Output length limits and structured output are set.
  • Non-urgent jobs run through a batch pipeline with retries.
  • Retrieval depth has been tested against an evaluation set.
  • Each workflow uses the smallest model that passes its evaluation.
  • Changes ship behind flags with a rollback plan.

Our LLM application development work includes production features such as caching, typed outputs and fallbacks, along with cost dashboards and regression testing, which is the foundation this kind of optimisation needs. If you are planning private hosting as an alternative, our guide to self-hosted LLM costs and GPU sizing covers that comparison.

Frequently asked questions

How much can prompt caching realistically save?

It depends on how much of each prompt is a stable prefix and how often requests repeat within the cache window. Providers have published figures such as a 50% discount on cached input tokens (OpenAI) and cache reads at 10% of the base input price (Anthropic), but those apply only to the cached portion of input. Output tokens and uncached context are billed as normal, so measure your own cached-token ratio before forecasting savings.

Will switching to a smaller model hurt answer quality?

It can, which is why the switch should be gated by an evaluation set built from real requests. Many classification, extraction and short-rewrite tasks pass comfortably on smaller models; open-ended reasoning and long-form generation are more sensitive. Pin each workflow to the smallest model that meets an agreed quality threshold.

Is prompt compression safe for legal or financial documents?

Treat it with caution. Learned compression removes tokens it judges low-information, and in dense material such as contracts, financial tables or code a single dropped word can change meaning. For these documents, better retrieval and re-ranking are usually safer ways to reduce context.

Should we build our own model router?

Only after static assignment is in place and you have data showing a large share of mixed, high-volume traffic at one entry point. Routers need training data, monitoring and maintenance. For most teams, pinning workflows to suitable models and adding a simple cascade with a validator delivers most of the benefit.

Sources and methodology

Guidance reflects PoliteTech delivery experience. The external references below informed specific points in this article.

  1. OpenAI: Prompt Caching in the API (1 October 2024) — accessed 9 November 2026. Supports the 1,024-token minimum, automatic prefix reuse, 50% discount on cached input tokens and the cache expiry window.
  2. Anthropic: Prompt caching with Claude (announced August 2024) — accessed 9 November 2026. Supports the cache-write and cache-read pricing multipliers, the up to 90% cost and 85% latency reduction claims and the long-document latency example.
  3. OpenAI: Batch API guide — accessed 9 November 2026. Supports the 50% batch discount, 24-hour completion window, separate rate-limit pool and typical batch use cases.
  4. Jiang et al., LLMLingua: Compressing Prompts for Accelerated Inference of Large Language Models (arXiv, 2023) — accessed 9 November 2026. Supports the description of learned prompt compression and the up to 20x compression result.
  5. Chen, Zaharia and Zou, FrugalGPT (arXiv, 2023) — accessed 9 November 2026. Supports the description of prompt adaptation, model approximation and cascades, and the up to 98% cost reduction result.
  6. Ong et al., RouteLLM: Learning to Route LLMs with Preference Data (arXiv, 2024) — accessed 9 November 2026. Supports the description of learned routers and the more than two times cost reduction in certain cases.

Where is your LLM budget actually going?

We can review token logs for your highest-volume workflows and recommend which caching, batching or model changes are worth making first.