Guide

How to use Claude prompt caching to reduce API cost

Mark the stable start of your prompt with cache_control and pay a fraction of the input price on every repeat. Breakpoints, pricing, TTL and hit rate.

プリペイド、サブスクなしREST でも MCP でもモデル・データ・エージェントを 1 つのキーで

このページはまだ翻訳されていないため、英語で表示しています。

1 回目:キャッシュに書き込み2 回目以降:キャッシュから読み取りシステムプロンプトキャッシュ済みドキュメントキャッシュ済み履歴キャッシュ済み新しいメッセージ新しいメッセージ課金される入力

Every Claude request resends the whole prompt: tool definitions, system prompt, reference documents and every earlier turn. In an agent loop or a long chat, the same tokens are billed again on each turn. Anthropic prompt caching fixes that. You mark where the stable part of the prompt ends, the first request writes that prefix to a cache, and later requests that start with the same bytes read it back at a fraction of the input price. This guide covers billing, breakpoints, what breaks a cache, and how to check that it works.

01

How Claude prompt caching works

Claude caches only what you mark. A cache breakpoint is a cache_control field, {"type": "ephemeral"}, on a content block. Everything up to and including that block becomes the cached prefix. Claude assembles a prompt in a fixed order, tools first, then the system prompt, then messages, so a breakpoint on the last system block caches the tools and the system prompt together.

You can set up to four breakpoints in one request, so the long-lived part (tools and instructions) and the growing part (the conversation) are cached separately. Or put one cache_control at the top level of the request: Claude then caches everything up to the last block and moves the breakpoint forward as the conversation grows.

A hit needs an exact prefix match on the same model. Prefixes shorter than the model's minimum length are not cached at all; Anthropic's caching guide lists the minimum for each model.

02

How cached tokens are billed

A Claude response splits its input into three counts, each with its own price:

Usage fieldWhat it countsBilled at
input_tokensInput after the last breakpointInput price
cache_creation_input_tokensPrefix written to the cache by this callCache-write price
cache_read_input_tokensPrefix read from the cacheCache-read price
output_tokensThe answer, thinking includedOutput price

A write costs a little more than plain input, and a read costs a small fraction of it. On claude-sonnet-5.5, for example, the docs list the cache write at 1.25 times the uncached input price and the cache read at one twentieth of it. Caching therefore pays for itself on the second request: one write plus one read comes to 1.3 times the input price for the prefix, against 2 times for sending it uncached twice.

モデルコンテキスト入力出力キャッシュ読み取り
Claude Fable 5.1
claude-fable-5.1
1M$10.00$50.00$0.25
Claude Opus 5.5
claude-opus-5.5
1M$4.00$20.00$0.20
Claude Sonnet 5.5
claude-sonnet-5.5
1M$2.00$10.00$0.10
Claude Haiku 5.5
claude-haiku-5.5
1M$0.10$0.50$0.01
Claude Fable 5
claude-fable-5
1M$10.00$50.00$1.00
Claude Opus 5
claude-opus-5
1M$5.00$25.00$0.50
Claude Sonnet 5
claude-sonnet-5
1M$2.00$10.00$0.20
Claude Opus 4.8
claude-opus-4.8
1M$5.00$25.00$0.50
Claude Opus 4.7
claude-opus-4.7
1M$5.00$25.00$0.50
Claude Opus 4.6
claude-opus-4.6
1M$5.00$25.00$0.50
Claude Sonnet 4.6
claude-sonnet-4.6
1M$3.00$15.00$0.30
Claude Opus 4.5
claude-opus-4.5
200K$5.00$25.00$0.50
Claude Sonnet 4.5
claude-sonnet-4.5
1M$3.00$15.00$0.30
Claude Haiku 4.5
claude-haiku-4.5
200K$1.00$5.00$0.10

100 万トークンあたりの米ドル価格(カタログからリアルタイム表示)。

The table shows live input, output and cache-read prices for every Claude model. Each model's page, such as Claude Sonnet 5.5, also lists the cache-write price, and Models & pricing has the formula for one call.

03

How long a cache lives (TTL)

Anthropic keeps a cache entry for five minutes by default, and every read resets that timer. A conversation whose turns arrive less than five minutes apart keeps its cache warm for as long as it runs. One that pauses for longer pays for a fresh write on its next turn, then reads again from there.

04

What invalidates a cache

Because the match is on exact bytes, any change in the prefix invalidates the cache from that point on:

A timestamp or request id in the system prompt

It breaks everything after it on every call. Put dynamic values in the latest user message.

Changing tool definitions

Tools render first, so adding, removing or reordering a tool, or serializing its schema with keys in a different order, invalidates the whole cache.

Switching models

Each model has its own cache.

Changing thinking settings

Turning thinking on or off, or changing the effort level between turns, invalidates the cached messages.

Rewriting history

Summarizing or trimming earlier turns changes the prefix, so expect one fresh write after each rewrite.

Landing on a different channel

That one is about routing.

05

Why routing matters: one conversation, one channel

A cache lives on the channel that wrote it. A gateway that spreads requests over several channels could send turn two of a conversation to a different channel than turn one, and turn two would pay for a new write instead of a read.

