Learn · KV cache

Prompt Caching: How It Works, From API Providers to Your Own GPUs

What prompt caching is, how KV cache prefix reuse works, how OpenAI, Anthropic, Gemini, and Bedrock handle it, and how to run it on your own GPUs.
A man with short brown hair wearing a dark blue long-sleeve shirt against a light gray background.

Matt Tanner

Oct 9, 2026

17 min read

IN THIS GUIDE

An agent can send the same system prompt, tool definitions, and earlier conversation on every turn. Without cache reuse, the model processes that shared prefix again before generating a new token. As the history grows, repeated prefill can take up a larger share of the request’s work.

Prompt caching is how providers and inference engines avoid that repeat: keep the attention state for the opening of a prompt and reuse it when the next request starts the same way. We’ll look at how that reuse works, how OpenAI, Anthropic, Google Gemini, and Amazon Bedrock expose it, and how to use it on models you serve yourself.

What is prompt caching?

Prompt caching reuses the attention state a large language model already computed for a prompt prefix it has seen before, so only the tokens after the matching prefix need processing. That state is the KV cache. You get a shorter time to first token (TTFT) and cheaper input tokens, and the response is still generated fresh.

Prompt caching stores the model’s intermediate key and value tensors, rather than a saved answer. A hit restores the attention state for the matching prefix and lets generation continue from there. The model still produces the response afresh; the saving comes from skipping work it would otherwise repeat.

What gets cached is whatever stays the same across requests: system instructions, tool definitions, reference documents such as a contract or a source file, and older conversation history in a multi-turn chat. Anthropic builds the cacheable prefix from tools, then system, then messages, in that order. The latest user message is usually the part that changes, so its new tokens are processed fresh.

How prompt caching works under the hood

Prefill is the expensive part

Every request runs in two phases. Prefill computes keys and values for every token of the input prompt; decode then generates the answer one token at a time, reading them back. The longer the prompt, the longer prefill runs before the first token appears, and that wait is the part a cache hit shortens.

Prompt caching skips prefill for a matching prefix; it doesn’t accelerate the generation of new tokens. The reusable state is the KV cache: per-layer key and value tensors built as the model processes each token. That state can occupy substantial memory per request, and its footprint changes as requests advance and finish.

Standard prefix caching is keyed on the exact prefix

A token’s keys and values depend on the earlier tokens it can attend to. The same sentence following a different history therefore doesn’t necessarily produce the same KV state. Conventional prompt caching starts at the beginning and stops at the first difference, because the remaining state was computed against a different prefix.

Exact matching applies to the rendered prefix, including the content and settings that become part of it. On Anthropic’s API, all text and images through the cache-controlled block must match. Similar wording isn’t enough to reuse that state.

Prefix-only matching limits plain reuse, but selective recomputation can extend it. A cached document chunk carries state from its original preceding context. CacheBlend reuses that state and recomputes a small subset of tokens to account for the new context, recovering the interactions that plain chunk reuse misses. That matters for retrieval-augmented generation (RAG), where documents can appear after different instructions or other retrieved chunks.

Blocks, hashes, and the first miss

Engines don’t compare prompts token by token. vLLM splits the KV cache into fixed-size blocks and hashes each full block from three inputs: the hash of the block before it, the tokens in the block, and extra values such as LoRA IDs, image hashes, and cache salts. Because each hash includes its parent, a block’s identity encodes the entire prefix up to that point. A lookup walks the chain from the first block and stops at the first hash it can’t find.

Block size determines how much of a partial match is reusable. In vLLM’s four-token-block example, a 14-token request shares its first 10 tokens with an earlier request, but only 8 hit the cache. The third block matches at just two positions, so it can’t be reused as a full block. vLLM caches complete blocks rather than treating a partially matching block as a hit.

Anthropic writes an entry at a cache breakpoint using a cumulative hash of the prefix through that block. Change a block at or before the breakpoint and the hash changes too. The entry for that longer prefix no longer matches, even if most of its text stayed the same.

Prompt caching block hashes: request 2 reuses five of six blocks, while a timestamp changed in the system prompt makes request 3 miss every block
A changed token in an early block changes every hash after it, so the cache serves nothing past that point; block sizes and counts are illustrative.

