惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

T
Tenable Blog
月光博客
月光博客
雷峰网
雷峰网
WordPress大学
WordPress大学
博客园 - 司徒正美
Last Week in AI
Last Week in AI
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
V
Visual Studio Blog
H
Help Net Security
Engineering at Meta
Engineering at Meta
Google DeepMind News
Google DeepMind News
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
S
Security @ Cisco Blogs
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
爱范儿
爱范儿
W
WeLiveSecurity
J
Java Code Geeks
Forbes - Security
Forbes - Security
H
Hacker News: Front Page
T
Threatpost
The Cloudflare Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
N
Netflix TechBlog - Medium
Latest news
Latest news
V2EX - 技术
V2EX - 技术
小众软件
小众软件
T
The Blog of Author Tim Ferriss
A
Arctic Wolf
B
Blog RSS Feed
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
I
InfoQ
C
Check Point Blog
N
News | PayPal Newsroom
Cyberwarzone
Cyberwarzone
V
V2EX
TaoSecurity Blog
TaoSecurity Blog
P
Privacy & Cybersecurity Law Blog
Microsoft Security Blog
Microsoft Security Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
D
DataBreaches.Net
F
Fortinet All Blogs
阮一峰的网络日志
阮一峰的网络日志
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
IT之家
IT之家
K
Kaspersky official blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Google DeepMind News
Google DeepMind News
C
CXSECURITY Database RSS Feed - CXSecurity.com
www.infosecurity-magazine.com
www.infosecurity-magazine.com

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Prompt Caching With the Claude API: A Practical Guide
GDS K S · 2026-04-29 · via DEV Community

I noticed a pattern looking at three months of Anthropic invoices. The same 8 KB system prompt was getting billed full price on every request. Same instructions, same tool definitions, same RAG context, charged again every turn. The fix takes about ten lines of code and cuts the input bill by roughly 90 percent on cached tokens. This guide is the version of that fix I wish I had bookmarked a year ago.

TL;DR

Question Short answer
What does it do? Stores a prefix of your prompt server-side so later requests skip re-encoding it
How much does it save? Cache reads cost 10 percent of the base input rate, so up to 90 percent off cached tokens
What does it cost to write? First write costs 1.25x base input (5-minute TTL) or 2x (1-hour TTL)
When does it pay off? Any prefix reused at least twice within the TTL window
Smallest cacheable chunk? 1024 tokens for Sonnet and Opus, 2048 tokens for Haiku
Where do I put the marker? On the last block of the chunk you want cached

1. What prompt caching actually is

When you send a Message to the Claude API, Anthropic encodes your full prompt every time. System instructions, tool schemas, retrieved documents, prior turns, every part. Caching adds an opt-in: you mark a content block as a cache breakpoint, and Anthropic stores the encoded state of everything up to that point. The next request that starts with the same exact bytes reads from the cache instead of recomputing.

Three things to internalize:

The cache is a prefix cache. Order matters. Same system prompt, same tools, same first message in the array. If anything in the prefix differs by even one token, you get a cache miss and pay full input price.

Each breakpoint is ephemeral with a TTL of either 5 minutes (default) or 1 hour. The clock resets every time you read the cache, so a chatty conversation keeps its cache warm without re-paying the write cost.

You get up to four breakpoints per request. Smart layering matters: tools at the deepest level, then system, then static context, then the conversation tail. Each breakpoint extends the cached prefix one layer outward.

2. The cost math, with numbers

For Claude Sonnet 4.6 at the public rate of three dollars per million input tokens, here is what one mid-size system prompt costs across ten requests in a five-minute window.

Scenario Per request 10 requests Effective rate
No caching, 8 KB prefix (~2k tokens) $0.0060 $0.060 $3.00/Mtok
5m cache, first miss + 9 hits $0.0075 first, $0.0006 after $0.0129 $0.65/Mtok
1h cache, first miss + 9 hits $0.0120 first, $0.0006 after $0.0174 $0.87/Mtok

The 5-minute TTL pays for itself after the second request. The 1-hour TTL pays for itself after the third. Use 1-hour only when you know the prefix lives longer than 10 minutes between calls; otherwise stick with the default 5m and let the cache renew on each read.

Output tokens are not affected. Caching only changes the input side.

3. The smallest useful implementation

Take the static parts of your prompt and tag the last block with cache_control. Everything before that block gets cached; everything after stays dynamic.

TypeScript

import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic();

const SYSTEM_PROMPT = `You are a code reviewer for a TypeScript monorepo.
[... 1500 more tokens of style guide, examples, repo conventions ...]`;

async function review(diff: string) {
  const response = await client.messages.create({
    model: "claude-sonnet-4-6",
    max_tokens: 1024,
    system: [
      {
        type: "text",
        text: SYSTEM_PROMPT,
        cache_control: { type: "ephemeral" }, // 5m TTL by default
      },
    ],
    messages: [{ role: "user", content: diff }],
  });

  console.log({
    cache_creation: response.usage.cache_creation_input_tokens,
    cache_read: response.usage.cache_read_input_tokens,
    fresh_input: response.usage.input_tokens,
  });

  return response;
}

Enter fullscreen mode Exit fullscreen mode

The first call returns a non-zero cache_creation_input_tokens and bills the 1.25x write multiplier on the system prompt. Every later call within 5 minutes returns a non-zero cache_read_input_tokens and bills the 0.1x read rate. The diff itself stays uncached because it sits after the breakpoint.

Python

import anthropic

client = anthropic.Anthropic()

SYSTEM_PROMPT = """You are a code reviewer for a TypeScript monorepo.
[... 1500 more tokens of style guide, examples, repo conventions ...]"""

