Every production LLM app eventually hits the same moment: the feature works, usage grows, and the monthly API invoice starts looking like a second infrastructure bill. The fix is not a cheaper provider or a single clever trick. To cut LLM API costs in a way that survives scale, treat tokens like a budget: measure where they go, then remove the waste without removing the information the model actually needs.
Measure before you optimize
Before changing anything, log three numbers per feature: input tokens per request, output tokens per request, and requests per day. Most providers return usage figures in the API response, so pipe them into your existing metrics. You will almost always find one surprise: a chat feature resending a 4,000-token history on every turn, or a summarizer running on a default token limit nobody set. Fix those first, because no compression technique beats deleting tokens you never needed to send.
12 techniques that actually move the bill
Each of these is a concrete, code-level change. Start with the low-effort ones and work down the list.
1. Cache the stable prompt prefix
Prompt caching lets the provider skip reprocessing the unchanged start of your prompt. Put your system instructions, API docs, and few-shot examples first, in exactly the same order on every call, and mark that prefix as cacheable. Most providers discount cached input steeply (some list up to around 90% off cached tokens, so check your provider’s pricing page for the current rate). The catches: the prefix must be long enough and byte-identical, and the first call that writes the cache can cost extra. For chatbots and agents reusing the same instructions across thousands of requests, this is usually the single biggest win.
response = client.messages.create(
model="claude-sonnet-4-6",
system=[
{"type": "text", "text": SYSTEM_PROMPT,
"cache_control": {"type": "ephemeral"}}
],
messages=[{"role": "user", "content": query}],
max_tokens=500,
)
2. Route easy tasks to smaller models
Not every call needs your flagship model. Classification, extraction, routing, and simple rewrites usually run fine on a mini or flash-class model that costs a fraction per token and answers faster. A simple router, even a rules-based one, sends the easy traffic to the cheap model and reserves the expensive one for hard cases. The non-negotiable part: keep a labeled eval set and re-run it after routing. A cheaper wrong answer that gets retried costs more than one correct expensive call. The exact ladder changes constantly, so it helps to track a current comparison of the best LLM APIs for developers before you hard-code routing rules.
def answer(query):
if is_simple(query): # regex, keyword, or tiny classifier
return cheap_model.complete(query, max_tokens=200)
return flagship_model.complete(query, max_tokens=2000)
3. Cap output and demand structure
Output tokens are priced higher than input at most providers, so the completion is where the money goes. Set an explicit max_tokens on every call. Then stop asking for prose when you need data: a JSON object with exactly the fields you parse replaces paragraphs of explanation. Use your provider’s structured output or JSON mode so the response parses on the first try (see technique 10). Fewer output tokens, faster responses, and no post-processing regex.
resp = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": prompt}],
max_tokens=300,
response_format={"type": "json_object"},
)
4. Retrieve context instead of dumping it
The classic RAG mistake is stuffing the entire document into the prompt just in case. Retrieve the top few relevant chunks and send only those. For agents, summarize stale conversation history into a running summary instead of resending the full transcript every turn. Every token in the prompt is paid for on every call, so context should be earned, not defaulted.
5. Compress the prompt itself
Once the content is right, squeeze the wrapper: strip redundant whitespace and verbose scaffolding, cut few-shot examples down to the two or three that actually change behavior, and replace boilerplate introductions with direct instructions. Test each cut against your eval set. Prompt compression is free money, but it is also the easiest place to accidentally remove the one example that kept the model on track.
6. Cache answers, not just prompts
If users ask the same questions, do not pay to answer twice. Hash the normalized query, store the response, and serve cache hits at zero API cost. For near-duplicates, a semantic cache compares embeddings and reuses an answer when similarity clears a threshold. Tune that threshold conservatively: a false cache hit (the wrong answer, delivered fast) is worse than a cache miss.
key = sha256(normalize(query).encode()).hexdigest()
if cached := store.get(key):
return cached # zero tokens spent
result = model.complete(query, max_tokens=400)
store.set(key, result, ttl=3600)
7. Batch the work that can wait
Reports, backfills, dataset labeling, bulk classification: anything nobody is waiting on. All major providers offer batch APIs that run asynchronously at roughly half the price (rates and turnaround times vary, so check official pricing). Queue the offline work, submit it as a batch, and collect results hours later. The discount stacks with the other techniques, so a batched, cached, compressed, small-model job costs a fraction of the naive version.
8. Stream and stop early
Streaming does not reduce tokens by itself, but it lets you stop paying sooner. If the first sentences show the answer is off track, abort the request instead of waiting for a full completion you will discard. For search-and-extract tasks, ask the model to emit the answer first and the explanation after, then cut the stream the moment you have what you need.
9. Do not pay for reasoning you will not read
Reasoning models bill thinking tokens as output. If your app discards the chain of thought and only uses the final answer, configure the model to omit or minimize the visible reasoning trace; several providers expose this as a parameter. For easy subtasks, lower the reasoning effort setting and save the deep thinking budget for the calls that genuinely need it.
10. Kill the retry loop
Every retry is a full-price repeat of the call. The cheapest retry is the one that never happens: validate inputs before the call, use structured outputs so responses parse, and set strict timeouts. Log which prompts retry most often and fix those prompts instead of raising the retry count. One flaky prompt retried three times at production volume is often a bigger line item than the model choice itself.
11. Consolidate round trips
Five small calls cost five sets of overhead: repeated system prompts, repeated context, repeated latency. Where steps are independent, combine them into one well-structured call. Where an agent makes one tool call per fact, let it batch tool calls or prefetch. Count calls per user task, not just tokens per call, and treat “calls per task” as a metric worth driving down.
12. Govern it like money, because it is
Set per-feature budgets with alerts, per-key rate limits, and a hard kill switch for runaway loops. An agent stuck retrying can burn a day’s budget in minutes, and no optimization technique protects you from a bug. Review the cost dashboard weekly the way you review server costs. Optimization without guardrails just means the next incident is more expensive.
Technique comparison at a glance
| Technique | Effort | Best for | Watch out for |
|---|---|---|---|
| Prompt caching | Low | Repeated system prompts, chat, agents | Needs a long, stable prefix; cache-write call can cost extra |
| Model routing | Low-Medium | Mixed-difficulty traffic | Quality risk if the router misclassifies |
| Output caps + structured output | Low | Every call | Caps set too tight truncate answers |
| Retrieve instead of dumping | Medium | RAG, long docs, agents | Retrieval misses drop needed context |
| Prompt compression | Low | Bloated hand-written prompts | Easy to cut the example that mattered |
| Response / semantic caching | Medium | Repeated or similar queries | False hits serve wrong answers |
| Batch APIs | Low | Offline, scheduled work | Hours of latency; not for interactive use |
| Stream + early stop | Low | Long generations, extraction | Requires client-side abort logic |
| Suppress reasoning output | Low | Reasoning models, easy subtasks | Less debuggability when things go wrong |
| Retry reduction | Low | Flaky prompts, agents | Needs logging to find the bad prompts |
| Call consolidation | Medium | Multi-step agents, pipelines | Bigger prompts are harder to debug |
| Budgets + kill switches | Low | Everything in production | Alerts need someone to act on them |
The rule underneath all of it
Cheaper per call means nothing if the answer gets worse. Gate every technique above on the same check: run your eval set before and after, and confirm quality holds. A wrong answer that triggers a retry, a support ticket, or a lost user costs more than any token ever will. Optimize the tokens, but measure the task.
Pick the three lowest-effort techniques that fit your workload, ship them behind your eval set, and check the invoice next month. A sensible starting order for most codebases: cache the prompt prefix, cap the output, and route the easy traffic to a smaller model. That is an afternoon of work. And if volume keeps climbing despite all of it, the endgame is self-hosting, where an open-source inference server like vLLM swaps per-token pricing for GPU rent.