Where the cache lives and why it expires

vLLM’s local prefix-cache blocks occupy GPU memory alongside model weights and active requests. In vLLM, blocks that no running request needs go into a free queue, and when space runs out, it evicts the least recently used cached block at the head of that queue. A hit “touches” a block and removes it from the queue; a block nobody touches for a while is next to go.

Providers manage a version of the same constraint across a fleet. OpenAI keeps cached state on individual machines and routes using a hash of the initial prompt tokens. Traffic above 15 requests per minute can overflow to another machine, so an identical prefix still needs to reach a machine holding an unexpired matching entry. Each provider sets a time to live (TTL) for reuse eligibility, and some charge a token-based premium when a request writes reusable state.

Prompt caching vs. KV caching vs. semantic caching

Prompt caching and KV caching get used interchangeably, but they describe different scopes. KV caching happens inside every generation; prompt caching keeps that KV cache after the request ends and reuses it for a later one. Semantic caching and response caching store answers instead.

TechniqueWhat is storedMatch ruleSkipsOutput
Within-request KV cachingKeys and values for every token processed so farNone; scoped to one requestRecomputing earlier tokens at each decode stepGenerated normally
Prompt / prefix caching (across requests)The same KV tensors, kept for a reusable prefixExact prefix, block by block, up to the first differencePrefill for the matched prefixGenerated fresh after the prefix
Semantic cachingAn earlier prompt’s embedding and its final answerEmbedding similarity above a thresholdThe whole model callThe stored answer
Response caching (exact match)A final answer keyed on the requestByte-identical request hashed to the same cache keyThe whole model callThe stored answer

Semantic caching works differently from the first two rows: it runs before generation, matches by meaning, and when it hits, the model never runs. That suits repeated FAQ-style questions and goes wrong when two similar-looking questions need different answers, which is the subject of how semantic caching works and where it stops. The layers stack: a semantic miss can still hit a warm prefix cache.

What prompt caching saves, and what it doesn’t

Latency

A cache hit removes prefill work for the matched prefix, so the saving shows up in time to first token and grows with the length of the shared prefix. Streaming speed after the first token doesn’t change, because caching does nothing for decode. OpenAI’s new prewarm option exists for this reason: an application can write shared instructions and reference material into the cache at startup, before a user asks anything, so the first real request starts warm.

Cost

Providers discount cached tokens on the input side and leave output tokens alone. On OpenAI’s GPT-5.6 and later models, a cache write costs 1.25x the uncached input rate and a read costs 0.1x on most of them (0.05x on GPT-6.1 Sol). At the 0.1x rate, one write followed by nine full reads costs 2.15x the prefix’s ordinary input price, against ten full-price passes without caching. Anthropic also charges more to write the cache than to read it, with rates that vary by model and cache lifetime. Per-model rates and the break-even math are in our full prompt caching pricing breakdown for Anthropic, Bedrock, OpenRouter, and Groq.

The write premium is the part that bites. A breakpoint on content that never repeats pays 1.25x for tokens that would have cost 1x uncached, so caching the wrong span costs more than not caching at all.

When it doesn’t help

Caching pays only when the same prefix comes back, long enough and often enough. These are the cases where it doesn’t:

SituationWhy there’s no saving
The shared prefix is below the minimumMinimums run from 512 to 4,096 tokens depending on provider and model, and Anthropic processes shorter prompts without caching and returns no error
Something early in the prompt changes per requestA timestamp or user ID near the start changes the prefix for every request. With an explicit Anthropic breakpoint after that value, each request writes a new entry instead of reusing the previous one.
Traffic is too sparse to keep the cache warmHosted entries expire after a window without reads, from minutes to hours, and on your own GPUs they are evicted when memory is needed
Parallel requests arrive before the first one respondsOn Anthropic’s API, an entry is available for reuse once the first response starts. Requests sent earlier can’t read that new entry yet.
The work is mostly decodeLong answers to short prompts spend their time generating, which caching doesn’t touch

