How to Calculate LLM API Costs: From Pricing Model to Cost Optimization
This article explains how major LLM APIs actually bill usage through tiered pricing for input tokens, output tokens, and cached tokens. Using a realistic codebase analysis task as a worked example, it walks through the cost math and then presents four practical engineering levers for reducing spend: context caching, input compression, output length control, and a tiered model strategy. It closes with recommendations for making cost an ongoing part of your observability stack.
Why “Pay Per Token” Is More Complicated Than It Looks
Many developers glance at a headline rate like “price per million tokens” and assume they understand their costs. In reality, mainstream LLM API billing is typically split into at least three tiers:
- Input tokens: everything sent to the model, including system prompts, context, and user input.
- Output tokens: the model’s generated response. The unit price is usually 2–4x the input price.
- Cached read tokens: when part of a request repeats a prefix from a previous request (for example, a fixed system prompt or the leading portion of a long document), the cached portion is billed at a lower rate, commonly 1/4 to 1/2 of the input price.
That means the same task can vary in cost by several multiples depending on how it’s implemented. A high-frequency application with a long context can easily see its bill spiral out of control if no engineering optimization is applied.
A Concrete Example: A Codebase Analysis Task
Suppose we’re building an automated script that asks an LLM to analyze a mid-sized project’s codebase and produce modification suggestions. A typical workload:
- Input context: roughly 500,000 tokens (source files + directory structure + requirements description)
- Output content: roughly 20,000 tokens (analysis report + suggested code)
To make the discussion concrete, here’s a set of hypothetical example prices (actual prices depend on your cloud provider — check the official documentation):
- Input: $0.11 / million tokens
- Output: $0.39 / million tokens
- Cached read: $0.03 / million tokens
The calculation:
Input cost = 0.5M × $0.11/M = $0.055Output cost = 0.02M × $0.39/M = $0.0078Total ≈ $0.063 per run
Less than ten cents per run sounds cheap. But if the script is integrated into a CI pipeline and triggered on every commit, running 1,000 times a month comes to about $63. Multiply that across multiple repositories and branches, and the cost becomes worth taking seriously.
Promotional discounts (such as new-user limited-time discounts or off-peak pricing) can halve this cost, but promotions are temporary variables. Engineering optimization is the long-term variable. Building your architecture on the assumption that “there will always be a discount” is a common cost-management mistake.
Four Optimization Techniques That Actually Work
1. Use Context Caching Effectively
In the example above, most of the codebase content — perhaps 450,000 of the 500,000 tokens — stays unchanged between calls. Only the new diff or the new question changes. If the stable portion is placed at the start of the request as a cacheable prefix, the cost structure becomes:
Cache hits: 0.45M × $0.03/M ≈ $0.0135Incremental input: 0.05M × $0.11/M = $0.0055Output: 0.02M × $0.39/M = $0.0078Total ≈ $0.027 per run (over 55% savings)
Implementation notes: put stable content (system prompts, project background, historical code) at the prefix and variable content at the end of the request. Also pay attention to cache validity windows — if the TTL expires, the cache is invalidated and you’ll pay for a full recomputation.
2. Compress the Input: Not All Context Is Worth Sending
A full 500,000-token codebase usually contains plenty of content irrelevant to the task: build artifacts, auto-generated configuration, and verbose boilerplate code. Adding a pre-filtering step before sending (for example, ranking files by relevance and sending only function signatures instead of full implementations) can typically compress input by 30%–60% without noticeably degrading output quality.
3. Control Output Length
Output tokens carry the highest unit price, yet in many scenarios the model produces extensive explanatory text when all you need is the conclusion and the code. You can constrain output by specifying the response format in the prompt (“output only the modified function, no explanation”) or by setting a max_tokens limit. Cutting the output from 20,000 to 10,000 tokens saves roughly another $0.004 per run.
4. Tiered Model Strategy
Tasks like codebase analysis can be split into two phases: “triage” and “deep analysis.” First, use a lightweight, low-cost model to rank files by relevance; then send only the most relevant fragments to a stronger model for deep analysis. In practice, this cascaded architecture can often reduce total cost by an order of magnitude.
Make Cost Part of Your Observability Stack
Cost reduction isn’t a one-time action — it’s an ongoing process. It’s worth setting up a simple cost-observability mechanism at the application layer:
# Pseudocode: log the cost breakdown for each calllog.info({"input_tokens": usage.prompt_tokens,"output_tokens": usage.completion_tokens,"cached_tokens": usage.cached_tokens,"estimated_cost": calc_cost(usage, price_table),})
Combined with cloud monitoring and billing alerting tools (such as log services and cost alerts), aggregate cost data by project and by API endpoint. That way you can catch runaway spend before it happens, instead of being surprised by the bill at the end of the month.
Summary
Managing LLM API costs comes down to three things: understand tiered pricing, build the habit of estimating per-call costs, and continuously optimize with engineering techniques (caching, compression, and cascading models). Get the accounting right before you scale — that’s a lesson every team bringing LLM capabilities into production should learn early.
