Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Handbooks  /  AI Cost Engineering
Handbook~15 min readProductionworked math + runnable code
The AI Cost Engineering Handbook

The bill is
just tokens.

A demo that costs pennies becomes a product that costs five figures a month — and teams are shocked, because they never did the arithmetic. But AI spend isn't mysterious: it's a simple sum over tokens, with two prices and a few multipliers. Once you can compute a request's cost by hand, the levers become obvious — and the plainest of them (shorter outputs, when output is a large share of your tokens) often beats the clever ones. This handbook turns the invoice into an equation you control.

01

Cost is a sum

Every LLM API bills the same way: per token, with prices quoted per million tokens. A request has two token counts — input (everything you send: system prompt, context, the user's message) and output (what the model generates) — and each has its own price. The cost of one request is just input tokens times input price plus output tokens times output price, divided by a million. That's it. No hidden magic; the whole bill is that sum, repeated across every call.

The reason bills surprise people is that they never estimate that sum at scale. A single request costing $0.01 feels free; a million requests a day is $10,000. Cost engineering is nothing more than doing this arithmetic before the invoice, instrumenting the token counts you actually send, and then pulling the levers the equation reveals. And the equation reveals a lopsided one: the two prices are not equal.

The one-sentence version

A request's cost is input-tokens × input-price + output-tokens × output-price (per million) — and because output is priced several times higher, trimming output is the biggest lever.

02

Output is the lever

Output tokens are typically priced several times higher than input tokens — a 5× ratio is common. That asymmetry changes everything about where cost hides. Two requests with the same total token count can differ 2× in price depending on how the tokens split between input and output. A verbose model that restates the question, thinks out loud, and pads its answer is quietly the most expensive thing in your system.

So the highest-leverage cost cut is almost always the same: make outputs shorter. Ask for concise answers, set a sensible max_tokens, use structured outputs so the model emits only the fields you need, and don't make it echo the input back. This single lever routinely beats the fancy ones, because it attacks the most expensive term in the equation directly. Input is cheaper, so a big fixed context hurts less than a big generation — and the next section shows how to make that fixed context nearly free.

03

Caching pays fast

Many applications send the same long prefix on every call — a big system prompt, a style guide, a document you keep asking about. Prompt caching stores that prefix so later requests pay only a small fraction of the input price for it (a cache read is often ~0.1× the base price), in exchange for a modest one-time write premium (often ~1.25×).

Why caching pays off almost immediately
Write onceFirst call pays a small premium (~1.25×) to store the prefix.
Read cheapEvery later call pays ~0.1× for the cached prefix instead of full price.
Break-evenThe per-reuse saving dwarfs the premium → pays off in < 1 reuse.
Best forBig stable prefixes reused across many calls (system prompt, docs).

The economics are striking. The write premium is a small fraction of the prefix cost; the saving on each reuse is most of it. So the break-even point is well under one reuse — caching pays for itself the first time the prefix is reused, and everything after is nearly free. The catch: the prefix must be stable and identical (caches key on exact prefix match), so put the fixed content first and the variable content last. Get that ordering right and a huge system prompt stops mattering to your bill.

04

The cost equation

The base request cost, with prices pin and pout quoted per million tokens:

cost  =  ( Tin·pin + Tout·pout ) / 106    with typically   pout ≈ 5·pin

Because pout ≫ pin, an output token costs several input tokens — so the same total tokens cost more when weighted toward output.

With caching, the reused prefix of Tpre tokens is billed at a read multiple instead of full price. The reuses needed to break even against the write premium are:

breakeven  =  (mwrite − 1) / (1 − mread)  =  0.25 / 0.9  ≈  0.28   reuses

Independent of prefix size and price — the ratio cancels. Under 1 reuse means caching pays from the first reuse. The runnable calculator below computes request cost, the cache discount, and the break-even.

RUN IT YOURSELF

A cost calculator you can edit

Cost engineering is arithmetic you can run. A request costs input-tokens × input-price plus output-tokens × output-price, per million — so at illustrative prices of $3/M in and $15/M out (not any one model's current rate), 1M input is $3 and 1M output is $15. Caching bills a reused prefix at a fraction of the input price (~0.1×) for a small one-time write premium (~1.25×), so it pays off in under one reuse, independent of prefix size. And because output is priced ~5× input, the same total tokens cost more when weighted toward output — which is why trimming output is the top lever. Change the token counts, prices, or cache multipliers and watch the bill move.

CPython · WebAssembly
05

The full lever set

Beyond shorter outputs and caching, a handful of levers cut spend without cutting quality:

LeverHow it saves
Shorten outputsAttacks the most expensive term directly — concise answers, max_tokens caps, structured outputs.
Prompt cachingReused stable prefixes billed at ~0.1× — pays off from the first reuse.
Model routingSend easy requests to a cheaper model; reserve the flagship for hard ones (a cheap-smart cascade).
BatchingAsync/batch APIs offer large discounts for non-urgent work.
Context trimmingSend only the context you need — retrieval beats stuffing the whole corpus.
Dedup & memoizeCache full responses for identical requests; don't pay twice for the same answer.

Order them by leverage, not novelty: measure first, then cut output, then cache, then route. A cheaper model that's right 95% of the time on easy traffic, with the expensive model as fallback, can slash the bill while barely moving quality — that's serving economics meeting cost engineering. And context engineering — sending less, more relevant input — compounds with all of it.

06

Pitfalls

The classic mistake is optimizing without measuring. Cost is dominated by a few request types; guess wrong and you'll tune the cheap ones. Instrument token counts per endpoint first — you'll usually find one verbose feature is most of the bill. Another trap: breaking the cache by putting variable content (a timestamp, a user id) at the front of the prompt, which changes the prefix and defeats caching for everyone downstream. Keep the fixed part first.

Also beware false economy: a cheaper model that fails and triggers retries, escalations, or human review can cost more end-to-end than the pricier model that just gets it right. Cost per successful outcome is the real metric, not cost per call. And reasoning models add a wrinkle — their hidden "thinking" tokens are billed as output, so a model that thinks a lot is expensive even when its visible answer is short. The discipline is the same throughout: know the token equation, measure where the tokens go, and pull the biggest lever first.

Worth knowing

Reasoning models bill their internal chain-of-thought as output tokens — often the majority of a request's cost — so "the answer was short" doesn't mean "the request was cheap." Budget thinking, and measure output tokens including hidden reasoning.

By the numbers

Worked example: costing a support bot, step by step

A support bot sends a 3,000-token system prompt that never changes, 1,500 tokens of retrieved help articles, a 100-token question, and gets back 400 tokens. It serves 100,000 requests a day. Prices are the page’s $3/M in and $15/M out. The workload is illustrative; the arithmetic is the equation above.

StepWhat changesArithmeticPer requestPer day
1Input cost4,600 × $3 / 106$0.0138$1,380
2Output cost400 × $15 / 106$0.0060$600
3Baselinestep 1 + step 2; × 30 days = $59,400/month$0.0198$1,980
4Cap output at 250 tokens250 × $15 / 106 = $0.00375 out$0.01755$1,755 (−$225)
5Instead, cache the 3,000-token prompt3,000 × $3 × 0.1 + 1,600 × $3, all / 106, + $0.006 out$0.0117$1,170 (−$810)
6Do both$0.0057 in + $0.00375 out$0.00945$945 (−52%)
7Route 60% of traffic to a model at a tenth of the price0.6 × $0.000945 + 0.4 × $0.00945$0.004347$434.70 (−78%)

The month goes from $59,400 to about $13,000. Notice step 5 beats step 4 here: input is 70% of this bot’s bill (step 1 over step 3), because a big fixed prompt and retrieved context outweigh a short answer. On a feature that writes long answers from short prompts, the order flips and trimming output wins. That is why measuring per-endpoint token counts comes before choosing a lever. At this volume the cache stays warm, so the 1.25× write premium is paid rarely and rounds to nothing. Step 7 only holds if the cheap model really handles that 60%, which is the false-economy check from the pitfalls section. Prove it on a sample of real tickets before switching the traffic over.

In the wild

Where this shows up in production and interviews

  • Cost per feature, not per account

    Every API response reports the input, output and cached token counts it billed. Log them on every call, tagged with the feature and the tenant. The invoice tells you the total; only these tags tell you which endpoint or customer is most of it. Watch the cached-token count too: if it drops to zero after a deploy, someone changed the front of the prompt and the bill is about to jump.

  • Agent loops multiply input

    An agent resends its whole growing context on every step. Start at 2,000 tokens, add 1,000 per step, and run 10 steps: the last call sends 11,000 tokens, but the run sends 65,000 in total. That is 5.9× the tokens of the final call alone, and the gap grows with the square of the step count. Cap the steps, cache the fixed prefix so each resend of it bills at 0.1×, and summarise or drop old tool results instead of carrying them forever.

  • Unit economics of your own product

    Divide monthly token spend by active users and compare it with what a user pays. A flat-price plan with a few heavy users can lose money on exactly those users. Per-user quotas, or routing heavy use to a cheaper model, keep the margin.

  • The interview version

    In “design a chatbot” or “design a RAG system”, estimate the bill out loud: tokens in and out per request, times requests per day, times price. Then say which term dominates and which lever you would pull first. Doing the step 1 to 3 arithmetic in a minute shows more than naming a model.

Self-check

Check yourself

Use the page’s prices ($3/M in, $15/M out, cache read 0.1×, write 1.25×). Work each one out before you open the answer; the point is to get fast at the equation, not to remember the result.

Feature A sends 500 tokens and gets 1,500 back. Feature B sends 4,000 and gets 100 back. At $3/M in and $15/M out, which costs more per call?

A. It costs (500 × 3 + 1,500 × 15) / 106 = $0.024. B costs (4,000 × 3 + 100 × 15) / 106 = $0.0135. B sends 2.6× as many tokens in total but is cheaper, because A’s tokens are mostly output.

A developer adds a request id to the first line of the cached 3,000-token system prompt. What happens to the bill?

Every request now has a different prefix, so every request misses the cache and writes a new entry. That prefix costs 3,000 × $3 × 1.25 / 106 = $0.01125 per call instead of $0.009 uncached, or $0.0009 cached. Caching is now worse than no caching. Move anything variable, such as ids, timestamps, the user’s name or today’s date, to the end, after the stable instructions and documents, and check that the cached-token count in the usage data is above zero.

A big model costs $0.02 a call and succeeds 95% of the time. A small one costs $0.002 and succeeds 70%. You can detect failures and retry them on the big model. Is the cascade cheaper per success?

Yes. The cascade costs 0.002 + 0.3 × 0.02 = $0.008 a call and succeeds 0.7 + 0.3 × 0.95 = 98.5% of the time, about $0.0081 per success. The big model alone is 0.02 ÷ 0.95 ≈ $0.021 per success. The catch is the word “detect”: failures you cannot spot reach users, and then cost per call is the wrong number.

A reasoning model shows a 200-token answer but used 3,000 hidden thinking tokens. At $15/M output, what did the output cost, and how far off is an estimate from the visible text?

3,200 × 15 / 106 = $0.048. The visible 200 tokens alone would suggest $0.003, so the estimate is 16× too low. Thinking tokens are billed as output. Read the usage the API reports instead of counting the visible answer, and set a thinking budget where the API offers one.

Frequently asked

Quick answers

How is LLM cost calculated?

Per token: input-tokens × input-price + output-tokens × output-price, with prices quoted per million tokens.

Why does output dominate?

Output is priced several times higher than input (often ~5×), so long generations drive the bill — trimming output is the top lever.

Does caching save money?

Yes — a reused stable prefix is billed at ~0.1× for a small write premium, so caching pays off from the first reuse.

What's the biggest lever?

Shorter outputs, then caching, then routing easy requests to a cheaper model — but measure first so you cut what actually costs.

Finished this one? 0 / 209 Handbooks done
NextLLM API Pricing Next on the “Serving models, and paying for them” ladder · rung 10 of 13

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Handbooks