Context edits can break agent cache reuse: summarizing history, adding a tool, or refreshing an early timestamp moves the first difference toward the start of the prompt.

How API providers handle prompt caching

All four providers below reuse an exact prefix. They differ in who places the cache boundaries and how you see the result.

ProviderModeHow you see cache hits in the responseWhere to read details
OpenAIAutomatic by default; explicit breakpoints on GPT-5.6 and laterusage.input_toke ns_details.cache d_tokens and cache_write_toke nsOpenAI prompt caching guide
AnthropicExplicit breakpoints on content blocks, plus automatic caching set with one top-level cache_controlcache_read_input _tokens and cache_creation_i nput_tokensClaude prompt caching docs
Google GeminiImplicit caching on by default for Gemini 2.5 and newer; explicit caching (Beta) through a cache object with a TTLCached token count in usage_metadata (generateContent API)Gemini context caching docs
Amazon BedrockImplicit caching (best effort) and explicit cache checkpoints, varying by model and APIcacheReadInputTo kens and cacheWriteInputT okens (Converse API)Bedrock prompt caching guide

Two rows carry caveats. Gemini’s implicit caching can reduce input costs, but the saving isn’t guaranteed. Its explicit caching guarantees the cached-input discount and adds storage charges for the time the cache exists, with a TTL you can set. On Bedrock, implicit caching is best effort, and meeting the conditions for an explicit checkpoint doesn’t guarantee a hit.

OpenAI launched its GPT-6 caching update on September 22, 2026, with a 30-minute reuse window for eligible shared prefixes. The update also introduced a Prompt Caching Dashboard, miss diagnostics such as tools_changed, and finer control over cache boundaries. For GPT-5.6 and later, caching requires at least 1,024 tokens; prompt_cache_options.mode selects implicit or explicit-only behavior, prompt_cache_breakpoint marks a boundary, and a request can write up to four entries. The available TTL is 30m, measured from the latest write or reuse of the prefix.

Two details are easy to miss. GPT-5.6 and later charge for cache writes and use prompt_cache_options.ttl; earlier OpenAI models had no write charge and used prompt_cache_retention. The September announcement advertised up to 90% savings, while current cached-input discounts reach 95%, reflecting GPT-6.1 Sol’s 0.05x read rate. Use the rate for the model you deploy rather than the launch headline.

With a hosted API, the provider decides where the cache lives, how long it survives, and what it costs. You can shape your prompt to hit it more often, but you can’t change the cache.

Prompt caching on self-hosted models

When you serve an open-weight model yourself, prompt caching stops being a line on a bill and becomes a memory-management decision you own. The engine does the prefix matching; how much survives, where, and for how long depends on what you run under it.

vLLM automatic prefix caching

vLLM‘s automatic prefix caching (APC) retains KV state from earlier requests and reuses it when a new prompt starts with the same tokens. It is the block-hash scheme described above, and current vLLM turns it on by default for generative models. In the v0.30.0 tag, an unset enable_prefix_caching falls back to a per-model support check that is true for decoder-only and hybrid generative models and false for encoder-decoder and attention-free ones. Set enable_prefix_caching explicitly in the example below to make the intended configuration clear:

from vllm import LLM
llm = LLM(model="lmsys/longchat-13b-16k", enable_prefix_caching=True)

On vllm serve, the equivalent flags are --enable-prefix-caching and --no-enable-prefix-caching. To check that it’s working, compare vllm:prefix_cache_hits with vllm:prefix_cache_queries; both count tokens, so their ratio is your prefix cache hit rate. For multi-tenant serving, a per-request cache_salt limits reuse to requests carrying the same salt, so if each tenant gets its own salt, one tenant can’t infer another’s cached content from response timing. These vLLM details were checked against the docs on October 3, 2026, so pin the version you deploy.

SGLang and RadixAttention

SGLang uses a radix tree to find and manage shared prefixes. Its runtime retains KV state across requests, follows matching branches in the tree, and evicts unused state with an LRU policy. Cache-aware scheduling helps requests reuse those branches. The match rule is still a prefix; the tree makes shared paths efficient to find.

Where single-instance prefix caching runs out

The built-in cache in either engine lives in one instance’s GPU memory, and that’s where its limits come from.

