Claude API cost optimization: cut your bill 40-70% in production

App DevelopmentJul 1, 2026 · 10 min read

Short answer

Claude API costs can be reduced 40-70% using five strategies: prompt caching (90% discount on cached input tokens), model routing (Haiku for classification, Sonnet for reasoning, Opus for complex tasks), Batch API for non-real-time workloads (50% discount), output length control, and context pruning. RaftLabs applies these patterns across 100+ AI products. A production system handling 100,000 calls/day can drop monthly spend from $15,000+ to $4,500-$9,000.

Key Takeaways

  • Prompt caching gives 90% discount on cached input tokens. Apply to system prompts above 1,024 tokens immediately.
  • Model routing from Opus to Sonnet cuts token cost by 80% with no quality loss on most tasks
  • Batch API gives 50% discount for non-latency-sensitive workloads: document processing, nightly jobs, bulk analysis
  • Output length instructions reduce token spend 20-40% on verbose models
  • Context pruning prevents conversation history from compounding token costs across multi-turn sessions

Claude API bills compound fast. A system handling 100,000 calls per day can hit $15,000/month in token costs before the team has even looked at the invoice. Most of that spend is recoverable. Teams going live with a Claude integration service for the first time almost always leave 40-60% on the table. Not from bad code, but from skipping five techniques that pay for themselves immediately.

This article covers those five techniques. Each one includes the exact API parameters, a savings calculation you can apply to your own numbers, and the tradeoffs worth knowing before you ship.

Claude API pricing in 2026

Before optimizing, get the numbers right. Here is the current pricing table.

Anthropic's official pricing page is the only source to trust for these numbers. They change with model releases, and any third-party summary is typically 1 to 2 model generations behind. The scale of this cost category is growing fast: according to Gartner, worldwide end-user spending on generative AI models reached $14.2 billion in 2025, up 148% from $5.7 billion in 2024 — which means token cost optimization is becoming a material line item for any team running AI in production.

ModelInput ($/MTok)Output ($/MTok)
Claude Opus 4$15.00$75.00
Claude Sonnet 4.6$3.00$15.00
Claude Haiku 4.5$0.80$4.00

Cache pricing applies on top:

Cache operationPrice
Cache write25% of base input price
Cache read10% of base input price
Batch API50% discount on all models

The output multiplier is the thing most teams underestimate. Sonnet output costs 5x more per token than Sonnet input. Opus output costs 5x more than Opus input. A system that generates long outputs on Opus is burning money at a rate that surprises people when they first see the bill broken down.

The Batch API discount applies universally. 50% off Haiku is modest. 50% off Opus is massive.

Strategy 1: Prompt caching

Prompt caching has the highest ROI of any technique here. For most production systems, it alone recovers 30-50% of monthly spend.

How it works

You send a cache_control parameter on the portion of your prompt you want Anthropic to cache. On the first call, Anthropic processes that content at 1.25x the standard input price (the cache write cost). On every subsequent call within the cache window, Anthropic serves that content from cache at 0.1x the standard input price. That is a 90% discount on the cached portion.

Cache entries live for 5 minutes by default. Each request that hits the cache also extends the TTL by 5 minutes. You can also set explicit TTLs up to 1 hour.

When to use it

Apply caching whenever your prompt has a stable prefix that repeats across requests. The main case: system prompts. If you send a 2,000-token system prompt with every API call, caching that system prompt is free money.

The minimum cacheable prefix is 1,024 tokens on Sonnet models. Shorter prefixes silently do not cache. You pay the write cost but get nothing back.

Code pattern

const response = await client.messages.create({
  model: "claude-sonnet-4-6",
  max_tokens: 2048,
  system: [
    {
      type: "text",
      text: YOUR_LARGE_SYSTEM_PROMPT, // 2,000+ tokens
      cache_control: { type: "ephemeral" },
    },
  ],
  messages: [{ role: "user", content: userMessage }],
});

The cache_control block goes on the last content block you want to include in the cached prefix. Everything before it gets cached together.

Real savings calculation

System prompt: 2,000 tokens. Request volume: 10,000 calls/day. Model: Sonnet 4.6 at $3/MTok input.

