GT logo
Contact Us

Claude is Expensive? Stop Burning Cash on Tokens with These 12 Brutal Optimizations

Claude is Expensive? Stop Burning Cash on Tokens with These 12 Brutal Optimizations

The Token Problem Nobody Talks About

Let me tell you what I see in almost every AI engineering team:

  1. Prompts that read like novels when they should be haikus
  2. Entire databases dumped into context windows "just in case"
  3. No caching. Zero. Every request re-sends everything.
  4. Developers treating tokens like they are free

If your Claude bill looks like a mortgage payment, this post is for you. I am going to show you exactly how we cut token usage by 73% for one client — without dumbing down the intelligence.

This is not a gentle guide. It is a tactical manual.

First, Let Us Do the Math

Claude 3.5 Sonnet pricing:

  • $3.00 per million input tokens
  • $15.00 per million output tokens

Scenario: 500 users, 50 API calls per user per day, 2000 tokens per call input, 500 tokens per call output

  • Daily: 500 × 50 × 2,500 = 62,500,000 tokens = $281.25/day
  • Monthly: $8,437.50/month

Now imagine you optimize:

  • Compress prompts (savings: 40%)
  • Implement semantic caching (savings: 60% of redundant calls)
  • Use Haiku for simple queries (savings: 90% on certain tasks)

Optimized monthly: $2,100/month

That is $6,337 saved every month. For one app. Scale that across your organization.

Optimization #1: The Prompt Compression Killshot

Stop writing prompts like this:

You are a helpful customer service assistant for Acme Corp. We sell widgets. 
Our return policy is 30 days. Customers can return items if they have
the receipt. We offer full refunds. If someone does not have a receipt
we can still help them. Here is our contact information...
[500 more words of obvious stuff]

Write like this:

ROLE: Acme customer service (widgets)
RULES: 30-day returns, receipt required for refund, non-receipt=store credit
TASK: {user_query}

Result: 85% token reduction on system prompts. Zero intelligence loss.

The Compression Patterns That Actually Work

1. Acronym Stacking Instead of: "We want you to analyze the sentiment of this text and tell us if it is positive, negative, or neutral"

Write: "Sentiment: {text} → pos/neg/neu"

2. Example Compression Instead of:

Example 1: Input: "I love this product" Output: positive
Example 2: Input: "Terrible experience" Output: negative
Example 3: Input: "It was okay I guess" Output: neutral

Write:

EXAMPLES: "love"→pos | "terrible"→neg | "okay"→neu

3. Implicit Context If you are building a legal document analyzer, do not say "This is a legal document analyzer." Just format your input to signal it:

[DRAFT CONTRACT]
Party A: ACME Inc.
Party B: Beta LLC
Terms: ...
[/DRAFT CONTRACT]
LEGAL ANALYSIS REQUESTED:

Optimization #2: Semantic Caching — The Secret Weapon

This is the single biggest win most teams are leaving on the table.

What Most Teams Do

Every time a user asks "How do I reset my password?", your API:

  1. Sends the entire conversation history
  2. Sends the full system prompt
  3. Pays for all those tokens again

What Smart Teams Do

Implement semantic caching:

// Pseudocode — actual implementation varies by stack
async function queryWithCache(userMessage: string, history: Message[]) {
  // Hash the input
  const queryHash = sha256(userMessage + summarize(history));

  // Check cache
  const cached = await cache.get(queryHash);
  if (cached && isFresh(cached, 1 hour)) {
    return cached.response; // Zero Claude API call
  }

  // Cache miss — call Claude
  const response = await callClaude(userMessage, history);

  // Store in cache
  await cache.set(queryHash, {
    response,
    timestamp: Date.now()
  });

  return response;
}

Real Results

A SaaS support chatbot we built:

  • 73% cache hit rate
  • Token bill dropped from $12K/month to $3.2K/month
  • Response time dropped from 2.1s to 47ms for cached queries

The Catch

Semantic caching requires:

  1. A vector database or embedding store (Pinecone, Weaviate, Qdrant)
  2. Similarity threshold tuning (too loose = bad responses, too strict = low hit rate)
  3. Cache invalidation strategy (product info changes → invalidate)

Optimization #3: Model Routing — Use the Right Hammer

You do not need Claude Opus for every task.

Task Model Cost per 1M tokens Savings vs Sonnet
Simple Q&A Haiku $0.25 99%
Code completion Sonnet $3.00 baseline
Complex reasoning Opus $15.00 -400%

Routing Strategies

1. Intent Detection

