~/academy $ claude learn tokens-costs-and-rate-limits
Tokens, costs, rate limits and errors
How to count tokens before sending, read usage to track cost, understand Claude API rate limits and usage tiers, and handle errors and retries properly. 9 min
$ Read
Count before you send
client.messages.count_tokens takes the same inputs as a real request (system, messages, tools, images and PDFs as base64) and returns input_tokens. It is free, with its own rate limit (5,000 requests a minute on the Start tier) that does not touch your message limits. The count is an estimate and can differ slightly from the real request.
Count against the model you will actually use. Claude 4.7 and later models use a newer tokenizer that produces about 30 percent more tokens for the same text than earlier models, so old counts understate current costs. The endpoint does not accept server tools or url and file sources.
count = client.messages.count_tokens(
model="claude-opus-5-5",
system="You are a scientist",
messages=[{"role": "user", "content": "Hello, Claude"}],
)
print(count.input_tokens)Lesson notes: Tokens, costs, rate limits and errors
Everything in this lesson as text, for revision or to read without the interactive steps. By the end you will be able to: You predict and log the cost of every request, stay inside your rate limits and recover cleanly from errors.
Step 1 of 6 · Read
Count before you send
client.messages.count_tokenstakes the same inputs as a real request (system, messages, tools, images and PDFs as base64) and returnsinput_tokens. It is free, with its own rate limit (5,000 requests a minute on the Start tier) that does not touch your message limits. The count is an estimate and can differ slightly from the real request.Count against the model you will actually use. Claude 4.7 and later models use a newer tokenizer that produces about 30 percent more tokens for the same text than earlier models, so old counts understate current costs. The endpoint does not accept server tools or
urlandfilesources.Count a request count = client.messages.count_tokens( model="claude-opus-5-5", system="You are a scientist", messages=[{"role": "user", "content": "Hello, Claude"}], ) print(count.input_tokens)Step 2 of 6 · Read
Log usage on every response
Each response's
usagehasinput_tokens,output_tokens,cache_creation_input_tokensandcache_read_input_tokens, plusserver_tool_usecounts when server tools ran. Store them with the request id and you can see cost per feature, per customer and per day.Remember that output includes thinking, and add server tool fees (such as web search) separately. The Console Usage page shows the same picture across your organisation.
Cost of one request # US dollars per million tokens for Opus 5.5, checked 18 November 2026 # (cache write uses the 5-minute rate) PRICE = {"in": 4.00, "out": 20.00, "write": 5.00, "read": 0.20} def request_cost(usage): return ( usage.input_tokens * PRICE["in"] + usage.output_tokens * PRICE["out"] + (usage.cache_creation_input_tokens or 0) * PRICE["write"] + (usage.cache_read_input_tokens or 0) * PRICE["read"] ) / 1_000_000 print(f"{response._request_id}: {request_cost(response.usage):.4f} USD")Step 3 of 6 · Read
Rate limits and tiers (checked 18 November 2026)
Limits are per organisation and per model, measured as requests per minute (RPM), input tokens per minute (ITPM) and output tokens per minute (OTPM). Organisations move up the Start, Build and Scale tiers automatically over time; new ones may begin in a lower Evaluation tier. Each tier also has a monthly spend cap: $500, $1,000 and $200,000.
On the Start tier, Opus 5.5 allows 4,000 RPM, 2,000,000 ITPM and 400,000 OTPM. Cached reads do not count towards ITPM, and
max_tokensdoes not count towards OTPM, only tokens actually written. Limits refill continuously rather than resetting each minute, and a sudden jump in traffic can hit a separate ramp limit, so grow traffic gradually.Responses include
anthropic-ratelimit-*headers showing what is left, and aretry-afterheader when you are limited. See your own limits on the Rate limits page of the Console.Step 4 of 6 · Read
Errors and retries
Common errors: 400
invalid_request_error(fix the request), 401authentication_error(bad key), 403permission_error, 404not_found_error, 413request_too_large, 429rate_limit_error, 500api_errorand 529overloaded_error. Every error body includes arequest_id.The Python SDK already retries connection errors, 408, 409, 429 and 5xx errors twice with exponential backoff, honouring
retry-after. Change that withmax_retries. The default timeout is 10 minutes. One 429 is different: hitting your tier's monthly spend cap returns noretry-after, witherror_codeenforced_spend_limit_reached, and retrying will keep failing until the month resets or your tier rises.Catch specific errors first import logging import anthropic log = logging.getLogger(__name__) client = anthropic.Anthropic(max_retries=4) # default is 2 try: response = client.messages.create(model="claude-opus-5-5", max_tokens=1024, messages=messages) except anthropic.BadRequestError as e: log.error("Fix the request: %s", e) except anthropic.RateLimitError as e: log.warning("Still rate limited after retries: %s", e) except anthropic.APIStatusError as e: log.error("API error %s", e.status_code) except anthropic.APIConnectionError: log.error("Could not reach the API")Step 5 of 6 · Sort
Retry or fix something first?
Decide what to do with each error.
- 429 rate_limit_error with a retry-after header
- 529 overloaded_error
- 400 invalid_request_error
- 401 authentication_error
- 500 api_error
- 429 with error_code enforced_spend_limit_reached
Show the answers
- 429 rate_limit_error with a retry-after header: Retry with backoff. Wait the number of seconds it says, then retry.
- 529 overloaded_error: Retry with backoff. Temporary high traffic. Back off and try again.
- 400 invalid_request_error: Fix something first. Something in the request is wrong, so a retry fails the same way.
- 401 authentication_error: Fix something first. The key is missing, wrong, revoked or expired.
- 500 api_error: Retry with backoff. An internal error. Retry with exponential backoff, and contact support with the request ID if it persists.
- 429 with error_code enforced_spend_limit_reached: Fix something first. The monthly spend cap is reached. Retries fail until access resumes or you move tier.
Step 6 of 6 · Quiz
Check your understanding
Your ITPM limit is 2,000,000 and 80 percent of your input tokens are cache reads. Roughly how many total input tokens a minute can you send?
- 2,000,000, the limit is the limit
- About 10,000,000
- About 2,400,000
- Unlimited
Show the answer
About 10,000,000 2M uncached tokens are 20 percent of the total, so the total is 10M: 2M uncached plus 8M cached. This example comes straight from the docs.