Without caching: 2,000 tokens x 10,000 calls x $3/MTok = $60/day on system prompt input alone.

With caching: cache write on first call = 2,000 x $0.75/MTok = $0.0015. Cache reads on 9,999 subsequent calls = 2,000 x 9,999 x $0.30/MTok = $5.99/day.

Daily savings: $54/day. Monthly: $1,620/month recovered from a single system prompt.

Verify cache hits by checking response.usage.cache_read_input_tokens. If that number is zero after the first call, you have a cache invalidation problem. Usually a timestamp or UUID embedded in the system prompt is the cause.

Strategy 2: Model routing

Not every task needs the same model. Routing by task complexity is the second biggest lever.

The routing decision

Claude Opus 4 costs 18.75x more per input token than Haiku 4.5. It costs 5x more than Sonnet 4.6. The goal is to send each task to the cheapest model that can handle it reliably.

Task typeRight modelReason
Classification (positive/negative, category assignment)Haiku 4.5Low reasoning demand. Haiku handles it accurately.
Structured extraction (pull fields from a document)Haiku 4.5 or Sonnet 4.6Haiku for simple schemas, Sonnet when field relationships are complex.
SummarizationSonnet 4.6Requires coherence over length. Haiku loses quality on long documents.
Q&A over retrieved contextSonnet 4.6Reasoning over provided context. Sonnet is accurate and fast.
Complex multi-step reasoningSonnet 4.6 or Opus 4Only use Opus when reasoning chains are long and errors are costly.
Code generation (boilerplate, tests)Sonnet 4.6Sonnet handles most coding tasks. Reserve Opus for architecture decisions.
Code review or security auditOpus 4High stakes. Wrong answers here cost more than the model difference.

Implementation pattern

A simple router function works in most codebases:

function selectModel(taskType: string, inputLength: number): string {
  if (taskType === "classification" || taskType === "extraction_simple") {
    return "claude-haiku-4-5";
  }
  if (taskType === "extraction_complex" || taskType === "summarization") {
    return inputLength > 50_000
      ? "claude-sonnet-4-6"
      : "claude-haiku-4-5";
  }
  if (taskType === "reasoning" || taskType === "code_generation") {
    return "claude-sonnet-4-6";
  }
  if (taskType === "security_audit" || taskType === "architecture_review") {
    return "claude-opus-4-latest";
  }
  return "claude-sonnet-4-6"; // default
}

Real savings calculation

A document processing pipeline runs 50,000 calls/day. Before routing: all calls go to Sonnet 4.6.

After routing audit: 60% are simple classification (route to Haiku), 30% are extraction (route to Haiku for simple, Sonnet for complex), 10% require reasoning (stay on Sonnet).

Assume 1,500 tokens input + 500 tokens output per call on average.

Before routing: 50,000 x 2,000 tokens x blended $4/MTok = $400/day.

After routing (approximate): 30,000 Haiku calls at blended $1.2/MTok + 15,000 Haiku extraction at $1.2/MTok + 5,000 Sonnet calls at blended $4/MTok = $36 + $18 + $20 = $74/day.

Monthly savings from routing alone: approximately $9,780/month.

Strategy 3: Batch API for non-real-time workloads

The Batch API gives a flat 50% discount on every request. The tradeoff: jobs complete within 24 hours, not in seconds.

What qualifies

A workload is a good Batch API candidate when:

  • No user is waiting on the response in real time

  • Results can be processed asynchronously

  • The job can be structured as discrete independent requests

Examples: nightly content generation, document classification pipelines, bulk data extraction, email analysis queues, report generation jobs.

Code pattern

import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic();

// Create a batch
const batch = await client.messages.batches.create({
  requests: documents.map((doc, i) => ({
    custom_id: `doc-${i}`,
    params: {
      model: "claude-sonnet-4-6",
      max_tokens: 1024,
      messages: [
        {
          role: "user",
          content: `Extract the key entities from this document:\n\n${doc.text}`,
        },
      ],
    },
  })),
});

// Poll for completion
let result = await client.messages.batches.retrieve(batch.id);
while (result.processing_status !== "ended") {
  await new Promise((r) => setTimeout(r, 60_000));
  result = await client.messages.batches.retrieve(batch.id);
}