Lovely Router keeps each conversation on the channel that holds its cache. It fingerprints a conversation from its system prompt plus its first user message, which stay the same as a chat grows, so this works without code changes. Claude Code's session header, metadata.user_id or an x-session-id header take priority when present. A pin lasts up to an hour and renews while the conversation is active. If the pinned channel is busy, the turn waits briefly rather than paying for a new write; if it fails, the turn moves to a healthy channel and the pin follows.

Send your own x-session-id when your app changes the first user message between turns, for example when it summarizes old history. Prompt caching lists every rule.

06

Walkthrough: cache a long system prompt in Python

This chat answers questions about a long handbook. The handbook goes in a system block with a breakpoint, and a top-level cache_control caches the conversation as it grows. Install the SDK with pip install anthropic, create a key in API keys and export it as LOVELY_API_KEY.

import os
import anthropic

client = anthropic.Anthropic(
    base_url="https://lovelyrouter.com",
    api_key=os.environ["LOVELY_API_KEY"],
)

HANDBOOK = open("handbook.md").read()  # long, stable reference text
history = []


def ask(question):
    history.append({"role": "user", "content": question})
    response = client.messages.create(
        model="claude-sonnet-5.5",
        max_tokens=1024,
        system=[{
            "type": "text",
            "text": HANDBOOK,
            "cache_control": {"type": "ephemeral"},  # breakpoint 1: the handbook
        }],
        cache_control={"type": "ephemeral"},  # breakpoint 2: the conversation so far
        messages=history,
        extra_headers={"x-session-id": "handbook-chat-1"},  # optional: one id per conversation
    )
    history.append({"role": "assistant", "content": response.content})

    u = response.usage
    written = u.cache_creation_input_tokens or 0
    read = u.cache_read_input_tokens or 0
    total = u.input_tokens + written + read
    print(f"written {written}, read {read}, uncached {u.input_tokens}, hit rate {read / total:.0%}")
    return next(block.text for block in response.content if block.type == "text")


print(ask("What is the refund window?"))
print(ask("Does it apply to digital goods?"))

The first call writes the handbook and the first question, so written is large and read is zero. From the second call on, read covers everything sent before and written only the newest answer and question. If an older anthropic package rejects the top-level cache_control argument, upgrade it or keep only the system breakpoint. If both counts stay at zero, the handbook is below the model's minimum.

07

Check your cache hit rate

Hit rate is the share of input read from the cache: cache_read_input_tokens divided by all three input counts. You can see it in three places:

In your code

, from usage, as in the walkthrough.

In Logs

, per call: In (uncached input plus cache writes) and Cached, with Cache write, Cache hit and Affinity in the details. The dashboard overview shows your hit rate across all calls.

, per channel group over the last 24 hours.

Affinity shows whether routing kept the cache reachable: sticky means the turn went back to its conversation's channel, explicit that you sent a session id, new that it was a first call or its pin had expired.

Reading a low hit rate

new on every turn means the system prompt or the first user message changes between turns: look for a timestamp, or send x-session-id. sticky with an empty Cached column means the prefix is below the model's minimum or carries no cache_control.

08

Pitfalls

Caching the wrong end

Stable content first, variable content last. A breakpoint after a per-user greeting caches nothing other requests can reuse.

Calling Claude through the OpenAI-compatible endpoint

cache_control is only certain to work in Anthropic Messages format, so call Claude at /v1/messages; see the Anthropic API guide.

Switching keys mid-conversation

Pins are scoped to your API key, the model and the channel group, so another key starts a new pin.

Reading input_tokens alone

It is only the uncached remainder; add the cache counts for the full prompt size.

09

Frequently asked questions

?
How much does Claude prompt caching save?+

It depends on how much of each request repeats a prefix. Cache reads cost a small fraction of the input price (a twentieth on claude-sonnet-5.5) and the first write a little more than plain input, so a prefix used even twice costs less than sending it uncached twice. Agents and long chats, where most input is history, save the most.

How long does a Claude prompt cache last?+

The cache TTL is five minutes by default, according to Anthropic, and every read resets the timer. Lovely Router keeps a conversation pinned to the channel that holds its cache for up to an hour while it stays active.

Why is cache_read_input_tokens always zero?+

Either the prefix changes between requests, it is shorter than the model's minimum, it carries no cache_control, or more than five minutes passed between requests. The Affinity and Cache write details in Logs tell you which.

Do I pay for cache writes?+

Yes. cache_creation_input_tokens are billed at the model's cache-write price, a little above its input price. Each model's page and GET /v1/models list it.

Does prompt caching work with Claude Code?+

Yes. Claude Code's session header keeps every turn of a session on one channel, so its prompt cache stays warm. AI coding agents covers the setup.

Next, read Prompt caching for the routing rules and how GPT and Gemini cache, the Claude API page for every Claude model, and pricing for how the prepaid balance works. Hitting rate limits instead? See Claude API 429 errors.

モデル・データ・エージェントを 1 つのプリペイドキーで

サブスクリプションなし。チャージして必要な分だけ使い、すべての請求をログで確認できます。