Cost Management
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.
The surprise bill is the most common way an AI feature gets cancelled. It's rarely one big mistake. More often it's a loop that ran longer than expected, a prompt that grew, a model chosen because it was the default or a user who found out your endpoint was free for them. This lesson shows how a request is charged, how to estimate and cap cost before you spend it, and which savings are real. The code has no prices in it on purpose: you supply them from the official pricing page.
What you'll learn
- The parts of a request's cost: uncached input, output, cache writes and reads.
- Computing cost from the usage the API reports.
- Budgets per user and per day that stop spend before it happens.
- The savings levers and their trade-offs.
- The limits the platform itself offers.
Before you start
How a request is charged
Model prices are per million tokens, one price for input and a higher one for output, and they change, so read the current pricing page and put the numbers in configuration (our service refuses to start without them). What stays fairly stable is how the parts combine, from the prompt caching documentation:
- Uncached input (
input_tokens) is charged at the base input price. Note that this field counts only tokens after your last cache breakpoint, not all input. The documentation's formula for total input is cache_read_input_tokens + cache_creation_input_tokens + input_tokens.
- Cache writes cost more than base input: 1.25 times for the default five-minute lifetime and 2 times for the one-hour option.
- Cache reads cost a fraction of the base input price, 0.1 times in the standard case. The page lists model-specific exceptions (some newer models have lower read multipliers), so check your model.
- Output tokens are charged at the output price.
- Batch requests are charged at 50 percent of standard prices, and the multipliers stack with the other modifiers on the pricing page.
Thinking and tools also produce tokens. Extended output from reasoning counts as output, so watch it if you use those features.
The calculator
"""Know what a request costs before the bill arrives. Prices are YOUR input: copy them from the official pricing page."""
import threading
from dataclasses import dataclass, field
from datetime import date
@dataclass(frozen=True)
class Prices:
"""USD per million tokens. The cache multipliers below are the documented standard ones; some models have a
different cache-read multiplier, so check the prompt caching page for yours."""
input_per_mtok: float
output_per_mtok: float
cache_write_5m_mult: float = 1.25
cache_write_1h_mult: float = 2.0
cache_read_mult: float = 0.1
batch_discount: float = 0.5 # batch usage is charged at 50 percent of standard prices
def cost_of(input_tokens: int, output_tokens: int, p: Prices, cache_read: int = 0, cache_write_5m: int = 0,
cache_write_1h: int = 0, batch: bool = False) -> float:
"""`input_tokens` is the uncached part, exactly as the API reports it (tokens after the last cache breakpoint)."""
per_in = p.input_per_mtok / 1_000_000
total = (input_tokens * per_in
+ cache_write_5m * per_in * p.cache_write_5m_mult
+ cache_write_1h * per_in * p.cache_write_1h_mult
+ cache_read * per_in * p.cache_read_mult
+ output_tokens * p.output_per_mtok / 1_000_000)
return total * (p.batch_discount if batch else 1.0)
def worst_case(input_tokens_estimate: int, max_output_tokens: int, p: Prices) -> float:
"""What one call could cost at most, given its max_tokens. Use it before the call, to refuse early."""
return cost_of(input_tokens_estimate, max_output_tokens, p)
def rough_tokens(text: str) -> int:
"""A crude estimate (about four characters per token for English). Use the token counting endpoint for real numbers."""
return max(1, len(text) // 4)
class BudgetExceeded(Exception):
def __init__(self, scope: str):
super().__init__(f"The {scope} budget has been used up.")
self.scope = scope
@dataclass
class Budgets:
daily_total: float
daily_per_user: float
today: callable = date.today
spent_total: float = 0.0
spent_by_user: dict = field(default_factory=dict)
_day: date | None = None
_lock: threading.Lock = field(default_factory=threading.Lock)
def _roll(self) -> None:
d = self.today()
if self._day != d:
self._day, self.spent_total, self.spent_by_user = d, 0.0, {}
def check(self, user: str, expected: float = 0.0) -> None:
"""Raise before spending. `expected` is the worst-case cost of the call about to be made."""
with self._lock:
self._roll()
if self.spent_total + expected > self.daily_total:
raise BudgetExceeded("daily")
if self.spent_by_user.get(user, 0.0) + expected > self.daily_per_user:
raise BudgetExceeded("per-user")
def charge(self, user: str, cost: float) -> None:
with self._lock:
self._roll()
self.spent_total += cost
self.spent_by_user[user] = self.spent_by_user.get(user, 0.0) + cost
def compare_options(requests: int, avg_input: int, avg_output: int, p: Prices, small: Prices | None = None,
cached_prefix: int = 0) -> dict[str, float]:
"""Back-of-envelope monthly comparison. The point is the shape of the savings, not the exact figure."""
base = requests * cost_of(avg_input, avg_output, p)
out = {"baseline": base, "batch": requests * cost_of(avg_input, avg_output, p, batch=True)}
if cached_prefix:
warm = requests * cost_of(avg_input - cached_prefix, avg_output, p, cache_read=cached_prefix)
out["cached_prefix_all_hits"] = warm + cost_of(0, 0, p, cache_write_5m=cached_prefix) # one write, then reads
if small:
out["smaller_model"] = requests * cost_of(avg_input, avg_output, small)
return out
The tests use round example prices (1.00 and 5.00 dollars per million tokens) so the arithmetic is easy to check. They are not real prices:
- One million uncached input tokens costs the input price; a million output tokens costs the output price.
- A million cache-read tokens cost 0.1 of the input price; cache writes cost 1.25 and 2 times.
- Batch halves the total.
Cap cost before spending it
Two ideas make a budget real:
- Worst case first. Before a call you know roughly how big the input is and the largest output you've allowed (
max_tokens), so you can compute the most it could cost. worst_case() does that, and the service refuses the request if the user's remaining allowance couldn't cover it. The token estimate is crude (about four characters per token); for exact counts, the API has a token counting endpoint that we exercised through the SDK against our mock.
- Charge from real usage. After each call the gateway reports actual tokens, the cost function turns them into dollars and
Budgets.charge() records the spend per user and in total. The day rolls over automatically.
Tests cover a user over their daily allowance (scope "per-user"), the whole system over its allowance (scope "daily"), a new day resetting both, and, in the service, a request refused with HTTP 429 and no model call made. Set the per-user allowance from what a normal user needs, not from what you can afford, so one abuser can't consume the shared pool.
The levers, with an honest comparison
To see the shape, we compared monthly cost for 10,000 requests, each with 2,000 input tokens (1,500 of them a stable prefix) and 300 output tokens, using the example prices above and a second example price of 0.20 and 1.00 for a smaller model:
| Approach | Monthly cost (example prices) |
| Baseline | $35.00 |
| Batch (if it can wait) | $17.50 |
| Cached 1,500-token prefix, every request a hit | $21.50 |
| Smaller model, if quality allows | $7.00 |
The numbers come from the compare_options function, so rerun it with your own prices and volumes. The "all hits" cache line is an upper bound. Real hit rates depend on traffic: with a five-minute lifetime, a quiet period lets the cache expire and the next request pays the write price again. Likewise a smaller model is only a saving if your evaluation set says the quality holds up.
- Right-size the model. Use a small model for classification, screening and extraction; save the large one for the hard writing.
- Cap output. Set
max_tokens to what you need. Output tokens cost more than input tokens.
- Trim input. Don't send the whole thread when the last three messages will do. Don't send tools you won't use.
- Cache stable prefixes (lesson 8.9) and monitor the hit rate.
- Batch what can wait, including evaluation runs.
- Don't pay twice for the same answer. Use the response cache for non-personal repeated questions.
- Cap repairs and loops. Each repair doubles a request's cost, and an agent loop multiplies it, so keep the limits from Module 6.
Platform-side limits
You aren't limited to your own code. From the rate limits page:
- Spend limits. Each usage tier has a monthly spend cap, and you can set your own lower limit in the Console. When you reach a limit you set, requests return HTTP 400 (
invalid_request_error) with a message saying when access resumes. When you reach your tier's cap, requests return 429 with no retry-after, until the next month or a tier increase.
- Workspaces. You can set custom spend and rate limits per workspace, which keeps an experiment or a single service from using everything. Organisation-wide limits always apply.
- Separate keys and workspaces for development and production make "who spent this?" answerable.
Treat these as the outer wall and your per-user budgets as the inner ones.
Watching cost
Record cost per request in your metrics (lesson 8.7) and alert on spend per window, not on the monthly invoice. Look at the distribution: a handful of very expensive requests often explain most of the bill. The Console's Usage page gives token charts and cache rates as a cross-check against your own numbers.
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 small team's assistant costs more than expected. The per-request cost metric shows the median is fine, but the top one percent of requests cost forty times more. They're all from one integration that pastes entire email threads, so the input cap and a "needs a person" fallback for oversized messages fix it. A per-user daily allowance means that if it happens again, one caller hits their own ceiling rather than everyone's.
Mistakes to avoid
- Hard-coding prices. They change, and the code goes stale silently.
- Estimating cost from the average and ignoring the tail.
- Counting only
input_tokens and forgetting that it excludes cached parts.
- Assuming caching always saves money. A write costs more than a normal read, so rarely reused prefixes can lose.
- No per-user limit on a public endpoint.
- Choosing the smallest model without checking quality.
Security notes
Cost controls are security controls: an attacker who can call your endpoint can spend your money. Authenticate, limit per user, cap input and output, and alert on spikes. Keep API keys per environment so a leak in one place doesn't expose production budgets.
Cost and speed
This lesson is the cost section. The one trade-off to remember is that the cheapest option is often a little slower or a little less capable. Choose deliberately, with your evaluation set as the referee.
Key takeaways
- Cost is uncached input + cache writes + cache reads + output, from the usage the API returns.
- Keep prices in configuration, copied from the official page.
- Check a worst-case estimate before the call and charge actual usage after it.
- The big levers: smaller models for easy steps, shorter outputs, caching, batches. Prove quality with evals.
- Use platform spend limits and workspaces as the outer wall.
Lesson recap: cost comes from the usage fields; cap it before, charge it after, and set an outer wall.
Quick quiz
- Why is
input_tokens not the total input?
- What does a one-hour cache write cost relative to base input, according to the documentation?
- What is a worst-case cost estimate for?
- What status do you get when you reach a spend limit you set yourself?
- Why might prompt caching cost more than not caching?
Answers and explanations
- It counts only tokens after the last cache breakpoint. Total input is cache reads plus cache writes plus
input_tokens.
- Two times the base input price (five-minute writes are 1.25 times).
- To refuse a request before it's made when the user or system couldn't afford its maximum possible cost.
- HTTP 400 with
invalid_request_error and a message saying when access resumes. The tier cap returns 429 with no retry-after.
- A cache write costs more than ordinary input, so if a prefix is rarely read again before it expires, you pay the extra and gain nothing.
Official references and further reading
Related tutorials