function routeQuery(input: string): 'simple' | 'moderate' | 'complex' {
  const simpleTriggers = ['what is', 'how to', 'where is', 'when does'];
  const complexTriggers = ['analyze', 'design', 'compare', 'evaluate', 'strategic'];

  // Use fast keyword matching or a cheap classifier
  if (simpleTriggers.some(t => input.toLowerCase().includes(t))) {
    return 'simple';
  }
  if (complexTriggers.some(t => input.toLowerCase().includes(t))) {
    return 'complex';
  }
  return 'moderate';
}

2. Confidence-Based Routing

// First try fast model
const fastResponse = await callHaiku(userQuery);
if (fastResponse.confidence > 0.85) {
  return fastResponse; // Good enough
}
// Fall back to smarter model for hard queries
return await callSonnet(userQuery, { context: fastResponse.failure_reasons });

3. Cascade Architecture

User Query
    ↓
Intent Detection
    ↓
┌─────────────┬──────────────┐
↓ Simple      ↓ Moderate     ↓ Complex
Haiku         Sonnet         Opus
($0.25/1M)    ($3/1M)        ($15/1M)

Optimization #4: Context Truncation Smarter Than naive

Most teams just chop the oldest messages when context window fills up. That is naive.

Strategy 1: Semantic Summarization

Instead of dropping oldest messages:

async function smartTruncateHistory(history: Message[], maxTokens: number) {
  const currentTokens = countTokens(history);
  if (currentTokens <= maxTokens) return history;

  // Find the conversation midpoint
  const midpoint = Math.floor(history.length / 2);

  // Summarize the first half
  const summaryPrompt = `Summarize this conversation in 50 words: ${history.slice(0, midpoint).map(m => m.content).join(' ')}`;
  const summary = await callHaiku(summaryPrompt); // Cheap model for summarization

  // Return summarized history + recent messages
  return [
    { role: 'system', content: `Earlier conversation summary: ${summary}` },
    ...history.slice(midpoint)
  ];
}

Strategy 2: Importance Weighting

Not all messages are equal. Prioritize:

  1. Last 5 exchanges — Critical for coherence
  2. User preferences — Long-term context
  3. System instructions — Non-negotiable
  4. Older闲聊 — Often filler
function weightedContext(messages: Message[]): Message[] {
  return messages
    .map((msg, idx) => ({
      msg,
      weight: msg.role === 'user' ? 2 :
              msg.role === 'system' ? 3 :
              idx > messages.length - 10 ? 1.5 : 0.5
    }))
    .sort((a, b) => b.weight - a.weight)
    .slice(0, MAX_CONTEXT)
    .map(x => x.msg);
}

Strategy 3: Dynamic Context Windows

// Small queries get minimal context
if (userQuery.length < 50) {
  // Only last 2 exchanges
  context = recentMessages.slice(-4);
} else if (userQuery.length < 200) {
  // Last 10 exchanges
  context = recentMessages.slice(-20);
} else {
  // Full context with summarization
  context = await smartTruncateHistory(fullHistory, MAX_TOKENS);
}

Optimization #5: Batch Processing for Bulk Tasks

When you need to analyze 10,000 documents, do not loop 10,000 times.

// BAD: $150 in API calls
for (const doc of documents) {
  await callClaude(`Analyze: ${doc}`); // 10,000 calls
}

// GOOD: $3 in API calls
const batchPrompt = documents
  .map((doc, i) => `${i + 1}. ${truncate(doc, 200)}`)
  .join('\n');

const results = await callClaude(`Analyze each and return JSON:
${batchPrompt}`);

// Parse results
return JSON.parse(results);

Rule of thumb: If you are looping an AI call, you are doing it wrong.

Optimization #6: The $0 Tool Pattern

Before sending anything to Claude, ask:

Can a rule-based system handle this?

  • Email validation? Regex. (saves $0.0001 per query)
  • profanity filtering? Word list. (saves $0.0001 per query)
  • basic categorization? Decision tree. (saves $0.001 per query)
  • Format transformation? String manipulation. (saves $0.0001 per query)

Claude costs $3/million tokens. A simple regex costs $0.0000001.

Optimization #7: Temperature and Token Optimization

Max Tokens is a Budget Knob

Setting max_tokens: 100 when you only need a one-liner is burning money.

// Adaptive max tokens based on query type
function getMaxTokens(query: string): number {
  if (query.includes('list')) return 150;      // Short lists
  if (query.includes('explain')) return 500;  // Moderate explanations
  if (query.includes('analyze')) return 1000; // Deep analysis
  return 300; // Default
}

Temperature as a Cost Lever

Use Case Temperature Why
Code completion 0.0-0.2 Deterministic, consistent
Factual Q&A 0.0-0.3 Accurate, focused
Creative writing 0.7-0.9 Varied, interesting
Brainstorming 0.8-1.0 Wild ideas welcome

Lower temperature = faster token generation = lower output costs.