// Retrieve results
for await (const item of await client.messages.batches.results(batch.id)) {
  if (item.result.type === "succeeded") {
    processResult(item.custom_id, item.result.message);
  }
}

Real savings calculation

A nightly document analysis job processes 20,000 documents. Each call averages 3,000 input tokens and 800 output tokens on Sonnet 4.6.

Standard pricing: (3,000 x $3/MTok + 800 x $15/MTok) x 20,000 = ($9 + $12) x 20,000 = $420/night.

With Batch API: same job at 50% discount = $210/night.

Monthly savings: $6,300/month from one scheduled job with zero code complexity added. Just a different API endpoint.

Strategy 4: Output length control

Claude models are verbose by default. Left unconstrained, they add context, disclaimers, formatting explanations, and closing summaries that the application discards immediately. This bloat appears on every call and compounds at scale.

The fix

Explicit length instructions in the system prompt reduce output tokens 20-40% on most tasks. Combine this with a tight max_tokens ceiling.

Before (no length instruction):

System: You are a helpful assistant that extracts entities from documents.

Typical output for an entity extraction task: 800 tokens. Includes a summary paragraph at the start, a JSON block, and a closing explanation of what was extracted and why.

After (explicit length instruction):

System: You are an entity extraction assistant.
Return only a JSON object with the extracted entities. No explanation before or after.
If no entities are found, return an empty object: {}

Typical output for the same task: 120 tokens. Just the JSON.

Token comparison

On Sonnet 4.6, 800 output tokens costs 800 x $15/MTok = $0.012 per call. At 50,000 calls/day, that is $600/day in output tokens.

After compression to 120 tokens per call: $90/day. Monthly delta: $15,300/month.

This is the easiest win on the list. It requires no infrastructure change. Add one line to your system prompt.

Additional techniques

  • Set max_tokens to a realistic ceiling. If your application never needs more than 500 output tokens, set max_tokens: 500. Uncapped calls generate more tokens than necessary.

  • Use JSON output format (output_config: { format: { type: "json_schema" } }) for structured extraction tasks. It eliminates the prose wrapper entirely.

  • For classification tasks, instruct the model to return only the label: "Return only the category name. No other text."

Strategy 5: Context window management

Multi-turn conversations accumulate tokens fast. Each turn adds to the history sent on the next call. A conversation with 20 turns and 500 tokens per turn sends 10,000 tokens of history on call 21, before the new message.

The problem

Most teams send the full conversation history on every call. For support chat or long document workflows, this compounds to thousands of tokens of context that the model processed two hours ago and no longer needs.

Rolling window pattern

For most chat applications, only the last N turns matter. A rolling window keeps history bounded:

const MAX_HISTORY_TURNS = 10;

function buildMessages(
  history: Message[],
  newMessage: string
): Anthropic.MessageParam[] {
  // Keep only the last N turns (each turn = 1 user + 1 assistant)
  const recentHistory = history.slice(-(MAX_HISTORY_TURNS * 2));

  return [
    ...recentHistory,
    { role: "user", content: newMessage },
  ];
}

Summarization for long sessions

When history must be preserved (multi-session support tickets, ongoing research), replace old turns with a compressed summary:

async function compressHistory(
  history: Message[]
): Promise<Message[]> {
  if (history.length < 20) return history;

  const olderTurns = history.slice(0, -10);
  const recentTurns = history.slice(-10);

  const summary = await client.messages.create({
    model: "claude-haiku-4-5", // cheapest model for summarization
    max_tokens: 512,
    messages: [
      {
        role: "user",
        content: `Summarize this conversation history in 3-5 bullet points. Include key decisions, facts established, and current task status.\n\n${JSON.stringify(olderTurns)}`,
      },
    ],
  });

  const summaryMessage: Message = {
    role: "user",
    content: `[Earlier conversation summary: ${summary.content[0].text}]`,
  };

  return [summaryMessage, ...recentTurns];
}

This uses Haiku (the cheapest model) to compress older history, then sends the compressed version on future calls.

Token savings from pruning

A support chat session averages 30 turns. Without pruning: call 30 sends approximately 29 prior turns at ~400 tokens each = 11,600 tokens of history per call.

