記事一覧へ
## Claude が92%キャッシュヒット率を達成するケーススタディ
AIエージェントが1ステップを踏むたびに、税金を支払います。
ゼロから全てを再読み込みします。
システム指示。ツール定義。3ターン前にすでにロードしたプロジェクトコンテキスト。そのすべてを。毎ターン。
これがコンテキスト税です。長時間実行するエージェンティックワークフローにとって、これはAIインフラ全体の中で最もコストのかかるラインアイテムであることが多いです。
数式にするとこうです:20,000トークンのシステムプロンプトを50ターンにわたって実行すると、フル価格で請求され新たな価値をゼロ生み出さない100万トークンの冗長な計算が発生します。
解決策はプロンプトキャッシュです。しかし上手に使うには、内部で実際に何が起きているかを理解する必要があります。
## 変化するものと変化しないものから始める
何かを最適化する前に、エージェントのプロンプト(コンテキスト)の構造について明確に考える必要があります。
エージェントが送るすべてのリクエストには、根本的に異なる2つの部分があります:
**静的プレフィックス**:システム指示、ツール定義、プロジェクトコンテキスト、行動ガイドラインを含みます。このコンテンツはセッションのすべてのターンで同一です。
**動的テール**:ユーザーメッセージ、ツール出力、ターミナル観測結果。これはすべてのリクエストに固有で、会話が進むにつれて成長します。
この区別がすべてです。静的プレフィックスは、無意味に再計算し続けているコストのかかる部分です。動的テールは、実際に新鮮な計算が必要な唯一の部分です。
プロンプトキャッシュは、静的プレフィックスの数学的状態を保存することで機能し、将来のリクエストがその再計算を完全にスキップできるようにします。そのプレフィックスを1回処理するコストを払います。その後のすべてのターンはメモリから読み込みます。
## なぜこれが機能するか:トランスフォーマーが実際に何をするか
キャッシュがなぜこれほど効果的なのかを本当に理解するには、プロンプトを読み込むときにモデルの内部で何が起きているかを理解する必要があります。
すべてのLLM推論リクエストには2つのフェーズがあります:
### フェーズ1:プリフィル
ここでモデルがフル入力プロンプトを処理します。これはコンピュートバウンドで、コンテキスト内のすべてのトークンにわたって密な行列乗算を実行します。モデルはすべてを読み込み、その表現を構築します。これが遅く、コストのかかるフェーズです。
### フェーズ2:デコード
ここでモデルが出力トークンを1つずつ生成します。これは、モデルが重い計算を実行するよりも以前に計算された状態を読み込む時間が大半を占めるため、コンピュートバウンドではなくメモリバウンドです。
プリフィルフェーズ中に、トランスフォーマーは各トークンに対して3つのベクトルを構築します:Query、Key、Valueです。アテンションメカニズムはこれらを使って、各トークンがシーケンス内の他のすべてのトークンとどう関係するかを把握します。
ここで重要な洞察があります:KeyとValueのベクトルは、それより前に来るトークンにのみ依存します。特定のプレフィックスに対して一度計算されると、変更する必要は二度とありません。
以下の図はこれを視覚的に説明しています:
キャッシュなしでは、それらのKey-Valueテンソルはリクエストが完了した瞬間に捨てられます。次のリクエストはゼロから始まり、すべての20,000トークンに対して再計算します。
KVキャッシュはそれらのテンソルを保存することでこれを解決します。インフラはそれらを推論サーバー上に保持し、入力テキストの暗号ハッシュによってインデックスします。同じプレフィックスを持つ新しいリクエストが来ると、ハッシュが一致し、テンソルがただちに取得され、モデルはすべての計算をスキップします。
これにより生成されるトークンごとの計算複雑性がO(n²)からO(n)に下がります。50ターンにわたって繰り返される20,000トークンのプレフィックスでは、これは莫大な削減です。
## 経済性
価格構造を理解することが、このアーキテクチャの決断をこれほど重要にします。
Anthropicがモデルファミリー全体でキャッシュの価格を設定している方法がここにあります:
記憶すべき3つの数字:
- キャッシュリードのコストはベース入力価格の10%、キャッシュから読み込まれるすべてのトークンが90%割引
- キャッシュライトのコストはベース入力価格より25%高く、KVテンソルを保存するための小さなプレミアム
- 延長1時間キャッシングはベース価格の2倍
数式はキャッシュヒット率が高い状態を維持する場合にのみ機能します。それが実際にどのように見えるか、最高の実世界例を見てみましょう。
## Claude Code:30分セッションのウォークスルー
Claude Codeはまったく1つの目標を中心に構築されています:キャッシュを温かく保つこと。
具体的にそれが何を意味するかを理解するために、典型的な30分のコーディングセッションがどのように見えるかをウォークスルーして、何が請求され何が請求されないかを正確に追跡しましょう。
### 0分:セッション開始
Claude Codeがシステムプロンプトとツール定義をロードします。プロジェクトルートにあるCLAUDE.mdファイルも読み込み、コードベースと規約を説明します。このペイロードは通常20,000トークンを超えます。
これがセッション全体で最もコストのかかる瞬間です。すべてのトークンが新しい。しかしこのコストを払うのは1回だけです。
### 1〜5分:最初のコマンド
「認証モジュールを見て改善案を提案して」といった最初の指示を入力します。
Claude CodeはExplore Subagentを送り出します。コードベースをナビゲートし、ファイルを開き、grepコマンドを実行し、関連コードの全体像を構築します。これらすべてが動的テールに追記されます。
20,000トークンの静的基盤?すでにキャッシュにあります。$3.00/MTokの代わりに$0.30/MTokで読み込まれています。新しいツール出力とメッセージにのみお金を払っています。
### 6〜15分:ディープワーク
Plan Subagentが Explore Subagentからの結果を受け取ります。生の結果をそのまま渡す代わりに(これにより動的テールが不必要に膨張する)、Claude Codeは簡潔なサマリーを渡します。これによりサフィックスを管理可能な状態に保ち、キャッシュを効率的に維持します。
プランナーが構造化された実装プランを生成します。レビューして承認すると、Claude Codeが変更を加え始めます。このループの各ターンで20,000トークンのプレフィックスをキャッシュから読み込みます。各キャッシュヒットはTTLをリセットし、将来のターンのためにキャッシュを温かく保ちます。
### 16〜25分:イテレーション
調整を求めます。Claude Codeがアプローチを修正します。さらにツールコール、さらにターミナル出力。動的テールは成長していますが、これはセッション内の新しい固有のコンテンツのみを表しています。
この時点で、セッションは合計で数十万トークンを処理しています。しかし20,000トークンの基盤は毎ターンキャッシュから読み込まれています。
### 28分:/costを実行
キャッシュなしでは、このようなセッションは簡単に200万トークンを超えます。Sonnet 4.5レートで約$6.00です。
高効率でキャッシュを実行すると:
- トークンの大半はキャッシュから$0.30/MTokで読み込まれます
- 新しい動的テールトークンのみが新鮮に計算されます
実際には、単一タスクで80%以上のコスト削減が期待できます。それをすべてのユーザー、毎日に掛け合わせます。
セッションが続くにつれたシステムプロンプトレイアウトのサマリーはこうです:
## すべてを壊すルール
プロンプトキャッシュについて最も直感に反することがここにあります。
1 + 2 = 3。しかし 2 + 1 はキャッシュミスです。
インフラはプロンプトをハッシュします。ハッシュは暗号学の識別子です。ハッシュは、その順序が変わると変わります。2つの要素の順序が異なる場合でも。キャッシュが空になります。プレフィックス全体がフル価格で再計算されます。
これから導かれる3つのルール:
- セッション中にツールを追加したり削除したりしない。キャッシュされたプレフィックスにはツールが含まれます。ツールを変えると、その後のすべてが無意味になります。
- セッション中にモデルを切り替えない。キャッシュはモデル固有です。会話の途中で安いモデルに切り替えると、キャッシュ全体の再構築が必要になります。
- 状態を変えるためにプレフィックスを変えない。代わりにClaude Codeは、次のユーザーメッセージにシステムを思い出させるタグを追加します。プレフィックスは変わりません。
## あなたにとっての意味
上記のすべてがClaude Codeがキャッシュを処理する方法を説明しています。同じルールが自分のエージェントを作る場合にも適用されます。
プロンプトの構造化方法はこうです:
- 上部にシステム指示とルール。中途半端に変えない。
- 必要なすべてのツールを事前にロードする。追加したり取り除いたりしない。
- その後に取得したコンテキストとドキュメント。期間中は静的。
- 下部に会話の履歴とツールの出力。
オートキャッシングをオンにすると、会話が進むにつれてブレイクポイントが自動的に前進します。
Claude Codeが自身のキャッシュを管理しています。AnthropicはちょうどAPIにオートキャッシングを追加したので、自分のエージェントにも同じことができます。
オートキャッシングなしでは、トークンの境界がどこにあるかを覚えておく必要がありました。誤った境界はキャッシュに届かないことを意味しました。
コンテキストリミットに対してコンパクト化するためにキャッシュセーフなフォーキングを使います。同じシステムプロンプト、ツール、会話を使い、新しいメッセージとしてコンパクト化を追加します。
コンパクト化コールは直前のものとほぼ同じに見えます。キャッシュされたプレフィックスが再び使用されます。新しいものとして請求されるのはコンパクト化指示だけです。
APIが機能しているか確認するには、すべてのレスポンスの以下の3つのフィールドを監視してください:
- `cache_creation_input_tokens`:メモリに格納されたトークン
- `cache_read_input_tokens`:メモリから読み込まれたトークン
- `input_tokens`:通常通り処理されたトークン
キャッシュ効率スコアは、生成トークン数に対する読み込みトークン数です。アップタイムを監視するのと同じように監視してください。
## 重要なポイント
プロンプトキャッシュはオンにする機能ではありません。周囲に構築するアーキテクチャ上の規律です。
Claude Codeは、それを大規模に実現したときにそのフィールドがどのように見えるかの最良の例です。
キャッシュヒット率92%。コスト削減81%。
これがエージェントを作るためのブループリントです。税金を無視することはできません。それは存在します。重要なのは、それを払い続けるか、取り除くかだけです。
## 参考資料:
https://www.dailydoseofds.com/p/kv-caching-in-llms-explained-visually/
https://x.com/trq212/status/2024574133011673516?s=20
https://manus.im/blog/Context-Engineering-for-AI-Agents-Lessons-from-Building-Manus