LimitWhat happensWhy
GPU memory fillsCached blocks are evicted, least recently used first, and the next request that needs them pays full prefillFree blocks are reclaimed from the head of an LRU queue
The pod restartsThe cache starts emptyThe block pool is allocated in GPU memory when the engine’s KV cache manager initializes
Requests land on another replicaA miss, even if a neighboring replica holds the same prefixEach replica reuses only its own local cache
The shared document isn’t at the startNo reuse for that documentMatching runs from the first token to the first difference

vLLM has its own answer to the first three rows. Its opt-in OffloadingConnector retains completed KV blocks in host memory, with optional filesystem, S3-compatible object storage, or peer-to-peer tiers behind it. A hit loads those blocks back to the GPU. Instances that share a filesystem directory or bucket can read each other’s blocks, and the peer-to-peer tier pulls blocks from another instance once your router names the peer. The match rule remains the prefix, so the last row stays a miss. For repeated documents and history, keeping the KV cache past a pod restart also requires storage that outlives the pod.

Extending the cache with LMCache

LMCache is the open-source KV caching engine our founders created, and it remains open source. Its standalone server manages reusable KV state separately from the inference engine, so an engine crash doesn’t destroy the server’s cache. CPU memory, local storage, and remote backends provide capacity beyond the GPU, with reuse across requests, sessions, and compatible engine instances. Available backends include local disk, Redis/Valkey, Mooncake, and S3-compatible object storage.

vLLM attaches through a KV connector, LMCacheMPConnector in the recommended multiprocess mode, and the LMCache quickstart also documents an SGLang integration that runs in multiprocess mode only. Non-prefix reuse comes through CacheBlend, the selective recomputation described earlier, and it is what clears the last row of the table.

Tensormesh Platform

Tensormesh Platform is the managed layer we build on LMCache for teams running vLLM on Kubernetes. It is not a serving engine and does not replace vLLM, which keeps doing the prefix matching it already does. vLLM’s OffloadingConnector is configuration you assemble per deployment; we manage the Platform’s cache tiers together on the cluster. GPU memory holds active work, host memory holds the hot set, and filesystem-backed storage retains a larger cache. Compatible state saved outside an inference pod can be reused after that pod restarts.

Cross-node sharing, listed as Preview in v1.0.0, lets a node retrieve compatible cached work from another node instead of recomputing it. Helm handles installation, and a web UI, CLI, observability, and multi-tenancy cover ongoing operations. Requests share a cache domain by default. Supply a different cache_salt for each tenant to separate cache reuse.

Content can repeat throughout a prompt without forming a shared prefix. The Platform supports non-prefix reuse for dense models through CacheBlend, which our research team published at EuroSys 2025. On RepoAgent, a documentation agent, prefix caching hit 3.4% of tokens while 85.9% of the prompts were reused, just not as a prefix, in part because file paths and project structure appear within the first 200 characters of the prompt. That is our own measurement on one agent workload, not a prediction for yours.

Tensormesh Platform runs with vLLM on Kubernetes with NVIDIA or supported AMD Instinct GPUs through ROCm. It uses filesystem-backed storage; SGLang support is next, and the compatibility matrix lists the verified models and the version set to deploy. The cache also runs only alongside models you serve in your own environment. It doesn’t attach to a model accessed through a hosted provider’s API, so Tensormesh Platform cannot cache your Claude or OpenAI API calls; for prefix-state reuse on those calls, use the provider’s caching features.

vLLM default prefix cache in one replica's GPU memory compared with Tensormesh Platform tiers across nodes: GPU memory, host memory and filesystem-backed storage with cross-node sharing
Left, vLLM’s default prefix cache in one instance’s GPU memory; right, the three tiers Tensormesh Platform manages across nodes, where only saved, compatible state can be reused after a pod restart.

How to structure prompts for higher cache hit rates

The rules are the same for a hosted API and for vLLM, because the match rule is the same.

