- Calculate the monthly cost of an LLM workload from request volume, token counts and per-million-token prices.
- Derive how input tokens grow with conversation length and apply history trimming to control it.
- Determine when prompt caching and batch processing pay off, and structure prompts so caching works.
- Estimate user-perceived latency from time to first token and generation speed.
- Implement retry logic with exponential backoff and jitter that respects Retry-After.
Before this: How Large Language Models Work, Context Windows and Memory
If you build anything on top of a hosted AI model, every request costs money and takes time. Understanding how those requests are priced lets you estimate a monthly bill before you ship, instead of discovering it afterwards.
Calling a model over an API
An API (application programming interface) is a defined way for one program to ask another program to do something. A hosted model's API is a web address your code sends an HTTPS request to. The request contains the conversation so far and some settings; the response contains the model's reply.
Most providers use a shape similar to the one below. Field names differ between providers, so treat this as a generic, OpenAI-compatible illustration rather than any one vendor's exact format.
{
"model": "example-model",
"max_tokens": 500,
"messages": [
{"role": "system", "content": "You are a concise support assistant."},
{"role": "user", "content": "How do I reset my password?"}
]
}
The system message sets standing instructions; user and assistant messages hold the conversation. An important detail: the API is stateless, meaning the server does not remember your previous call. To continue a conversation you send the whole history again each time. That is why long chats get more expensive per turn.
Tokens: the unit you pay for
Models read and write tokens, which are chunks of text: often a whole short word, sometimes part of a longer word or a punctuation mark. A common rule of thumb for English is that 1,000 tokens is roughly 750 words, but it varies by language and by the model's tokenizer.
Every request has two token counts:
- Input tokens: everything you send, including the system prompt, the conversation history, any documents you paste in, and tool definitions.
- Output tokens: everything the model writes back.
Providers price these separately, quoted per million tokens. Output is usually priced higher than input, often several times higher, because generating each output token takes a full pass through the model, while input tokens can be processed in parallel. As one example, as of November 2026 Anthropic's published API prices put output at five times the input price for its current models.
A worked monthly cost example
The prices below are illustrative round numbers, not any provider's actual rates. Check the current pricing page of whichever provider you use.
Assume a support bot with:
- Input price: $3 per million tokens; output price: $15 per million tokens.
- 10,000 conversations per day, 30 days a month = 300,000 requests.
- Each request sends 2,000 input tokens and receives 500 output tokens.
| Item | Tokens per month | Cost |
|---|---|---|
| Input | 300,000 × 2,000 = 600 million | 600 × 1,800 |
| Output | 300,000 × 500 = 150 million | 150 × 2,250 |
| Total | $4,050 |
Notice that output costs more than input here even though there is four times less of it. Capping response length is one of the simplest cost controls.
Prompt caching
Many requests start with the same long prefix: a big system prompt, a policy document, a set of tool definitions. Prompt caching lets the provider store the processed form of that prefix so later requests that begin with exactly the same text are cheaper and faster. Some providers cache automatically; others need you to mark what to cache. Writing to the cache can cost more than normal input, and cached prefixes are kept for anything from a few minutes to many hours, depending on provider, model and settings. As of November 2026, for example, Anthropic charges 1.25 times the input price for a five-minute cache write (2 times for a one-hour cache) and 0.1 times for a cache read, or less on some newer models.
Continuing the example: if 1,500 of the 2,000 input tokens are an identical system prompt, and cache reads cost 10% of the input price, then 450 million tokens cost $0.30 per million ($135) and the remaining 150 million cost $3 per million ($450). Input drops from $1,800 to about $585, before the small cost of cache writes. The rule: put stable content first and variable content (the user's question) last, because caching only works on an exact matching prefix.
Batch discounts
If you don't need an answer immediately, for example nightly document tagging or evaluating thousands of test cases, many providers offer a batch interface. You upload many requests at once and collect results later, typically within 24 hours. As of November 2026, both OpenAI and Anthropic advertise 50% off standard prices for batch jobs. In the example, a latency-tolerant workload of the same size would cost about $2,025 instead of $4,050.
Rate limits
Providers cap how much you can send, usually as requests per minute and tokens per minute, with limits that typically rise as your account's payment and usage history grows. Exceed them and you get an error (HTTP status 429, "too many requests"). Well-behaved clients honour a Retry-After header if the provider sends one, and otherwise retry with exponential backoff: wait a moment, retry, and double the wait after each failure, with a little randomness so many clients don't retry in lockstep.
Streaming
By default the API returns the whole reply once it is finished. With streaming, the server sends tokens as they are generated, usually over a long-lived HTTP connection using server-sent events. Streaming does not make the total answer faster or cheaper; it makes the first words appear sooner, which matters a lot for how responsive a chat interface feels. Two latency numbers are worth tracking separately: time to first token and total time to complete.
Going deeper
A cost model you can reason with
For a workload of requests, each with input tokens and output tokens, and prices and quoted per million tokens, the bill is
Everything else in this lesson modifies one of those terms. Caching lowers the effective for part of ; batching multiplies the whole thing by roughly 0.5; trimming history lowers ; a tighter max_tokens caps . When a bill surprises you, find out which term moved.
Why chat history grows faster than you expect
Because the API is stateless, turn of a conversation resends the system prompt ( tokens), all user messages (about tokens each) and the earlier assistant replies (about tokens each). Summing over a conversation of turns gives total input
The last two terms grow with , so a conversation twice as long costs roughly four times as much input once history dominates.
Worked example. Take , , and turns:
- System prompt: tokens.
- User messages: tokens (since ).
- Earlier replies: tokens (since ).
- Total input: 78,000 tokens. Output: tokens.
At the illustrative prices from earlier (USD 3 and USD 15 per million), that is USD 0.234 of input and USD 0.075 of output, about USD 0.31 per conversation. If the server remembered history you would only pay for about 21,000 input tokens; resending is why input dominates. The standard fixes are to drop or summarize old turns past a budget, and to keep the stable part (system prompt, tool definitions) at the front so it can be cached.
When does caching pay off?
Let a cache write cost times the normal input price and a cache read cost times it. If an identical prefix of tokens is used by requests before the cache expires, the prefix costs with caching and without. With the multipliers quoted earlier for Anthropic's five-minute cache (, ):
- : 1.25 versus 1. Caching a prefix you never reuse costs 25% more.
- : 1.35 versus 2. You already save about a third.
- : 11.15 versus 100. You save about 89%.
Solving gives , so a prefix reused even twice within the cache lifetime is worth caching. What breaks caching in practice is not the arithmetic but tiny changes to the prefix: a timestamp at the top of the system prompt, tools listed in a different order, or a user's name inserted early. Any change ends the matching prefix at that point.
Latency: two numbers, one formula
For a single streamed request, a useful first approximation is
where is the time to first token (queueing, network and processing the input) and is the generation speed in tokens per second. With s, tokens/s and a 500-token answer, the user waits about 5.5 s for the full reply but sees text after 0.5 s. Halving the answer to 250 tokens saves 2.5 s; a model that is 20% faster at generating saves about 0.8 s. Long inputs raise , because the model must process every input token before it writes anything (see the lesson on KV cache and context cost).
Retries without stampedes
When many clients hit a rate limit at once and all retry after the same fixed delay, they collide again. Exponential backoff with full jitter draws each wait at random:
where is the retry number. The sketch below estimates monthly cost and retries a rate-limited call. It is provider-neutral: plug in your own client call and the exception your SDK raises for HTTP 429.
import random, time
def monthly_cost(requests, t_in, t_out, p_in, p_out,
cached_frac=0.0, read_mult=0.1, batch=False):
"""Prices are per million tokens. Ignores cache-write cost."""
cached = t_in * cached_frac
input_cost = cached * p_in * read_mult + (t_in - cached) * p_in
total = requests * (input_cost + t_out * p_out) / 1e6
return total * (0.5 if batch else 1.0)
print(monthly_cost(300_000, 2_000, 500, 3, 15)) # 4050.0
print(monthly_cost(300_000, 2_000, 500, 3, 15, cached_frac=0.75)) # 2835.0
class RateLimited(Exception):
def __init__(self, retry_after=None):
self.retry_after = retry_after
def call_with_backoff(fn, max_retries=6, base=0.5, cap=30.0):
for attempt in range(max_retries + 1):
try:
return fn()
except RateLimited as e:
if attempt == max_retries:
raise
if e.retry_after is not None: # the server knows best
delay = e.retry_after
else: # full jitter
delay = random.uniform(0, min(cap, base * 2 ** attempt))
time.sleep(delay)
The second figure reproduces the caching example from earlier: 75% of input served from cache brings the month from USD 4,050 to USD 2,835 (USD 585 input plus USD 2,250 output), before cache-write costs.
Counting tokens properly
The 750-words-per-1,000-tokens rule is only a planning figure. Tokenizers are usually learned with variants of byte-pair encoding, which merges frequent character sequences into single tokens, so common English words are cheap while code, numbers, rare names and many non-English languages can take noticeably more tokens for the same content. Before committing to a budget, run a sample of real prompts through the provider's own token-counting tool or tokenizer, and log the token counts the API reports with each response; those reported counts, not your estimates, are what you are billed for.
Common pitfalls
- Estimating with toy prompts. Real requests carry system prompts, tool definitions, retrieved documents and history. Measure with production-shaped inputs.
- Forgetting hidden output. Reasoning models can generate internal reasoning tokens that are billed as output even when they are not shown; budget for them and cap them where the API allows.
- Breaking the cache by accident. Timestamps, request IDs or reordered tools near the top of the prompt silently disable prefix caching.
- Retrying everything. Retry 429s and transient server errors, not 400-class errors caused by a bad request, which will fail the same way again.
- Unbounded loops. An agent or retry loop without a step and spend cap can run up a large bill overnight.
- Hard-coding prices. Prices change; keep them in configuration and re-check the provider's pricing page.
In practice
- Before building, estimate: requests per month × (input tokens × input price + output tokens × output price). Do it with real prompt sizes, including history and documents.
- Set a sensible
max_tokensand trim conversation history you no longer need. - Order prompts as stable-first, variable-last so caching can help.
- Move anything that can wait into batch jobs.
- Handle 429 errors with backoff, and stream responses in user-facing interfaces.
- Re-check prices periodically; they change often, usually downward.
Key takeaways
- A model API is stateless: you resend the conversation each time, so long histories cost more per turn.
- You pay separately for input and output tokens, priced per million, and output usually costs several times more than input.
- Prompt caching cuts the cost of repeated identical prefixes, so put stable content first.
- Batch interfaces trade speed for a large discount, often around half price as of November 2026.
- Streaming improves perceived speed, not total cost; rate limits require retry-with-backoff logic.
Terms in this lesson
- API
- A defined interface that lets one program send requests to another, here to a hosted model over HTTPS.
- Token
- A chunk of text, often a word or part of a word, that models read and write and that providers bill by.
- Input tokens
- Everything sent to the model in a request, including instructions, history, documents and tool definitions.
- Output tokens
- The tokens the model generates in its reply.
- Prompt caching
- Reusing the processed form of an identical prompt prefix across requests at a reduced price.
- Batch API
- A way to submit many requests for delayed processing in exchange for a lower price.
- Rate limit
- A cap on how many requests or tokens an account may send in a given period.
- Streaming
- Receiving the model's reply token by token as it is generated instead of all at once.
- Time to first token
- The delay between sending a request and receiving the first generated token, dominated by queueing, network time and processing the input.
- Jitter
- Deliberate randomness added to retry delays so that many clients do not retry at the same moment.
Check your understanding
- 1.
Your chatbot's bill grows with each turn of a long conversation even though users type short messages. Why?
- 2.
Which change is most likely to make prompt caching effective?
- 3.
What does streaming improve?
- 4.
A request sends 4,000 input tokens and receives 800 output tokens. Input costs 2 dollars and output 10 dollars per million tokens. What does one request cost?
- 5.
A cache write costs 1.25× the input price and a cache read 0.1×. A 10,000-token prefix will be used by only one request before it expires. What should you do?
Exercises
Work each problem before opening the solution.
- Exercise 1Core
A document-tagging job runs 50,000 requests a month. Each sends 6,000 input tokens (of which 5,000 are an identical instruction block) and receives 200 output tokens. Prices: 3 dollars input, 15 dollars output per million; cache reads cost 0.1× input. Compute (a) the plain monthly cost, (b) the cost with the instruction block served from cache (ignore write costs), and (c) the cost if the job instead runs through a 50%-off batch API without caching.
Show solution
(a) Input: 50,000 × 6,000 = 300 million tokens × 3 = 900 dollars. Output: 50,000 × 200 = 10 million × 15 = 150 dollars. Total 1,050 dollars.
(b) Cached input: 50,000 × 5,000 = 250 million × 0.30 = 75 dollars. Uncached input: 50 million × 3 = 150 dollars. Output unchanged at 150 dollars. Total 375 dollars.
(c) 1,050 × 0.5 = 525 dollars.
Caching wins here because most input is a shared prefix. If the provider lets you combine batch and caching discounts, check its pricing page for how they stack; don't assume.
- Exercise 2Core
Using the formula , compute total input tokens for a 10-turn conversation with , , . Then compute it again if the app keeps only the last 4 turns of history (user and assistant messages) plus the system prompt.
Show solution
Full history: ; ; . Total 43,500 tokens.
Windowed: interpret "last 4 turns" as the current user message plus up to the 3 previous user/assistant pairs. Turn then sends .
- System prompt: 20,000.
- User tokens: turns 1 to 4 send 1, 2, 3, 4 messages (10 total); turns 5 to 10 send 4 each (24). Total 34 × 100 = 3,400.
- Assistant tokens: turns 1 to 4 send 0, 1, 2, 3 replies (6); turns 5 to 10 send 3 each (18). Total 24 × 400 = 9,600.
Total 33,000 tokens, about 24% less, and the saving grows with conversation length because the windowed cost is linear in while the full-history cost is quadratic. The trade-off is that the model forgets older turns unless you summarize them.
- Exercise 3Core
Write a Python function
max_cost_per_request(t_in, max_tokens, p_in, p_out)that returns the worst-case cost of a single request, and use it to find the largestmax_tokensthat keeps a request with 3,000 input tokens under 0.02 dollars at 3 and 15 dollars per million.Show solution
def max_cost_per_request(t_in, max_tokens, p_in, p_out): return (t_in * p_in + max_tokens * p_out) / 1e6 budget, t_in, p_in, p_out = 0.02, 3_000, 3, 15 # Solve t_in*p_in + m*p_out <= budget*1e6 for m m = int((budget * 1e6 - t_in * p_in) // p_out) print(m, max_cost_per_request(t_in, m, p_in, p_out)) # 733 0.019995Input costs 3,000 × 3 ÷ 10^6 = 0.009 dollars, leaving 0.011 dollars for output, which buys 0.011 × 10^6 ÷ 15 ≈ 733 tokens. Setting
max_tokens = 733guarantees the cap (reasoning-model hidden tokens also count as output, so include them in the cap if applicable). - Exercise 4Challenge
A chat feature has 20,000 conversations a day, each averaging 8 turns. The system prompt plus tool definitions is 3,000 tokens; user messages average 60 tokens and replies 300. Prices: 3 dollars input, 15 output per million; cache write 1.25×, cache read 0.1×. Assume the 3,000-token prefix is written to cache once per conversation (first turn) and read on every later turn. Estimate the monthly (30-day) cost with and without caching, and identify which term dominates.
Show solution
Per conversation, with :
- Prefix tokens: .
- User tokens: ().
- History replies: ().
- Output: .
Without caching: input 34,560 tokens × 3 ÷ 10^6 = 0.10368; output 2,400 × 15 ÷ 10^6 = 0.036. Total 0.13968 dollars per conversation. Monthly: 600,000 conversations × 0.13968 ≈ 83,808 dollars.
With caching: the prefix costs token-equivalents instead of 24,000. Input becomes token-equivalents × 3 ÷ 10^6 = 0.04923. Plus output 0.036 gives 0.08523 dollars. Monthly ≈ 51,138 dollars, a saving of about 39%.
Dominant term: without caching, the repeated prefix (24,000 of 34,560 input tokens) dominates. After caching, output (0.036) and resent replies (8,400 × 3 ÷ 10^6 ≈ 0.025) are the largest terms, so the next levers are shorter replies and history trimming. (In practice the conversation history itself can also be cached incrementally on some APIs, which would cut cost further.)
Further reading
- docsAnthropic, Pricing (Claude API documentation)
- docsAnthropic, Prompt caching (Claude API documentation)
- docsOpenAI, Rate limits (API documentation)
- articleMarc Brooker, Exponential Backoff and Jitter (AWS Architecture Blog, 2015)
- paperSennrich, Haddow & Birch, Neural Machine Translation of Rare Words with Subword Units (2015)
- courseHugging Face LLM Course, Chapter 6: Byte-Pair Encoding tokenization
Go further
Sources
Fact-checked and last reviewed 2026-11-05