Optimization #8: Prompt Chaining for Complex Tasks

Instead of one monolithic call:

INPUT: 50 page document
↓
CLAUDE: "Summarize this document" → 2000 tokens output
↓
CLAUDE: "Extract key insights" → 500 tokens output
↓
CLAUDE: "Generate action items" → 300 tokens output

Do this:

STEP 1: claude haiku (cheap)
"Give me 3 bullet points summarizing this: [doc truncated to 1000 tokens]"
Output: 100 tokens

STEP 2: haiku
"From these bullets: [bullets], what actions are most urgent?"
Output: 80 tokens

Total: 1,280 tokens vs 2,800 tokens. 54% savings.

Optimization #9: The Embeddings-First Pattern

Before sending text to Claude, embed it and check similarity.

async function ragQuery(userQuery: string, knowledgeBase: Document[]) {
  // Embed the user query
  const queryEmbedding = await embed(userQuery);

  // Find relevant chunks (cheap vector operation)
  const relevantChunks = await vectorStore.similaritySearch(
    queryEmbedding,
    { topK: 5 }
  );

  // Only send relevant chunks to Claude
  const context = relevantChunks
    .map(c => c.text)
    .join('\n\n');

  return callClaude(`
    Context: ${context}
    Question: ${userQuery}
  `);
}

Result: Instead of sending 50,000 tokens (entire document), you send 2,000 tokens (relevant chunks).

Optimization #10: Response Streaming with Early Stopping

If you stream responses, you can stop early when you have enough.

let fullResponse = '';
for await (const token of streamResponse(prompt)) {
  fullResponse += token;

  // Check if we have enough
  if (isComplete(fullResponse) && !isInMiddleOfSentence(fullResponse)) {
    stream.controller.abort(); // Stop generating
    break;
  }
}

Optimization #11: The System Prompt Optimization

System prompts are loaded every single call. Minimize them.

BAD:

You are a helpful, friendly, professional AI assistant named Claude.
You work for ACME Corp. You help customers with their questions.
You are knowledgeable about our products which include widgets,
gadgets, and doohickeys. You should be patient and thorough...
[300 more words]

GOOD:

ACME bot | Products: widgets, gadgets | Rules: patient, thorough | Mode: {user_preference}

Even better: Move system-level instructions to the first user message when possible, or use few-shot prompting.

Optimization #12: Token Counting Before API Calls

This sounds obvious. Nobody does it.

async function safeCallClaude(messages: Message[], maxBudget: number) {
  const tokenCount = await countTokens(messages);

  if (tokenCount > maxBudget) {
    throw new Error(`Would exceed budget: ${tokenCount} > ${maxBudget} tokens`);
  }

  return callClaude(messages);
}

// Usage
const messages = buildContext(userQuery, history);
await safeCallClaude(messages, 100000); // Hard limit

Fail fast, do not burn tokens on oversized payloads.

The Audit Framework

Implement this before/after measurement:

// Wrap every Claude call
const callLog = [];
async function loggedCallClaude(...args) {
  const before = Date.now();
  const beforeTokens = await countTokens(args[0]);
  const result = await callClaude(...args);
  const afterTokens = countTokens(result);

  callLog.push({
    timestamp: before,
    inputTokens: beforeTokens,
    outputTokens: afterTokens,
    cost: (beforeTokens * 0.000003) + (afterTokens * 0.000015),
    // Add metadata: user_id, query_type, etc.
  });

  return result;
}

// Dashboard: sum(callLog.map(x => x.cost))
// Alerts: if dailyCost > threshold, pag someone

The Harsh Reality

If you are not doing these optimizations, you are throwing money away.

Optimization Typical Savings Implementation Effort
Prompt compression 40-70% 1 day
Semantic caching 50-80% 1 week
Model routing 30-60% 2-3 days
Context truncation 20-50% 2 days
Batch processing 40-90% 1 day
RAG (embeddings-first) 60-95% 1-2 weeks

Most teams implementing even half of these see 60-80% cost reductions.

Your Action Items

Today:

  1. Add token counting to your API calls
  2. Calculate your current cost per query

This Week:

  1. Compress your system prompts by 50%
  2. Implement basic caching for repeated queries
  3. Add Haiku as a fallback for simple queries

This Month:

  1. Build a proper RAG pipeline
  2. Implement model routing
  3. Build a cost dashboard

The Bottom Line

Claude is not expensive. Your token usage is expensive.

The teams winning on AI costs are not using weaker models or dumbing down their prompts. They are being intentional about what they send to the API, caching aggressively, routing intelligently, and measuring constantly.

You can do the same.

Want help implementing these optimizations for your specific use case? Talk to us.

[[Move to top]]