Do thisBecause
Put system instructions, tool definitions, and reference documents first, and the user query lastThe prefix ends at the first difference. Put timestamps and user-specific content after the reusable material so they don’t disrupt the shared beginning.
Keep timestamps, user IDs, and request IDs out of the system promptOne per-request value near the top changes every hash after it
Keep tool definitions fixed and in a fixed orderTools sit near the front of the prefix on OpenAI and Anthropic; OpenAI suggests tool_choice set to "none" or allowed_tools instead of removing definitions
Serialize JSON deterministically, with sorted keysThe same object with a different key order is a different token sequence
Append to conversation history instead of trimming the middleSummarizing, compacting, or truncating earlier history can alter the prefix and reset reuse for the affected portion
Separate tenants on purposeprompt_cache_key on OpenAI and cache_salt on vLLM keep one customer’s cache accounting or reuse apart from another’s

Then measure. OpenAI defines the token cache-hit rate as cached tokens divided by input tokens, Anthropic reports cache_read_input_tokens separately from input_tokens, and on vLLM the ratio of the two prefix cache counters does the same job. When the number drops after a deploy, diff the first few thousand tokens of the prompt before looking anywhere else; OpenAI’s diagnostics tool will name the reason on its side.

Where to go from here

Prompt caching keeps and reuses the KV cache for an exact prompt prefix. On a hosted API, your lever is the prompt, so keep everything before the user query byte-stable. On your own models, you also decide how much cache to keep, where, and for how long, and the prefix rule is the one limit that more tiers and nodes won’t lift. Either way, measure the hit rate on real traffic before you change anything else.

Contact our team to discuss prompt caching for the models you serve yourself.

Frequently asked questions

  1. Is prompt caching the same as KV caching?

    No. KV caching happens inside every generation: the model keeps keys and values for earlier tokens so each new token doesn’t recompute them. Prompt caching keeps that KV cache after the request ends and reuses it for a later request that starts with the same prefix. Inference engines call the same idea prefix caching.

  2. Does prompt caching change the model’s output?

    No. A prefix-cache hit restores state the model would otherwise recompute, and generation continues normally from that state. Anthropic’s caching doesn’t alter output-token generation, and vLLM’s prefix-cache design preserves model outputs. Each OpenAI response is generated afresh, so identical requests can still produce different sampled text.

  3. How long does a prompt cache last?

    Minutes to hours, depending on the provider, the model, and the retention setting you choose. Each provider documents its own window, and most refresh it every time the entry is read, so check the OpenAI and Gemini caching docs for current values. On your own GPUs, an entry lasts until memory pressure evicts it, unless you offload it to host memory or storage.

  4. Does prompt caching reduce output token costs?

    No. Discounts apply to cached input tokens only, and output tokens are billed at the normal rate. Caching doesn’t speed up generation after the first token either, because decode work is unchanged. If your bill is dominated by long answers to short prompts, prompt caching will barely move it.

  5. Can you use prompt caching with open-weight or self-hosted models?

    Yes. vLLM’s automatic prefix caching and SGLang’s RadixAttention both reuse KV cache for shared prefixes, and current vLLM enables prefix caching by default for generative models. To keep the cache beyond one instance’s GPU memory, across restarts, or across nodes, add an offloading layer such as vLLM’s OffloadingConnector, LMCache, or Tensormesh Platform.

  6. How does prompt caching reduce inference costs?

    Prompt caching reduces inference costs by skipping prefill for the matched prefix, and the savings scale with how long that prefix is and how often it repeats. On a hosted API, it shows up as discounted cached input tokens; on your own GPUs, it shows up as compute you don’t spend, which leaves capacity for more requests on the same hardware.

WRITTEN BY

A man with short brown hair wearing a dark blue long-sleeve shirt against a light gray background.

Matt Tanner

Developer Relations

KV cache calculator

Size the cache for your model, context length and batch.

RELATED GUIDES

PagedAttention Explained: How Paged Attention Stores the KV Cache in Blocks

What Is LMCache?

Semantic Caching: How It Works, and Where It Stops

How to Calculate KV Cache Size: A Step-by-Step Sizing Method

Put it into practice

Keep KV cache beyond a single request

Tensormesh runs LMCache as a self-hosted layer, so the context your GPUs already processed can be reused across requests and nodes.