prompt-cachingkv-cachellm-inferenceclaude-setupagent-ops
プロンプトキャッシュを明快に解説:Claudeが92%キャッシュヒット率を達成する仕組み
♥ 1,070↻ 159
原文を表示 / Show original
A case study on how Claude achieves 92% cache hit-rate
Every time an AI agent takes a step, it pays a tax.
It re-reads everything from scratch.
The system instructions. The tool definitions. The project context it already loaded three turns ago. All of it. Every single turn.
That's the context tax. And for long-running agentic workflows, it's often the most expensive line item in your entire AI infrastructure.
Here's the math: a system prompt with 20,000 tokens running over 50 turns means 1 million tokens of redundant computation billed at full price, producing zero new value.
The fix is prompt caching. But to use it well, you need to understand what's actually happening under the hood.
Start With What Changes and What Doesn't
Before you can optimize anything, you need to think clearly about the structure of an agent's prompt (context).
Every request your agent sends has two fundamentally different parts:
The static prefix: it includes system instructions, tool definitions, project context, behavioral guidelines. This content is identical across every single turn of a session.
The dynamic tail: user messages, tool outputs, terminal observations. This is unique to every request and grows as the conversation progresses.
This distinction is everything. The static prefix is the expensive part you keep recomputing for no reason. The dynamic tail is the only part that actually needs fresh computation.
Prompt caching works by storing the mathematical state of the static prefix so that future requests can skip recomputing it entirely. You pay to process that prefix once. Every subsequent turn reads from memory instead.
Why This Works: What a Transformer Actually Does
To really understand why caching is so effective, you need to understand what happens inside the model when it reads your prompt.
Every LLM inference request has two phases:
Phase 1: Prefill
This is where the model processes your full input prompt. It's compute-bound, meaning it runs dense matrix multiplications across every token in your context. The model reads everything and builds up a representation of it. This is the slow, expensive phase.
Phase 2: Decode
This is where the model generates output tokens, one at a time. It's memory-bound rather than compute-bound because the model spends most of its time reading previously computed state rather than running heavy calculations.
During the prefill phase, the transformer builds three vectors for each token: a Query, a Key, and a Value. The attention mechanism uses these to figure out how each token relates to every other token in the sequence.
Here's the critical insight: the Key and Value vectors depend only on the tokens that came before them. Once they're calculated for a given prefix, they never need to change.
The illustration below visually explains what we just discussed:
Without caching, those Key-Value tensors get thrown away the moment a request completes. The next request starts from scratch and recalculates them for all 20,000 tokens again.
KV caching solves this by storing those tensors. The infrastructure keeps them on the inference servers, indexed by a cryptographic hash of the input text. When a new request comes in with the same prefix, the hash matches, the tensors are retrieved immediately, and the model skips all that computation.
This drops the computational complexity from O(n²) per generated token down to O(n). For a 20,000-token prefix repeated across 50 turns, that's an enormous reduction.
The Economics
Understanding the pricing structure is what makes this architectural decision so consequential.
Here's how Anthropic prices caching across their model families:
Three numbers to internalize:
Cache reads cost 10% of the base input price, a 90% discount on every token read from cache
Cache writes cost 25% more than the base input price, a small premium to store the KV tensors
Extended 1-hour caching costs 2x the base price
The math only works if your cache hit rate stays high. Which brings us to the best real-world example of what that looks like in practice.
Claude Code: A 30-Minute Session Walkthrough
Claude Code is built entirely around one objective: keep the cache hot.
To understand what that means concretely, lets walk through how a typical 30-minute coding session looks like and track exactly what gets billed and what doesn't.
Minute 0: Session Start
Claude Code loads its system prompt and tool definitions. It also reads the CLAUDE.md file in your project root, which describes the codebase and conventions. This payload regularly exceeds 20,000 tokens.
This is the most expensive moment of the entire session. Every single token is new. But you only pay this cost once.
Minutes 1 to 5: First Commands
You type your first instruction, something like "look at the auth module and suggest improvements."
Claude Code dispatches an Explore Subagent. It navigates through the codebase, opens files, runs grep commands, and builds a picture of the relevant code. All of this gets appended to the dynamic tail.
The 20,000-token static foundation? Already in cache. Being read back at $0.30/MTok instead of $3.00/MTok. You're only paying for the new tool outputs and your message.
Minutes 6 to 15: Deep Work
The Plan Subagent receives the findings from the Explore Subagent. Rather than passing the raw results verbatim (which would blow up the dynamic tail unnecessarily), Claude Code passes a concise summary. This keeps the suffix manageable and the cache efficient.
The planner produces a structured implementation plan. You review it, approve it, and Claude Code starts making changes. Every turn in this loop reads the 20,000-token prefix from cache. Each cache hit resets the TTL, keeping the cache warm for future turns.
Minutes 16 to 25: Iteration
You ask for adjustments. Claude Code revises its approach. More tool calls, more terminal output. The dynamic tail is growing, but it represents only the new, unique content in this session.
At this point, the session has processed hundreds of thousands of tokens total. But the 20,000-token foundation has been read from cache every single turn.
Minute 28: Running /cost
Without caching, a session like this easily crosses 2 million tokens. At Sonnet 4.5 rates, that's around $6.00.
With caching running at high efficiency:
The vast majority of tokens are read from cache at $0.30/MTok
Only the new dynamic tail tokens are computed fresh
In practice, you'd expect somewhere in the range of an 80%+ cost reduction on a single task. Now multiply that by every user, every day.
To summarise here's how the system prompt layout looks are the session continues:
The Rule That Breaks Everything
Here is the most counterintuitive thing about prompt caching.
1 + 2 = 3. But 2 + 1 is a cache miss.
The infrastructure hashes the prompt. The hash is an identifier for cryptography. The hash changes if anything in that order changes, even if two elements are in a different order. The cache is empty. The whole prefix is recalculated at full price.
Three rules that follow from this:
Don't add or take away tools during a session. The cached prefix includes tools. Changing the tools makes everything that comes after it useless.
Never switch models mid-session. Caches are model-specific. Switching to a cheaper model mid-conversation requires rebuilding the entire cache.
Never change the prefix to change the state. Instead, Claude Code adds a tag to the next user message that reminds the system. The prefix never changes.
What It Means for You
Everything above explains how Claude Code handles caching. The same rules apply if you are making your own agent.
This is how to structure your prompts:
At the top are system instructions and rules. Don't change in the middle.
Load all the tools you'll need ahead of time. Don't add or take them away.
Retrieved context and documents after that. Static for the duration.
At the bottom, the history of the conversation and the tool's outputs.
With auto-caching turned on, the breakpoint moves forward automatically as the conversation goes on.
Claude Code is in charge of its own cache. Anthropic just added auto-caching to its API, so you can do the same for your own agent.
Without auto-caching, you had to remember where the token boundaries were. A wrong boundary meant not getting to the cache.
Use cache-safe forking to compact for the context limit. Use the same system prompt, tools, and conversation, then add the compaction as a new message.
The compaction call looks almost exactly like the last one. The cached prefix is used again. The only thing that is billed as new is the compaction instruction.
To see if an API is working, keep an eye on these three fields in every response:
cache_creation_input_tokens: tokens put into memory
cache_read_input_tokens: tokens read from memory
input_tokens: tokens worked as usual
Your cache efficiency score is the number of read tokens compared to the number of creation tokens. Keep an eye on it the same way you keep an eye on uptime.
Key Takeaways
Prompt caching is not a feature you turn on. It is an architectural discipline you build around.
Claude Code is the best example of what that field looks like when it's done on a large scale.
A cache hit rate of 92%. A cut in costs of 81%.
This is the blueprint if you are making agents. You can't ignore the tax; it exists. The only thing that matters is whether you are paying for it or getting rid of it.
References:
https://www.dailydoseofds.com/p/kv-caching-in-llms-explained-visually/
https://x.com/trq212/status/2024574133011673516?s=20
https://manus.im/blog/Context-Engineering-for-AI-Agents-Lessons-from-Building-Manus