← Math
Math

Token and cost arithmetic

Why is the review bot over budget?

Keep context capacity and the cost of each token class in separate calculations.

Outcome

Estimate tokens from characters, count every token against the window, and forecast a bill with cache reads, cache writes and output priced separately.

Terminology (5)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Token
The unit a model reads and writes: a word piece, often 3 to 4 characters of English or code.
Context window
The most tokens one request can hold: input, cached input and the output the model may write.
Prompt caching Also cached input tokens
Reusing a stored prefix of the prompt: in this worked pricing model, a cache write costs more than input and a read costs less.
Cache hit rate
The share of requests that find the prefix still cached.
Token cost forecast
Requests × tokens per class × price per class, compared with a budget.

Why this matters

Model APIs bill by the token and reject requests that do not fit. Forecasts made from averages and list prices go wrong in predictable places: rounding, what counts toward the window, and how often a cache is actually warm.

This lesson assumes percentages, rounding and weighted averages.

From token counts to capacity and cost

A token is a unit produced by a model’s tokenizer. Characters per token provide an empirical size estimate; the tokenizer supplies the actual count. The context window is a capacity budget for the request and its reserved reply, while a price forecast multiplies billable token counts by their rates.

Recall that a weighted average combines alternative outcomes by how often each occurs. Here that arithmetic combines cache reads and writes before adding ordinary input and output charges. The worked rates and cache policy belong to this model; estimates of size, capacity checks and expected bills each answer a different question.

01Estimate tokens from characters

Estimate tokens from characters

Your team’s CI runs an AI review on every pull request. The design doc said each request had 5,000 tokens to spare and the month would cost 1,752 USD against a 2,000 USD budget. Large pull requests now fail with a context error. Before raising the cap, you need to find what the planned traffic will actually cost.

The team measured 3.5 characters per token on its own code. A pull request touching files of 20,990, 7,342 and 1,825 characters is then 5,998, 2,098 and 522 tokens, 8,618 in all. Round each declared-ratio estimate upward to a whole token; truncating gives 8,615. Rounding removes that arithmetic shortfall, but an average ratio is still an estimate and can undercount real tokenizer output. Count the assembled prompt with the model’s tokenizer before a strict window check.

The lab parses the empirical ratio as binary64, divides each character count by it, then takes the ceiling of that computed quotient. Thus 21 / 0.7 is mathematically 30, but the represented quotient is 30.000000000000004 and this estimate is 31. This remains an empirical estimate, including rounding, rather than an exact tokenizer count or guaranteed upper bound. E accepts 1..10,000 files, a finite positive ratio, and nonnegative integer character counts. Each quotient, rounded estimate and their total must lie in the common safe-integer range 0..9,007,199,254,740,991.

Exact counts come from the tokenizer: Anthropic’s TypeScript SDK has messages.countTokens, and js-tiktoken counts OpenAI encodings locally. The ratio is for a quick check before you call.

02Everything shares the context window

Everything shares the context window

The team caps each review request at 16,000 tokens to bound latency and cost. Into that go the 6,000-token review guide, the diff, a 2,000-token limit on the reply and a 1,000-token reserve for the system prompt and tool output. With an 8,000-token diff the total is 17,000: 1,000 over. The largest diff that fits is 7,000 tokens.

The design doc subtracted the guide because it is cached, and reported 5,000 spare. Caching lowers what the guide costs; the model still reads all 6,000 tokens. C accepts nonnegative integers in the same safe range, and guide + diff + cap + reserve must also stay in that range. The resulting spare amount is an exact integer allocation check.

03Each token class has a price

Each token class has a price

USD per million tokens in this model
Token classPriceOne review
Input (the diff, 8,000)3.000.0240
Cache read (the guide, on a hit)0.300.0018
Cache write (the guide, on a miss)3.750.0225
Output (1,200 on average)15.000.0180

Output costs five times input, and writing the cache costs a quarter more than plain input, while reading it costs a tenth. These are the declared prices for this worked model; check your provider’s rates and cache policy before using them.

04Caching depends on traffic

Caching depends on traffic

The 8,000-token diff cannot pass the current 16,000 cap. To isolate the pricing fault, first forecast 40,000 completed reviews after raising that cap to 18,000. The output cap is still 2,000; the observed average billable reply is only 1,200. At hit rate h, the guide’s expected rate is h × 0.30 + (1 − h) × 3.75. Add the diff and reply charges, divide by one million and multiply by reviews. Predict the three totals.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// One review's cost and 40,000 reviews' cost as the cache hit rate falls.
const [input, cacheWrite, cacheRead, output] = [3, 3.75, 0.3, 15]; // USD per million tokens
const [guide, diff, reply] = [6000, 8000, 1200];

for (const hit of [1, 0.35, 0]) {
  const review =
    (diff * input +
      guide * (hit * cacheRead + (1 - hit) * cacheWrite) +
      reply * output) /
    1e6;

  console.log(`${hit.toFixed(2)} ${review.toFixed(4)} ${(review * 40000).toFixed(2)}`);
}

In this worked service, a cached prefix expires after a few minutes without use. Pull requests arrive in bursts during working hours, and the team measured that only 35% of reviews found the guide still cached. The other 65% pay to write it again. The weighted guide rate is 2.5425 USD per million, so one review costs (24,000 + 15,255 + 18,000)/10⁶ = 0.057255 USD. A month costs 2,290.20 instead of the 1,752.00 that assumes every review hits. Raising the cap solves the context rejection but still exceeds the 2,000 budget; reducing diffs to 7,000 lowers this forecast by 120 to 2,170.20, also over.

F is an approximate budget forecast in binary64. In order, form the hit-rate times read-price product, the (1 − hit-rate) times write-price product and their sum. Form the diff charge and guide charge, add those, then add the output charge; multiply that subtotal by reviews and divide by one million. Compare this unformatted cost with the parsed budget using ≤, then display two decimals by rounding the represented value with halfway ties to even: 1.125 displays as 1.12, yet remains over a budget just below 1.125. This is not an exact-decimal invoice calculation. Counts and average counts are nonnegative and at most the safe-integer maximum, hit rate is in [0, 1], budget is finite and nonnegative, and every intermediate product, sum and cost is finite. Parsing and output formatting are supplied.

With a 0% hit rate, is caching the guide still worth it?

05What the forecast does not say

What the forecast does not say

06Budget the review assistant

Budget the review assistant

Repair the review bot’s preflight arithmetic and its monthly quote. A cache hit changes the bill, while the same guide still occupies context space; the budget decision needs both checks.

In the frontend A diff-size warning in Next.js and Svelte Optional

The CI dashboard can warn before a pull request is too large to review, from the same ratio and the max-diff the server computes.

Estimate.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// The CI settings page: warn before a pull request is too large to review.
export function DiffSizeWarning({
  diffChars,
  ratio,
  maxDiff
}: {
  diffChars: number;
  ratio: number;
  maxDiff: number;
}) {
  const tokens = Math.ceil(diffChars / ratio);

  if (tokens <= maxDiff) return null;

  return (
    <p role="alert">
      This diff is about {tokens.toLocaleString()} tokens; the reviewer can read{" "}
      {maxDiff.toLocaleString()}. Split the pull request or review it by hand.
    </p>
  );
}

Check this idea later
A 1,000-character file at 4 characters per token, and a 1,001-character one?
The output cap rises from 2,000 to 3,000 tokens. What happens to the largest diff that fits?
Sources

Values above were run in Node 22, Go 1.27, Rust 1.99 and Apple clang 17. The review assistant, its traffic and the prices are a worked model.

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.