Traditional software has a fixed cost per request that rounds to zero. AI features do not: every call has a real, variable price, and a feature that looked cheap in testing can become the largest line on an infrastructure bill once real users find it. The good news is that most of the spend is concentrated in a few patterns that are straightforward to fix.
Understand where the money goes
Costs are per token, split between input and output, and output is typically several times more expensive than input. Before optimising anything, instrument per-request cost broken down by feature, by user and by prompt version. Almost every team that does this finds the same two things: one feature accounts for most of the bill, and a small number of users account for most of that feature.
The second most common finding is that input tokens dominate. A RAG feature sending 12,000 tokens of retrieved context to produce a 200-token answer is paying almost entirely for input, which means retrieval tuning is a cost lever, not just a quality one.
Prompt caching: usually the biggest single win
Providers cache a prompt prefix and charge substantially less for the cached portion on subsequent calls. The requirement is that the prefix is byte-identical, which makes prompt structure a cost decision:
[ system instructions ] ← stable
[ tool definitions ] ← stable CACHEABLE PREFIX
[ few-shot examples ] ← stable
[ company knowledge base ] ← stable
───────────────────────────── cache breakpoint
[ retrieved documents ] ← varies
[ conversation history ] ← varies
[ current user message ] ← varies
The mistakes that silently destroy cache hit rates:
- A timestamp or request ID in the system prompt. One dynamic character at position 40 invalidates everything after it.
- Personalising the system prompt with the user's name or account tier. Move it below the breakpoint.
- Reordering tool definitions between calls, which happens when they are built from an unordered map.
- Editing the prompt frequently. Each change resets the cache for everyone.
Monitor cache hit rate as a first-class metric. A drop from 90% to 20% after a deploy is a several-fold cost increase that no other alarm will catch.
Route by difficulty
Most workloads are not uniformly hard. Sending every request to the most capable model is like running every query on the largest database instance because some queries are complex.
classify intent → small, fast model
extract fields from form → small model with a strict schema
summarise a document → mid-tier model
draft a legal response → most capable model
generate code + review → most capable model
Two routing patterns work well in practice. Static routing assigns a model per task type — simple, predictable, and covers most of the benefit. Cascading tries a cheaper model first and escalates when a confidence check or validation fails, which saves more but adds latency on the escalation path and a second failure mode to reason about.
Whichever you choose, evaluate the cheap model on your actual eval set rather than assuming. Small models are often adequate for classification and extraction and clearly inadequate for multi-step reasoning, and the only way to know where your task sits is to measure it.
Reduce input before reducing quality
- Retrieve less. Five well-ranked chunks usually beat fifty. Adding a reranking step often lets you cut the number of chunks sent by 60% while improving accuracy.
- Compact conversation history rather than carrying every turn verbatim.
- Trim tool results. Return the three fields the model needs, not the full API response.
- Cut few-shot examples once the model handles the task reliably. They were scaffolding.
- Strip boilerplate from retrieved documents — navigation, headers, repeated legal footers.
Control output
Output tokens are the expensive ones, and they are also the ones users wait for:
- Set
max_tokensdeliberately on every call, sized to the task. - Ask for the format you want. "Answer in at most three sentences" is a cost control as well as a UX decision.
- Use structured output for anything a machine consumes — a JSON object is far shorter than a paragraph explaining the same thing.
- Be deliberate about extended reasoning. Reasoning tokens are billed and can dwarf the visible answer. Enable it where accuracy justifies it, not by default.
Cache at the application level too
Provider caching helps with repeated prefixes. Application caching eliminates the call entirely:
$key = 'ai:summary:' . $doc->id . ':' . $doc->updated_at->timestamp . ':' . PROMPT_VERSION;
$summary = Cache::remember($key, now()->addDays(30), fn () => $this->llm->summarise($doc));
Document summaries, classifications, embeddings and category assignments are all deterministic given the same input and prompt — there is no reason to regenerate them. Include the prompt version in the key so a prompt change invalidates correctly rather than serving output from the old instructions.
Semantic caching (matching similar rather than identical queries) is a further step, and it needs care: two questions with high embedding similarity can have different correct answers, so the similarity threshold has to be tuned and validated rather than guessed.
Guardrails against the bad week
- Per-user and per-tenant budgets, enforced in code with a clear message when exceeded — not discovered on the invoice.
- Hard caps on agent iterations. A loop that runs 200 times is both a bug and a bill.
- Rate limits per feature, so one runaway integration cannot consume the whole quota.
- Alerts on daily spend anomalies and on cache hit rate drops.
- A kill switch per feature. The ability to disable one AI feature without a deploy is worth having before you need it.
The order that works: measure per-feature cost, fix the cache boundary, reduce retrieved context, route the easy tasks to a cheaper model, then cache deterministic results. In most applications those five steps take the bill down by more than half without touching output quality.
Related Service
🤖 Business Process Automation
Business process automation with n8n, Zapier, Make, and AI — connect your tools, eliminate repetitive work, and let workflows run themselves around the clock.
Explore Business Process Automation →
Reviews & Comments
Reviews are moderated and appear after approval.
No reviews yet — be the first to share your thoughts.
Leave a Review