Shipping an LLM feature is easy in a prototype—until traffic scales to 50,000 daily requests and uncached system prompts plus verbose JSON outputs turn a $40 test bill into a $2,500 monthly cloud invoice.
Where LLM API Spend Actually Goes (And How to Cut It by 60–80%)
Commercial LLM APIs bill per million input and output tokens, with output tokens costing 3x to 5x more than input tokens. Combining four engineering levers—prefix prompt caching, model-tier routing, concise structured outputs, and Redis exact/normalized caching—routinely cuts monthly spend by 60–80% while lowering p95 response latency.
Before changing code, plug your prompt size and daily request volume into our LLM Token Counter & API Cost Calculator to see your baseline spend across Flash, Balanced, and Frontier model tiers.
4 High-Impact Cost Optimization Techniques
| Technique | Typical Cost Reduction | Latency Impact |
|---|---|---|
| 1. Model-tier routing (Flash/Mini for classification & extraction) | 75% – 90% on routed calls | 2x – 4x faster |
| 2. Prefix / system-prompt caching (static instructions first) | 50% – 90% on cached input tokens | Lower time-to-first-token (TTFT) |
| 3. Redis exact hash cache for repeated user queries | 100% on cache hits | < 5 ms response |
4. Compact JSON keys + strict max_output_tokens cap |
20% – 40% on expensive output tokens | Faster stream completion |
Rule #1 for Prompt Caching: Keep Static Context Byte-Identical at the Prefix
Automatic and explicit prompt caches match tokens from the start of the request. If you inject a dynamic timestamp or user ID on line 1 of your system prompt, you invalidate the entire cache on every call! Always order messages so static instructions, tool schemas, and reference documents come first, and dynamic user input comes last.
Practical Example: Redis Response Cache + Token Cap in PHP 8.x
<?php
function cachedLlmClassify(Redis $redis, string $apiKey, string $ticketText): array
{
$normalized = strtolower(trim(preg_replace('/\s+/', ' ', $ticketText)));
$cacheKey = 'llm:classify:v1:' . hash('sha256', $normalized);
$cached = $redis->get($cacheKey);
if (is_string($cached)) {
return json_decode($cached, true, 512, JSON_THROW_ON_ERROR);
}
$payload = [
'model' => 'gpt-4o-mini', // Route classification to fast/low-cost tier
'temperature' => 0,
'max_completion_tokens' => 120, // Hard ceiling prevents runaway token bills
'response_format' => ['type' => 'json_object'],
'messages' => [
[
'role' => 'system',
'content' => 'Classify the support ticket as JSON: {"cat":"billing|bug|auth","prio":1-3}. No prose.',
],
['role' => 'user', 'content' => mb_substr($ticketText, 0, 2000)],
],
];
$ch = curl_init('https://api.openai.com/v1/chat/completions');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 15,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Authorization: Bearer ' . $apiKey,
],
CURLOPT_POSTFIELDS => json_encode($payload, JSON_THROW_ON_ERROR),
]);
$raw = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($code !== 200 || ! is_string($raw)) {
throw new RuntimeException('LLM upstream error: HTTP ' . $code);
}
$resp = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
$result = json_decode($resp['choices'][0]['message']['content'] ?? '{}', true, 512, JSON_THROW_ON_ERROR);
$redis->setex($cacheKey, 86400, json_encode($result));
return $result;
}
Production Guardrails Against Runaway Bills
- Truncate untrusted user inputs: Enforce a character/byte ceiling before sending user text to an LLM endpoint so a single 500 KB paste cannot burn 125,000 tokens.
- Validate JSON outputs strictly: Test sample responses with our JSON Validator or generate typed models with JSON to Pydantic.
Implementing a Two-Tier Model Router in Node.js / TypeScript
Sending simple intent classification, tag extraction, or spell-checking requests to a $15/1M-output-token frontier reasoning model wastes 90% of your AI budget. Route requests dynamically based on task complexity—sending structured extraction and triage to a Flash/Mini tier while escalating only complex multi-step code or architectural synthesis:
export type TaskComplexity = 'extract' | 'summarize' | 'deep_reasoning';
const MODEL_ROUTING_TABLE: Record<TaskComplexity, { model: string; maxOutTokens: number }> = {
extract: { model: 'gpt-4o-mini', maxOutTokens: 200 },
summarize: { model: 'gpt-4o-mini', maxOutTokens: 500 },
deep_reasoning: { model: 'gpt-4o', maxOutTokens: 1600 },
};
export function selectModelConfig(task: TaskComplexity, inputChars: number) {
const base = MODEL_ROUTING_TABLE[task];
// Hard guardrail: reject oversized untrusted inputs before incurring token billing
if (inputChars > 40_000) {
throw new Error(`Input length (${inputChars} chars) exceeds 40k per-request budget ceiling.`);
}
return base;
}
Batch APIs (50% Instant Discount for Asynchronous Workloads)
Not every LLM call sits behind a synchronous user click! Nightly content classification, bulk translation, log summarization, and embedding backfills tolerate a 1-to-12-hour turnaround. Major LLM providers (OpenAI Batch API, Anthropic Message Batches, Google Gemini Batch) offer a flat **50% discount on both input and output tokens**—plus separate higher rate-limit pools—when you upload requests as an `.jsonl` (NDJSON) batch file instead of firing real-time HTTP loops!
Trimming Output Token Verbosity Without Losing Accuracy
Because output tokens cost 3x–5x more than input tokens, cutting 250 unnecessary tokens from every response saves far more money than trimming 250 tokens from your prompt:
- Ban conversational preambles: Instruct the system prompt to output raw JSON without `"Sure! Here is the JSON analysis you requested:"` markdown wrappers.
- Use concise enum codes instead of long sentences inside JSON arrays: Returning `{"severity":"H","rule":"NO_SELECT_STAR"}` instead of verbose paragraph strings across 50 items cuts output tokens by 70%—and maps back to human-readable UI strings in your frontend for free!
- Configure stop sequences (`stop: ["\n\n"]`) on single-line completion or classification tasks so generation halts the instant the answer is emitted.
Token Cost Monitoring & Per-Tenant Rate Limiting
- Log `usage.prompt_tokens`, `usage.completion_tokens`, and `cached_tokens` per tenant: Track real unit economics per customer plan so a single heavy user on a $19/month SaaS plan cannot consume $85/month in unthrottled Frontier API calls!
- Enforce sliding-window token budgets in Redis: Meter *tokens per minute/day* per `user_id` rather than only HTTP requests per minute, returning HTTP `429 Too Many Requests` (HTTP Status Code Reference) when a free-tier quota is reached.
- Forecast before shipping: Model any new feature’s prompt length and daily request volume in our LLM Token Counter & API Cost Calculator and compare infrastructure hosting options in the Serverless & Cloud Cost Calculator.