Token Usage and Cost Optimization
Independent educational resource, not an official Anthropic course. Facts about the API, prices and limits were checked against Anthropic's documentation on 15 November 2026 and the code was run against a local mock of the API, not the live service. Check the linked official pages before relying on a number, and test with your own key.
With a hosted model, every feature has a price per use, and that price is set by tokens. Developers who measure tokens from day one build features that are cheap by design; those who do not meet the invoice later. This lesson shows where to read usage, how to price it, and the levers that actually reduce cost, with tested code.
Learning objectives
- Read every usage field and know which are billed and how.
- Compute the cost of a request including cache reads and writes.
- Estimate input cost before sending, with the token counting endpoint.
- Choose among model choice, shorter prompts, caching and batching.
- Add a budget guard to your code.
Prerequisites
What is in usage
| Field | Meaning |
input_tokens | Input tokens after the last cache breakpoint. With no caching, this is the whole prompt. |
output_tokens | Tokens the model generated. |
cache_creation_input_tokens | Tokens written to the prompt cache on this request. |
cache_read_input_tokens | Tokens read from the cache. |
The documentation gives the formula for total input when caching is used: total_input_tokens = cache_read_input_tokens + cache_creation_input_tokens + input_tokens. For example, with a 200,000-token cached document and a 50-token question, input_tokens shows 50, even though the total input is 200,050.
Prices that matter (checked 15 November 2026)
| Model | Input | 5-minute cache write | Cache read | Output |
| Claude Sonnet 5.5 | $2 / MTok | $2.50 / MTok | $0.10 / MTok | $10 / MTok |
| Claude Opus 5.5 | $4 / MTok | $5 / MTok | $0.20 / MTok | $20 / MTok |
The pricing page also lists a 1-hour cache write at a higher rate, rows for other models, and Haiku 5.5 rates that depend on conditions described on that page. The Batch API gives a 50% discount on input and output. Prices change; the code below keeps them in one dictionary you update in one place.
Step by step: track cost in code
This module adds up the cost of each call, including cache reads and writes, stops when a budget is reached, and estimates a request's input cost before you send it:
from dataclasses import dataclass, field
import anthropic
# USD per million tokens, from Anthropic's pricing page (checked 15 Nov 2026). Update when prices change.
# cache_write is the 5-minute cache write price; cache_read is the cache hit price.
PRICES = {
"claude-sonnet-5-5": {"input": 2.00, "cache_write": 2.50, "cache_read": 0.10, "output": 10.00},
"claude-opus-5-5": {"input": 4.00, "cache_write": 5.00, "cache_read": 0.20, "output": 20.00},
}
@dataclass
class CostTracker:
"""Adds up the cost of every call. input_tokens is only the part of the prompt after the last
cache breakpoint, so cache reads and writes are priced separately from it."""
input_tokens: int = 0
output_tokens: int = 0
cache_read_tokens: int = 0
cache_write_tokens: int = 0
log: list = field(default_factory=list)
def add(self, model: str, usage) -> float:
cache_read = getattr(usage, "cache_read_input_tokens", 0) or 0
cache_write = getattr(usage, "cache_creation_input_tokens", 0) or 0
p = PRICES[model]
cost = (
usage.input_tokens * p["input"]
+ cache_write * p["cache_write"]
+ cache_read * p["cache_read"]
+ usage.output_tokens * p["output"]
) / 1_000_000
self.input_tokens += usage.input_tokens
self.output_tokens += usage.output_tokens
self.cache_read_tokens += cache_read
self.cache_write_tokens += cache_write
self.log.append((model, cost))
return cost
@property
def total(self) -> float:
return sum(c for _, c in self.log)
class BudgetExceeded(RuntimeError):
pass
def guarded_ask(client: anthropic.Anthropic, tracker: CostTracker, budget_usd: float, **kwargs):
"""Stop before spending more than budget_usd in this process."""
if tracker.total >= budget_usd:
raise BudgetExceeded(f"Budget of ${budget_usd:.2f} reached (spent ${tracker.total:.4f}).")
message = client.messages.create(**kwargs)
tracker.add(kwargs["model"], message.usage)
return message
def estimate_input_cost(client: anthropic.Anthropic, model: str, **kwargs) -> tuple[int, float]:
"""Count tokens before sending. The endpoint is free, but the count is an estimate."""
count = client.messages.count_tokens(model=model, **kwargs).input_tokens
return count, count * PRICES[model]["input"] / 1_000_000
Tested against a mock API: a call with 2,000 input and 500 output tokens on Sonnet 5.5 cost $0.009, a call with 100 input tokens and 10,000 cache-read tokens cost $0.0012, and the guard refused a third call once the $0.005 budget had been passed. The token counting call returned 14 tokens for a short prompt.
Counting tokens before you send
The token counting endpoint (POST /v1/messages/count_tokens) accepts the same inputs as a normal request (system prompt, tools, images, PDFs) and returns input_tokens. It is free, with its own rate limits separate from message creation (5,000 requests per minute on the Start tier on the page checked). Three cautions from the documentation:
- The count is an estimate; the real number can differ slightly, and you are not billed for tokens Anthropic adds for system optimisation.
- Models from Claude Opus 4.7 onward use a newer tokenizer that produces roughly 30% more tokens for the same text than earlier models. Recount prompts against the model you will use.
- It does not use prompt caching, and it does not accept server tools, the MCP connector, or images and documents referenced by URL or file ID (send those as base64 to count them).
The levers that reduce cost
| Lever | What it does | Watch out for |
| Right-size the model | Use a small, fast model for classification and extraction; reserve larger models for hard cases (lesson 1.8). | Test quality on your own examples first. |
| Shorten prompts | Cut repeated boilerplate and trim chat history. | Do not trim away context the answer needs. |
| Limit output | Ask for short answers; set a realistic max_tokens. Output costs five times input on the current models. | Too low a limit truncates answers. |
| Prompt caching | Cache reads cost a small fraction of base input, and cached tokens do not count toward your input-tokens-per-minute limit. | Only repeated prefixes benefit; cache writes cost a little more than normal input. |
| Batch API | 50% off input and output for work that can wait. | Asynchronous: not for interactive features. |
| Do not call at all | Cache answers you already have; skip the model for rules you can code. | Stale answers; keep expiry rules. |
Setting a higher max_tokens does not change your output-tokens-per-minute rate limit calculation, because that limit counts the tokens actually generated, but it does let a runaway answer cost more. Prompt caching has its own request parameters and rules; read the prompt caching guide before adopting it.
Real-world use case (illustrative scenario)
This scenario is an invented example to show how the ideas fit together. It is not a case study and its details are not measured results.
A support assistant answers from a 40,000-token policy handbook. Sent fresh on every question, 1,000 questions a day is 40 million input tokens. Caching the handbook as a stable prefix means most of those tokens are priced as cache reads rather than full input. The team added the cost tracker, a per-day budget guard that switches the feature to "contact us" when reached, and a weekly report of cost per feature. The first report showed one background job costing more than the chat feature, which they would never have found without logging usage.
Common errors and solutions
| Problem | Cause | Fix |
| Cost estimates look far too low | Using input_tokens only when caching is on. | Add cache read and write tokens. |
| Estimates off after upgrading models | New tokenizer yields about 30% more tokens. | Recount with the new model. |
| Token counting returns an error | Server tools, MCP connector or URL/file-sourced images. | Count without them, or send images as base64. |
| Monthly bill surprises you | No per-feature tracking or limits. | Log usage per call; set a Console spend limit (lesson 2.1). |
Security considerations
- Usage logs reveal behaviour (who asked how much). Treat them as business data.
- Cap per-user usage so one abusive account cannot spend your budget; combine application limits with your Console spend limit.
- Do not log prompts to compute cost; log counts.
Performance and cost considerations
Cost and latency usually fall together: fewer tokens in and out means a faster, cheaper request. Measure both per feature, and change one lever at a time so you know what worked.
Key takeaways
- Cost comes from
usage: input, output, and cache reads and writes priced differently.
- Track cost in code and add a budget guard; do not wait for the invoice.
- Token counting is free and an estimate; recount when the model changes.
- The main levers: model size, shorter prompts, shorter outputs, caching and batching.
Lesson recap: output costs more than input, cache reads cost least, and six levers cut the bill.
Knowledge check
- A response shows
input_tokens: 50 and cache_read_input_tokens: 200000. What is the total input?
- Cost of 2,000 input and 500 output tokens on Claude Opus 5.5?
- Why recount prompts after moving to a newer model?
- Which lever fits a nightly job that can run for hours?
- Does the token counting endpoint cost money?
Answers and explanations
- 200,050 tokens: the sum of cache read, cache creation and uncached input tokens.
- 2,000 × $4 / 1M = $0.008 plus 500 × $20 / 1M = $0.010, total $0.018.
- Models from Claude Opus 4.7 onward use a tokenizer that produces about 30% more tokens for the same text, so old counts underestimate.
- The Batch API, which gives a 50% discount for asynchronous work.
- No. It is free, with its own rate limits.
Official references and further reading
Related tutorials