With a 10-turn window: call 30 sends 10 prior turns = ~4,000 tokens of history.

On Sonnet 4.6: 7,600 fewer input tokens x $3/MTok = $0.0228 saved per call-30 equivalent. At 10,000 conversations/day reaching turn 30: $228/day in context savings.

Putting it together: cost reduction calculator

Here is a worked example for a production system. The system handles 100,000 API calls/day. It is a document processing and chat application using Sonnet 4.6.

Before optimization

Cost categoryDaily spend
System prompt input (2,000 tokens, every call)$600
Document input tokens (avg 3,000 tokens)$900
Output tokens (avg 800 tokens)$1,200
Chat history context (avg 5,000 tokens)$1,500
Total$4,200/day

Monthly: approximately $126,000/month.

After applying all 5 strategies

Strategy appliedDaily spend
System prompt (cached, 10% read cost after first call)$60
Document input (unchanged)$900
Output tokens (compressed to 200 tokens with instructions)$300
Chat history (rolling window, avg 1,500 tokens)$450
40% of document jobs moved to Batch API (50% discount)$180 (vs $360)
Total$1,890/day

Monthly: approximately $56,700/month.

Monthly savings: $69,300. That is a 55% reduction.

The biggest wins came from system prompt caching ($16,200/month), output compression ($27,000/month), and context pruning ($31,500/month). Model routing on the batch jobs added another $5,400/month.

What not to cut

Optimization has limits. Two mistakes consistently cost more than they save.

Do not undersize the model for complex reasoning. A classification task on Haiku costs $0.0002. A complex reasoning task on Haiku that fails, causing a retry on Sonnet, a downstream data error, or a support ticket, costs far more. The model selection table in Strategy 2 is conservative by design. When in doubt, default to Sonnet rather than Haiku for anything with branching logic.

Do not over-compress outputs on high-stakes tasks. A code review that gets truncated misses bugs. A contract extraction that omits edge cases creates liability. Output compression works well for classification, summarization, and structured extraction. It is a bad fit for security audits, legal analysis, or any task where completeness matters more than cost. Know the difference before applying length limits.

Do not remove conversation history for sessions that require it. A rolling window of 10 turns is correct for most support chats. It is wrong for a multi-session research workflow where turn 1 established a constraint that still applies at turn 50. Use the summarization pattern instead of hard truncation when context continuity matters.


If you are building production AI systems on Claude and want a second set of eyes on your architecture, the team at RaftLabs has run this cost optimization playbook across more than 30 Anthropic API integration projects. We review current spend, identify the highest-ROI changes, and build the implementation plan in one session. Talk to us here.

Ask an AI

Get an instant summary of this post from your preferred AI assistant.

Frequently asked questions

Claude Haiku 4.5 at $0.80/MTok input and $4/MTok output is the cheapest. But cheapest is not always lowest total cost. Using Haiku on tasks that require Sonnet-level reasoning causes more retries, longer outputs from incomplete reasoning, and downstream errors that require human correction. All of which cost more than the saved tokens. Route by task complexity, not by price alone.
Prompt caching works by sending a cache_control: {type: ephemeral} flag on the portion of your prompt you want cached. Anthropic caches that content for 5 minutes (extendable with each request). Cached tokens cost 10% of the base input price on read, and 25% to write initially. The breakeven point is any prompt repeated more than 1.4 times within the cache window. For system prompts that repeat on every call, the savings are immediate.
Yes. The Batch API supports Claude Haiku, Sonnet, and Opus. It gives a 50% discount on all models and handles up to 10,000 requests per batch. The tradeoff is latency: batch jobs complete within 24 hours but are not guaranteed to be instant. Use it for document processing, content generation pipelines, nightly analysis jobs, and any workload where the user is not waiting in real time.
Example: a system prompt of 2,000 tokens sent 10,000 times per day costs $24/day in standard input pricing (at Sonnet rates of $3/MTok). With prompt caching, the first call writes the cache ($1.50) and subsequent calls read at 10%: $7.20/day total. That is 70% savings on that input segment alone. For apps with large system prompts sent on every request, caching alone often cuts monthly Claude costs by 30-50%.

Stay on topic

More on LLM engineering