def review(diff: str):
    response = client.messages.create(
        model="claude-sonnet-4-6",
        max_tokens=1024,
        system=[
            {
                "type": "text",
                "text": SYSTEM_PROMPT,
                "cache_control": {"type": "ephemeral"},  # 5m default
            }
        ],
        messages=[{"role": "user", "content": diff}],
    )

    print({
        "cache_creation": response.usage.cache_creation_input_tokens,
        "cache_read": response.usage.cache_read_input_tokens,
        "fresh_input": response.usage.input_tokens,
    })

    return response

Enter fullscreen mode Exit fullscreen mode

For a 1-hour TTL, change the breakpoint to {"type": "ephemeral", "ttl": "1h"}. That is the only difference.

4. Layering breakpoints in a real request

The four-breakpoint cap is generous when you stack the layers right. Here is the pattern that has worked across every production prompt I have audited.

┌─────────────────────────────┐
│  tools (rarely change)      │  breakpoint 1
├─────────────────────────────┤
│  system prompt              │  breakpoint 2
├─────────────────────────────┤
│  static context / RAG docs  │  breakpoint 3
├─────────────────────────────┤
│  conversation history       │  breakpoint 4
├─────────────────────────────┤
│  current user turn          │  uncached
└─────────────────────────────┘

Enter fullscreen mode Exit fullscreen mode

Each breakpoint extends the cached prefix down one layer. If the user adds a turn but the docs and tools and system stay the same, you pay full rate only on the new user turn and the model's response.

const response = await client.messages.create({
  model: "claude-sonnet-4-6",
  max_tokens: 2048,
  tools: [
    { name: "search_docs", description: "...", input_schema: {/*...*/} },
    {
      name: "run_query",
      description: "...",
      input_schema: {/*...*/},
      cache_control: { type: "ephemeral" }, // breakpoint 1
    },
  ],
  system: [
    {
      type: "text",
      text: SYSTEM_PROMPT,
      cache_control: { type: "ephemeral" }, // breakpoint 2
    },
  ],
  messages: [
    {
      role: "user",
      content: [
        { type: "text", text: RETRIEVED_DOCS,
          cache_control: { type: "ephemeral" } }, // breakpoint 3
        { type: "text", text: priorTurnSummary,
          cache_control: { type: "ephemeral" } }, // breakpoint 4
        { type: "text", text: currentUserMessage }, // uncached
      ],
    },
  ],
});

Enter fullscreen mode Exit fullscreen mode

A nuance worth knowing: a single breakpoint actually creates two cache entries internally, one for the 5m TTL and one for the 1h TTL if you have configured both anywhere in the request. The usage object reports both with cache_creation.ephemeral_5m_input_tokens and cache_creation.ephemeral_1h_input_tokens.

5. The failure modes

Caching is unforgiving about exact-prefix matching. The four ways I have seen it silently miss in production:

A timestamp slipped into the system prompt. Someone added Today is ${new Date().toISOString()} at the top. Every request now has a unique prefix. Every request misses cache. Move the timestamp to the user turn, or round it to the nearest hour.

Trailing whitespace. Two engineers concatenated the prompt with + "\n" in different places. The bytes differ. The cache misses.

Tool order changed. Tools are part of the prefix. If you sort them by frequency or load them from a Map (insertion order), make sure the order is stable across processes.

Below the size floor. Sonnet caches blocks of at least 1024 tokens; Haiku needs 2048. A 600-token system prompt will not cache at all, and you will see no cache_creation_input_tokens in the response. Either pad it or accept the full rate.

6. When to pick 1h over 5m

Decision rule that has held up:

Use case TTL
Interactive chat, agent loops 5m
Background batch jobs every minute 5m
Cron job every 15 minutes 1h
Long-running review session, hourly digests 1h
Single-shot one-off no cache

The 1-hour TTL costs 2x base on the write. You need at least three reads inside that hour to come out ahead versus the 5m TTL, which only needs two. If your traffic is spiky and unpredictable, 5m is the safer default.

7. The honest tradeoffs

Four caveats nobody mentions in the marketing copy.

Caching shifts cost, it does not remove it. Output tokens still bill at the full rate. If your bill leans on output (long generated reports, code synthesis), caching helps less than the 90 percent headline suggests.

Cache hit rate is observable but not always predictable. Anthropic does not guarantee a write will be readable on the next request; in practice it always lands for me, but the docs are clear that the cache write runs on a best-effort basis. Build with the assumption that any individual request might miss.

Tool definitions count as part of the prefix. Adding a new tool invalidates the cache for every prompt that uses tools. Plan tool schema changes during low-traffic windows.

No public API exists for manually evicting a cache. You either let the TTL expire or change the prefix. This matters when you ship a system-prompt update and want to confirm the old version no longer lives in the cache.

8. The bottom line

Prompt caching is the highest-ROI single change you can make to a Claude API integration today. Eight extra lines of config, no architecture change, and a 90 percent cut on the largest line item in most invoices. The reason for the under-use is not technical; the docs treat caching as a feature flag, not as the default.

Set the breakpoint, log cache_read_input_tokens for a week, and watch what your bill does. If you are running tools, set four breakpoints, not one. If you are running interactive sessions, stick with the 5m TTL.

The cheaper the input gets, the more the architecture starts to look like the cache is the prompt and the prompt is the cache. That shift is worth thinking about before the next round of API price changes lands.


GDS K S · thegdsks.com · building Glincker · follow on X @thegdsks

The bill that caching hides is not the next one. The one you would have paid in twelve months if you never set the breakpoint.