ByteCosts
measure-prompt-cache-hit-rate.mdx

AI Coding Agents

Prompt cache metrics for token usage and cost

Use three prompt cache metrics together. Measure the share of input tokens served from cache, flag turns that create unusually large cache entries, and price the read, write, and ordinary input buckets at their own rates. This shows whether the cache is reusing expensive context and whether that reuse is reducing the cost of your workload.

Define three metrics per model and route

Normalize each response to three disjoint counts. Call them R for tokens read from cache, W for tokens written, and U for ordinary uncached input. In this accounting, a token billed as a write belongs in W. Determine whether the provider’s input counter includes or excludes cache activity before using it as a denominator.

MetricCalculationWhat it tells you
Token hit ratiosum(R) / (sum(R) + sum(W) + sum(U))Share of all input served at the cached read rate.
Write churnTurns with large W divided by measured turns in the same cohort. Also track their combined W.How often a workload recreates a sizable part of its context, and how much it writes when it does.
Effective input multiplier(U + read_mult R + write_mult W) / (U + R + W)Cost of the measured input relative to processing the same quantity at the model’s ordinary input rate.

For churn, start with your ordinary warm-turn append size as a reference. Flag writes that exceed that size by more than the variation you expect in tool results. Mark initial fills and planned compaction in the event stream. Keep those writes in the cost report and inspect them separately from unexpected rebuilds. This lets you distinguish frequent small writes as a conversation grows from recurring large writes that consume the savings from reuse.

For a lifetime price split, replace the single write term with the sum of each write bucket times its rate multiplier. The token denominator still includes the total write count just once. For mixed models or price tiers, sum the estimated input costs and divide by the sum of the ordinary-input baseline costs for those requests. Averaging multipliers across models gives equal weight to requests with unequal input prices and sizes.

When choosing a churn threshold, check both absolute volume and context share. A write that is small against a long document can be a full rebuild for a shorter session. Plot write size against total input for warm turns, then inspect the points away from your usual append pattern. If they all come from the same session phase, compare each phase with its own baseline. A workload that intentionally rebuilds at task boundaries can have a steady churn rate until an application change makes rebuilds happen mid-task.

Track usable usage separately from the number of completed turns. An apparent improvement can come from excluding a route whose counts stopped arriving. Compare coverage and traffic mix before attributing a change to prompt layout.

Map native usage fields before aggregating

These fields are documented as of November 30, 2026. Paths in the table are relative to usage except where the table specifies response metadata or an SDK field. Use the shape returned by the endpoint your application actually calls. A gateway may translate field names or return only part of the upstream breakdown.

Provider and APIRead countWrite and ordinary input accounting
Anthropic Messagescache_read_input_tokenscache_creation_input_tokens is writes and input_tokens is ordinary input. Add all three for total input.
Azure OpenAI and OpenRouter Chat Completionsprompt_tokens_details.cached_tokensAzure documents prompt_tokens_details.cache_write_tokens on Standard pay-as-you-go deployments with GPT-5.6 and later model families. OpenRouter documents the same two fields. Verify whether prompt_tokens includes writes on the endpoint you call before deriving ordinary input. OpenAI’s prompt caching guide documents the Responses usage fields.
OpenAI Responsesinput_tokens_details.cached_tokensinput_tokens is total input. On GPT-5.6 and later subtract reads and input_tokens_details.cache_write_tokens to get ordinary input. Earlier models have no separate write charge.
Gemini Interactionsusage.total_cached_tokens in the Python and JavaScript SDKsThe documented Interactions API supports implicit caching. Use a verified total-input count from your integration before calculating a token ratio.
Gemini on VertexcachedContentTokenCount in response metadataThe field covers implicit and explicit reuse. Account for any model-specific writes and explicit storage separately.
DeepSeekprompt_cache_hit_tokensprompt_cache_miss_tokens is the complementary input bucket. Use hit plus miss for total input in this reporting shape.
Mistral Chat Completionsprompt_tokens_details.cached_tokensUse prompt_tokens for total prompt input. The documented billable uncached count is prompt_tokens - prompt_tokens_details.cached_tokens.
xAI Responses and Chat Completionsinput_tokens_details.cached_tokens in Responses or prompt_tokens_details.cached_tokens in Chat CompletionsUse input_tokens for Responses and prompt_tokens for Chat Completions. The documented usage examples report reads.
Bedrock ConversecacheReadInputTokenscacheWriteInputTokens is writes and inputTokens is ordinary input when caching is enabled. Add all three for total input. cacheDetails gives write lifetime information.

Anthropic breaks creation down under cache_creation into ephemeral_5m_input_tokens and ephemeral_1h_input_tokens. OpenAI’s supported Responses models report ttl_30m_tokens and ttl_12h_tokens under input_tokens_details.cache_write_tokens_details. OpenAI counts billed reads separately from upgrades charged as writes. Use the split fields to price creation, then reconcile their sum against the total write field. OpenAI’s GPT-5.6 cache changes

Treat a missing read field as unknown unless the provider documents omission as a miss. Mistral documents that cached_tokens can be zero or omitted when no tokens are served from cache. Count an omitted read field as zero on a completed Mistral response with otherwise usable usage. If the entire usage object is missing, keep the measurement unknown. Bedrock also documents an exception for Amazon Nova implicit reuse, which its cache usage fields do not report. Keep those requests out of a comparison that assumes every read is visible. Gemini explicit storage belongs in a separate cost line. It has a time component that the token-only multiplier omits.

