Understand the Asymmetric Economics of Tokens
Not all tokens are priced equally, and where they sit in your pipeline dictates your margin.
- The Output Multiplier: Across major frontier model providers (OpenAI, Anthropic, Google), output tokens cost 3x to 5x more than input tokens. Asking an LLM to "explain its reasoning before giving the final JSON" means you are paying a premium for conversational filler that your application parser immediately throws away.
- The Multi-Turn Compounding Trap: LLMs are stateless. In a 10-turn chat session, Turn 10 re-sends Turns 1 through 9. Without context pruning, token consumption grows quadratically rather than linearly.
- The Agentic Loop Risk: Autonomous agents that call tools, read full database payloads, and self-correct can easily burn 50,000+ tokens on a single user ticket if left unconstrained.
Layer 1: Prompt & Payload Hygiene (Immediate 20–30% Savings)
Before changing your infrastructure, clean up what crosses the API boundary.
Strip Conversational Filler from System Prompts
System prompts tend to accumulate edge-case rules like a junk drawer, and you pay for every word on every single API call. Replace polite prose with direct, imperative constraints.
- Bloated (44 tokens): "You are a helpful and polite enterprise assistant. Whenever a customer asks a question, please read the provided context carefully and summarize the answer clearly in three bullet points without making anything up."
- Optimized (16 tokens): "Answer using ONLY the provided context. Format: 3 concise bullet points. No preamble."
Enforce Strict Output Boundaries
Because output tokens carry the highest price tag, constrain generation at both the prompt and parameter levels:
- Pass strict
max_tokenslimits at the API level to act as a hard ceiling. - Force structured outputs (JSON schema) with short key names (e.g.,
"cat"instead of"document_category_classification") when the output is consumed by code rather than humans. - Instruct the model explicitly: "Return ONLY the requested value. Zero prose or markdown wrapper."
Shape Tool Outputs at the Boundary
When an AI agent queries an internal API or database, never dump the raw JSON response directly into the model's context window. Filter the payload in code first. If the model only needs account_status and last_invoice_date, strip the other 60 fields before returning the tool result to the LLM.
Layer 2: Context & Retrieval Architecture (30–50% Savings)
In Retrieval-Augmented Generation (RAG) and chat applications, context bloat is the primary cost driver.
- Precision RAG & Reranking: Dumping the top 10 full documents into a prompt wastes thousands of tokens on irrelevant paragraphs. Chunk documents semantically into 300–500 token blocks, retrieve the top 15 via vector search, and use a fast, lightweight Reranker model to pass only the top 3 highest-scoring chunks to the LLM.
- Sliding Window & Rolling Summarization: Instead of passing a 50-message chat history on every turn, keep the system prompt, a 150-token rolling summary of older turns, and only the last 4 verbatim messages.
Layer 3: Infrastructure & Model Routing (50–80% Savings)
Architectural optimizations deliver the deepest, most durable cost reductions without touching prompt quality.
Strategy | How It Works | Typical Cost Reduction | Best Use Case |
|---|---|---|---|
Tiered Model Routing | Uses a lightweight classifier to send simple tasks (intent detection, extraction, formatting) to small models and reserves frontier models for complex reasoning. | 50% – 75% | Customer support pipelines, multi-step agents |
Prompt Caching | Caches static prefix tokens (long system instructions, few-shot examples, core documentation) at the provider level so you don't pay full price to re-process them. | 50% – 90% on cached inputs | Heavy system prompts (>1,000 tokens), codebase Q&A |
Semantic Caching | Uses vector similarity to detect if a user's question was already answered recently, returning the stored response with zero LLM call. | 100% on cache hits | High-volume FAQ bots, documentation search |
Batch APIs | Queues non-urgent workloads to run asynchronously during off-peak compute hours. | 50% flat discount | Nightly data enrichment, bulk document tagging, evals |
Layer 4: FinOps & Token Governance
You cannot optimize what you cannot attribute. Treat AI tokens like cloud compute:
- Tag Every Request: Attach metadata (
tenant_id,feature_name,workflow_step,environment) to every LLM API call. Know whether your onboarding flow or your reporting agent is driving your monthly bill. - Set Circuit Breakers for Agents: Enforce hard limits on autonomous loops (e.g., max 5 tool-call retries or max $0.50 per ticket) before the workflow halts and escalates to a human or fallback state.
- Measure Cost Per Outcome: Stop tracking "cost per 1M tokens" in isolation. Track cost per resolved support ticket or cost per verified lead extraction.
Some observations by examples
To keep the math transparent for engineering leaders, all cost calculations below use standard frontier model benchmark pricing ($3.00 / 1M input tokens, $0.30 / 1M cached input tokens, $15.00 / 1M output tokens) and small model pricing ($0.20 / 1M input tokens, $0.80 / 1M output tokens) at a volume of 100,000 requests per month.
Combined Impact at 100k Requests/Month
Optimization Layer | Unoptimized Tokens / Req | Optimized Tokens / Req | Monthly Cost (Before) | Monthly Cost (After) |
1. Prompt Caching | 6,300 in / 200 out | 300 uncached / 6,000 cached / 200 out | $2,190.00 | $570.00 |
2. Tool Payload Filtering | 4,200 in / 250 out | 580 in / 60 out | $1,635.00 | $264.00 |
3. Tiered Model Routing | 2,500 in / 400 out | 1,400 avg in / 260 avg out | $1,350.00 | $372.30 |
Total Pipeline Spend | 13,000 in / 850 out | 82% Effective Token Reduction | $5,175.00 / mo | $1,206.30 / mo |
Implementing all three patterns across a mid-sized production pipeline cuts monthly inference spend by 76.7%—saving $3,968.70 per month ($47,624 annually) while improving latency.
Example 1: Prompt Caching (Prefix Ordering & Cache Control)
The Scenario: An enterprise compliance assistant evaluates vendor contract clauses against a 4,500-token internal security policy and 1,500 tokens of few-shot grading examples.
Why It Fails in Production: LLM prompt caching works purely on exact prefix matching. If a developer injects dynamic variables (like a timestamp, user_id, or the incoming contract clause) at the top of the system prompt, the cache invalidates on every single call, forcing you to pay full price for the 6,000-token policy manual every time.
# ❌ BAD: Dynamic timestamp and user metadata sit at the top of the prompt.
# Every request changes token #12, invalidating prefix caching for the entire 6,000-token policy below it.
system_prompt = f"""
Current Timestamp: {datetime.utcnow().isoformat()}
Requesting User ID: {user.id} | Tenant: {user.tenant_name}
Clause to Evaluate: {user_submitted_clause}
You are a helpful legal and security compliance reviewer. Please read our company's
complete Master Security Policy and Few-Shot Examples below and thoroughly explain
whether the user's clause complies...
--- MASTER SECURITY POLICY (4,500 TOKENS) ---
{full_security_policy_text}
--- FEW-SHOT EXAMPLES (1,500 TOKENS) ---
{few_shot_examples}
"""
response = client.messages.create(
model="claude-3-5-sonnet-latest",
max_tokens=500,
system=system_prompt,
messages=[{"role": "user", "content": "Please review the clause above."}]
)
# ✅ GOOD: 100% static content sits at the top with an explicit cache breakpoint.
# Dynamic user data is isolated in the final user message turn.
response = client.messages.create(
model="claude-3-5-sonnet-latest",
max_tokens=250,
system=[
{
"type": "text",
"text": f"Evaluate contract clauses strictly against this policy.\n\n{full_security_policy_text}\n\n{few_shot_examples}",
"cache_control": {"type": "ephemeral"} # Caches the 6,000-token static prefix
}
],
messages=[
{
"role": "user",
# Only this 300-token dynamic block is billed at full input price
"content": f"Tenant: {user.tenant_name}\nClause: {user_submitted_clause}\nReturn JSON only: {{\"status\": \"PASS|FAIL\", \"risk_level\": \"1-5\", \"fix\": \"string\"}}"
}
]
)
The Economics (100,000 Requests/Month):
- Before: 6,300 uncached input tokens ($0.0189) + 200 output tokens ($0.0030) = $2,190 / month.
- After: 6,000 cached tokens at 90% discount ($0.0018) + 300 uncached tokens ($0.0009) + 200 output tokens ($0.0030) = $570 / month (74% savings).
Example 2: Tool Payload Filtering (Shaping Data at the Boundary)
The Scenario: A customer billing agent calls an internal ERP endpoint (GET /api/v2/invoices/{id}) to answer a customer asking why their latest invoice was declined.
Why It Fails in Production: Developers routinely serialize the entire database ORM object or raw REST response into the LLM's tool-result message. The LLM is forced to read thousands of tokens of internal UUIDs, CSS flags, warehouse codes, and audit logs just to find a single status string.
// ❌ BAD: Dumping raw 180-line ERP response directly into the agent's context window
const rawErpResponse = await fetch(`https://internal.erp/api/v2/invoices/${invoiceId}`).then(r => r.json());
/* rawErpResponse contains ~3,800 tokens of noise:
{
"_id": "66f1a9c0e4b0a1b2c3d4e5f6",
"organization_uuid": "9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d",
"stripe_webhook_raw_payload": { ... 120 lines of nested gateway metadata ... },
"internal_audit_trail": [ ... 45 historical log objects ... ],
"ui_theme_overrides": { "badge_color": "#FF0000", "show_banner": true },
"status": "DECLINED",
"decline_code": "insufficient_funds",
"amount_cents": 49900,
"retry_scheduled_at": "2026-11-06T00:00:00Z"
}
*/
const toolMessage = {
role: "tool",
tool_call_id: call.id,
content: JSON.stringify(rawErpResponse) // 3,800 tokens sent to the LLM!
};
// ✅ GOOD: Project only the exact fields the LLM needs to answer the question
const rawErpResponse = await fetch(`https://internal.erp/api/v2/invoices/${invoiceId}`).then(r => r.json());
const sanitizedToolPayload = {
inv_id: rawErpResponse.invoice_number,
status: rawErpResponse.status,
reason: rawErpResponse.decline_code,
amount: `${rawErpResponse.amount_cents / 100} ${rawErpResponse.currency}`,
next_retry: rawErpResponse.retry_scheduled_at
}; // Reduced from 3,800 tokens to 45 tokens!
const toolMessage = {
role: "tool",
tool_call_id: call.id,
content: JSON.stringify(sanitizedToolPayload)
};
The Economics (100,000 Requests/Month):
- Before: 4,200 total input tokens ($0.0126) + 250 conversational output tokens ($0.00375) = $1,635 / month.
- After: 580 total input tokens ($0.00174) + 60 concise output tokens ($0.0009) = $264 / month (83.9% savings and 3x faster Time-to-First-Token).
Example 3: Tiered Model Routing (Intent Classifier + Escalation)
The Scenario: A B2B SaaS operations pipeline processes 100,000 incoming user requests per month, ranging from simple status lookups and field extractions (75% of volume) to complex multi-document troubleshooting (25% of volume).
Why It Fails in Production: Routing 100% of traffic to a frontier reasoning model means paying $3.00/$15.00 per million tokens to format dates, classify basic intents, or answer routine FAQ queries that a lightweight model handles with identical accuracy at 1/15th the cost.
# ❌ BAD: Every query—even "Reset my API key"—invokes the heaviest frontier model
# with a massive 2,500-token master system prompt.
def handle_user_request(user_query: str, context_docs: str):
return llm_client.generate(
model="frontier-reasoning-model", # $3.00/1M in, $15.00/1M out
system=MASTER_2500_TOKEN_PROMPT,
prompt=f"Context: {context_docs}\nUser: {user_query}",
max_tokens=600
)
# ✅ GOOD: A sub-100ms small model classifies complexity using 200 tokens.
# 75% of routine tasks stay on the fast tier; only 25% escalate to the frontier model.
def handle_user_request_routed(user_query: str, context_docs: str):
# Step 1: Ultra-cheap classification (200 input tokens, 5 output tokens)
route = llm_client.generate(
model="fast-mini-model", # $0.20/1M in, $0.80/1M out
system="Classify query complexity. Return ONLY 'ROUTINE' (lookup, extraction, FAQ) or 'COMPLEX' (multi-step debugging, legal/policy synthesis).",
prompt=user_query,
max_tokens=5
).text.strip()
# Step 2a: 75% of traffic resolves on the small model with a lean prompt
if route == "ROUTINE":
return llm_client.generate(
model="fast-mini-model",
system=LEAN_400_TOKEN_PROMPT,
prompt=f"Context: {context_docs}\nQuery: {user_query}",
max_tokens=250
)
# Step 2b: Only the 25% complex queries consume frontier model compute
return llm_client.generate(
model="frontier-reasoning-model",
system=MASTER_2500_TOKEN_PROMPT,
prompt=f"Context: {context_docs}\nQuery: {user_query}",
max_tokens=600
)
The Economics (100,000 Requests/Month):
- Before (100% Frontier): 100,000 requests × (2,500 input + 400 output) = $1,350.00 / month.
- After (Tiered Routing):
- Router Overhead (100k calls): 200 input + 10 output on Small Model = $4.80
- Routine Tier (75k calls): 1,200 input + 200 output on Small Model = $30.00
- Complex Tier (25k calls): 2,500 input + 400 output on Frontier Model = $337.50
- Total Routed Spend: $372.30 / month (72.4% savings).