Measuring and Modeling LLM Token Consumption in Coding Scenarios
Coding assistants often charge by subscription quota rather than per-token pricing, and the quota display only shows integer percentages. This article explains how to measure the per-token deduction rate for four token types (cache reads, fresh input, cache writes, and output) using controlled experiments and interval sampling, then combine those rates with your real workload mix in a weighted model to estimate how many tokens a quota period can actually support. Example Python code and practical rollout steps are included.
1. Background: Why Quota-Based Billing Resists Simple Conversion
Many coding assistants use a subscription model: users receive a fixed quota per billing cycle. The UI typically shows only an integer percentage of quota consumed, without disclosing how each token type is converted. This creates two problems for cost estimation.
First, tokens are not priced uniformly. For the same one million tokens, cache-hit reads, cache-missed fresh input, cache writes, and model output may be deducted from the quota at very different weights. Treating all tokens as equally priced produces conclusions that diverge significantly from reality.
Second, real workloads vary widely in structure. Long conversations, large code context, and frequent tool calls make cache reads dominate total tokens, while one-shot long-text generation is dominated by output. Any statement about “how many tokens a quota can handle” that ignores the specific workload is meaningless.
A more reliable approach is to first measure the deduction rate for each token type, then weight those rates by the structure of your own workload, and finally derive the total volume the quota can support.
2. The Four Token Types and How to Count Them
Before discussing deduction rates, we need consistent terminology.
- Cache Read: Tokens consumed when the request prefix exactly matches cached content and the server reuses prior computation. In coding scenarios, system prompts, project structure descriptions, and conversation history are heavily reused, so this type often has the highest share.
- Fresh Input: Input tokens that miss the cache and must be processed from scratch. When every request contains different content, all input falls into this category.
- Cache Write: Tokens generated when content is written into the cache for the first time. This typically occurs only when a new context is established, but under some billing rules it is priced higher than ordinary input.
- Output: Tokens generated by the model. Output is usually the most computationally expensive and often priced higher than input.
A single request may contain multiple token types. If logs record only totals, per-type shares cannot be recovered—you must record the count for each type at the request level.
3. Isolated Measurement: Make Each Experiment Consume Only One Token Type
The most direct way to measure the deduction rate of a single token type is controlled variation: design each experiment to consume one type in bulk while keeping the others minimal.
3.1 Cache Reads
First write a fixed long context so it enters the cache. Then repeatedly send requests carrying the same prefix, appending only a tiny amount of new content each time. The vast majority of consumption will then come from cache reads.
Key points:
- The prefix must match byte-for-byte; any change in whitespace or timestamps invalidates the cache.
- The new content in each request should be as short and fixed as possible to avoid distorting results.
- Read the quota display before and after each request, and record the cumulative token count over each interval.
3.2 Fresh Input
The approach for fresh input is the opposite: use different content in every request so the cache never hits. Content can be randomly generated text or sampled segment by segment from a corpus, but each segment should have a stable length for easy conversion.
Key points:
- Generated content must differ clearly, avoiding repeated prefixes that would cause partial hits.
- Keep output as short as possible—for example, constrain responses to a minimal fixed reply—to prevent output from contaminating the statistics.
- Record input token counts, not request counts.
3.3 Cache Writes
Cache writes normally occur only when establishing new context. To measure them, give every request a completely new prefix, forcing repeated cache writes. Note that different services define cache TTL and hit conditions differently; confirm the current configuration before measuring and document it in your experiment records.
3.4 Output
Measuring output requires lengthening generation while minimizing input. With a fixed, very short prompt that requests a long response, output will dominate total tokens.
4. Using Interval Sampling to Cancel Out Integer-Display Error
The UI shows only integer percentages, so a single reading can be off by nearly a full percentage point. This error is significant in small tests but averages out over many intervals.
The method: send requests continuously and record the cumulative token count whenever the displayed value crosses from one integer to the next (e.g., 17% to 18%). Each such interval corresponds to exactly one percentage point of quota. Combining many complete intervals yields a stable average deduction rate.
Three key points:
- Discard incomplete intervals at the start and end; use only intervals fully crossed at both ends.
- When combining, divide total percentage points by total tokens rather than averaging per-interval ratios. The former weights intervals by actual consumption.
- More intervals mean more stable results. In practice, collect at least several dozen complete intervals and repeat experiments at different times to check consistency.
5. The Weighted Model: From Deduction Rates to Capacity
After measuring all four deduction rates, weight them by your workload structure. Let r_k be the deduction rate per million tokens of type k (in quota percentage points), and w_k its share of total tokens. The blended consumption per million tokens under a mixed workload is:
Blended consumption = Σ (r_k × w_k)
Since a full quota is 100 percentage points, the total tokens supported per cycle is approximately:
Capacity (in millions of tokens) = 100 / Blended consumption
The shares w_k must come from real logs. Coding habits differ greatly across teams, and borrowing someone else’s ratios introduces bias.
6. Example Code
The following code demonstrates the calculation flow. The deduction rates and mix are hypothetical values for illustration only and do not represent data from any real service; replace them with your own measurements and log statistics.
from dataclasses import dataclass@dataclassclass IntervalRecord:tokens: int # cumulative tokens of one type consumed in a complete intervalpercent_points: float = 1.0 # quota percentage points crossed by the intervaldef estimate_rate(records: list[IntervalRecord]) -> float:"""Return quota percentage points consumed per million tokens (pooled calculation,weighted by actual consumption)."""total_pct = sum(r.percent_points for r in records)total_tokens = sum(r.tokens for r in records)if total_tokens == 0:raise ValueError("No valid sampling data")return total_pct / total_tokens * 1_000_000def blended_rate(rates: dict[str, float], mix: dict[str, float]) -> float:"""Weight rates by workload mix; return blended consumption per million tokens."""if abs(sum(mix.values()) - 1.0) > 1e-6:raise ValueError("Mix shares must sum to 1")return sum(rates[k] * mix[k] for k in mix)def capacity_million_tokens(rates: dict[str, float], mix: dict[str, float],quota_points: float = 100.0) -> float:"""Estimate how many tokens of mixed workload the quota can support per cycle(in millions)."""return quota_points / blended_rate(rates, mix)if __name__ == "__main__":# All values below are illustrative assumptionsrates = {"cache_read": 0.8,"fresh_input": 12.0,"cache_write": 15.0,"output": 60.0,}mix = {"cache_read": 0.90,"fresh_input": 0.05,"cache_write": 0.03,"output": 0.02,}print(f"Blended consumption: {blended_rate(rates, mix):.2f} points per million tokens")print(f"Capacity: {capacity_million_tokens(rates, mix):.1f} million tokens")
7. Caveats When Applying This Method
1. Measure each model separately. Deduction rules may differ across models; reusing one set of rates across models leads to wrong conclusions.
2. Record measurement conditions. Cache TTL, concurrency, time of day, and quota reset timing can all affect results. Each dataset should include the measurement date and configuration notes for reproducibility.
3. Watch for nonlinear rules. Some billing plans price usage above a threshold separately or adjust weights during peak hours. A linear model only applies to the range where these rules have not kicked in.
4. Distinguish theoretical from actual capacity. The model yields a theoretical value under a given mix. In practice, failed requests, retries, and tool-call overhead reduce usable volume, so leave headroom in your estimates.
5. Use a consistent basis when comparing plans. When comparing subscription tiers, run the same measurement process against the same workload statistics, and compare on “cost per unit of work” rather than sticker price or headline quota numbers.
8. Rollout Recommendations
For teams looking to control costs, proceed in this order:
- Instrument at the request level to record the four token counts and the model used for each call.
- Aggregate workload structure weekly to establish a baseline share for each token type.
- Run the isolated experiments described above to measure deduction rates, completing at least one full round per model.
- Feed rates and shares into the weighted model to estimate per-cycle capacity, and calibrate against actual usage.
- Wire the calibrated model into monitoring and alert when shares or unit cost shift noticeably.
The core of this workflow is replacing assumptions with measured data. The quota display is coarse, but with well-designed experiments and enough samples, you can produce estimates solid enough to drive decisions.