Keep a raw usage sample for a cold fill, a warm read, and a turn that reads an earlier prefix while writing new context. Use those samples to check the adapter before publishing ratios. A warm read with zero writes can confirm where reads appear, but leaves open how a nonzero write is counted in the total. For endpoints with lifetime-specific write counters, sum the lifetime buckets and reconcile them against the aggregate before pricing the turn. For Anthropic Messages, also add ordinary, read, and write tokens to reconstruct total input. A comparison across routes depends on applying each endpoint’s accounting rules before rolling up the counts.

Apply rates for the actual model and write lifetime

The following read multipliers and baseline write rates come from the committed ByteCosts first-party rates, with additional lifetime multipliers from the provider docs. Multipliers express cost per token relative to ordinary input. Use the rates for the route you pay for. AI provider pricing index

ModelRead multiplierWrite multiplier or reporting basis
Claude Sonnet 5.5 and Opus 5.50.05×1.25× for five minutes or 2× for one hour.
Claude Haiku 5.50.10×1.25× for five minutes or 2× for one hour. Base rates rise for prompts over 100,000 tokens. Convert to dollars using the applicable tier.
OpenAI GPT-6.2 Sol0.05×1.25× for the default 30 minutes or 2.5× for 12 hours on supported Responses requests.
OpenAI GPT-5.6 Sol0.10×Same documented lifetime multipliers as GPT-6.2 Sol.
Gemini 3.5 Flash0.10×Keep explicit cache storage separate from the token multiplier.
DeepSeek V4 ProAbout 0.033×Price the reported miss bucket at the ordinary input rate.
Mistral Large 40.10×No separate write rate in the committed data.
xAI Grok 4.70.25×No separate write rate in the committed data.
Bedrock Converse modelsModel-specificUse the selected model’s AWS rates and the write lifetime.

A rate comparison across models needs one more step. A smaller multiplier on an expensive base rate can still produce a larger bill. Convert estimated weighted input tokens to currency with the price per million input tokens. Keep output costs in a separate column so output changes do not obscure what happened to the cache.

Work through a misleading request hit rate

Assume two completed Claude Sonnet 5.5 turns with five-minute writes. The short turn reads 900 of 1,000 input tokens. The long turn reads zero of 9,000 and writes 8,000. A dashboard that counts any read as a hit reports 50%. The token hit ratio is only 9% because 900 / 10,000 = 0.09. Averaging the two per-turn token percentages also overstates reuse, at 45%.

Across the pair, ordinary input is 1,100 tokens, reads are 900, and writes are 8,000. The weighted input is 1,100 + 0.05 900 + 1.25 8,000 = 11,145 ordinary-input equivalents. The effective multiplier is 11,145 / 10,000 = 1.1145. Using the committed $2 per million ordinary input tokens, the estimated input cost is $0.02229. The ordinary-input baseline is $0.02000. If the 8,000 written tokens instead billed as ordinary input, the same 9% hit ratio would accompany an estimated $0.01829 input cost. The write column explains the difference.

Log completed turns and set local targets

This illustrative Python snippet logs the input buckets for Claude Sonnet 5.5 using five-minute writes. Feed it the usage object from a completed request with known pricing and write lifetime. Supply a churn threshold chosen from your own workload. The emitted cost weight is in ordinary-input token equivalents.

import json

def log_cache_usage(usage, rebuild_threshold):
    read = usage["cache_read_input_tokens"]
    write = usage["cache_creation_input_tokens"]
    ordinary = usage["input_tokens"]
    print(json.dumps({
        "read_tokens": read,
        "write_tokens": write,
        "ordinary_tokens": ordinary,
        "total_input_tokens": read + write + ordinary,
        "weighted_input_tokens": ordinary + 0.05 * read + 1.25 * write,
        "large_write": write >= rebuild_threshold,
    }))

Add the resolved model, endpoint, and price tier in the surrounding logger. Sum the counters before taking ratios and leave the ratio undefined when total input is zero. Split cold starts, resumed sessions, and expected compaction from ordinary warm turns when investigating a regression. Report the share of completed requests with usable counters so changes in observability stay visible.

As an illustrative rule of thumb for warm, prefix-heavy traffic, start by investigating below 80% token reads and aim for an 80% to 95% band only if observed stable context can account for that share. For a workload that regularly appends large tool results, derive a local band from expected reusable tokens over total input. A 50% to 80% read share can be consistent with that workload design. These are investigation ranges, independent of provider guidance. For cost, an effective multiplier below 1.0 means the measured input buckets cost less than ordinary input would, before any separate storage charges.

Build the dashboard and verify the next regression

  • Validate each adapter against a cold request and a completed follow-up. Confirm that the three buckets add up and that each priced lifetime accounts for the expected writes.
  • Chart token hit ratio, large-write frequency, and weighted input together for each model and route. Add a view of total write volume so infrequent large rebuilds stay visible.
  • When the read share falls and writes rise, compare the request prefixes. For a proxy rollout, verify marker translation and usage reporting with the same test workload.
  • When a planned rewrite raises churn, use the compression break-even calculation to estimate how many later reads must repay it. Compare estimated input cost over the entire interval with the previous configuration.

Sources

Interactive report

  • The Cache Breakers: The agent sends another ordinary-looking request. A timestamp, a shuffled tool list, or a model switch just changed what the API can reuse. See what each edit puts on the invoice.

How this note was produced

Drafted with AI assistance from committed ByteCosts pricing snapshots and deterministic cost formulas. Figures are grounded in the linked sources (last updated 2026-11-30). Read our editorial & automation policy, inspect the methodology, or report a discrepancy.

Prompt cache metrics for token usage and cost. ByteCosts. Updated 2026-11-30. https://bytecosts.com/blog/measure-prompt-cache-hit-rate/

Sources