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

推荐订阅源

P
Privacy International News Feed
H
Help Net Security
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Blog — PlanetScale
Blog — PlanetScale
T
The Blog of Author Tim Ferriss
Y
Y Combinator Blog
Microsoft Security Blog
Microsoft Security Blog
Stack Overflow Blog
Stack Overflow Blog
Jina AI
Jina AI
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
D
Docker
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
I
InfoQ
Engineering at Meta
Engineering at Meta
H
Heimdal Security Blog
月光博客
月光博客
有赞技术团队
有赞技术团队
S
SegmentFault 最新的问题
V
Vulnerabilities – Threatpost
K
Kaspersky official blog
C
Cisco Blogs
Microsoft Azure Blog
Microsoft Azure Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
MongoDB | Blog
MongoDB | Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
L
LINUX DO - 热门话题
H
Hackread – Cybersecurity News, Data Breaches, AI and More
T
Tor Project blog
M
MIT News - Artificial intelligence
L
LINUX DO - 最新话题
P
Privacy & Cybersecurity Law Blog
Google DeepMind News
Google DeepMind News
宝玉的分享
宝玉的分享
Security Archives - TechRepublic
Security Archives - TechRepublic
IT之家
IT之家
博客园_首页
F
Full Disclosure
T
Threatpost
www.infosecurity-magazine.com
www.infosecurity-magazine.com
阮一峰的网络日志
阮一峰的网络日志
Security Latest
Security Latest
S
Security @ Cisco Blogs
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
AI
AI
Hacker News - Newest:
Hacker News - Newest: "LLM"
H
Hacker News: Front Page
A
Arctic Wolf
C
Check Point Blog
S
Securelist
A
About on SuperTechFans

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
Why your Anthropic prompt caching probably isn't working (and the npm package I built to fix it)
Leonhail Pay · 2026-05-20 · via DEV Community

I'm a solo developer with about five years of experience, mostly outside AI. The last few months I've been getting serious about it — reading docs, building small things with Claude, learning how it differs from the web APIs I'm used to.

While I was setting up Anthropic prompt caching for a project, I got stuck on a question I couldn't easily answer: how do I know it's actually working? The docs explained the cache_control API and the 90% discount on cached tokens. But the only way to verify a call had hit the cache was to manually parse cache_read_input_tokens from the response usage on every request. Nobody seems to do this.

That gap turned into my first published npm package, prompt-cache-optimizer. This post is what I learned about the four ways prompt caching silently fails, and what the package does to catch them.

What prompt caching is supposed to do

When you call messages.create with a long, stable prefix (system prompt, tool definitions, retrieved documents), Anthropic lets you mark a cache_control breakpoint. On the first call, that prefix gets written to the cache at ~1.25x the normal input rate. On any subsequent call within the cache TTL, the cached tokens are read back at 10% of the input rate.

That's a 90% discount on whatever portion of your prompt is stable. For a chatbot that re-sends a 10K-token system prompt every turn, this is the difference between a $5K monthly bill and a $500 one.
The math is incredible. The execution is finicky.

The four ways prompt caching silently fails

  1. Misplaced breakpoints
    cache_control markers cache everything before them in the request. Put the breakpoint in the wrong place and you cache the wrong things. Worse, the call still succeeds — Anthropic happily processes it, you get a normal response, you just paid full price.

  2. Prefix drift across calls
    The cache only hits if the cacheable prefix is byte-identical to what was cached. If you reorder your tools array between calls, or shuffle retrieved documents, or insert a timestamp anywhere in your system prompt — the prefix is different, cache misses, you pay full price.

Worse, you also pay the 1.25x write cost to cache the new (now-different) prefix, which expires in 5 minutes if nothing else hits it. So you're paying more than you would without caching at all.

  1. TTL expiration
    Anthropic recently dropped the default cache TTL from 1 hour to 5 minutes. A lot of setups that "had caching working" started silently regressing — calls that came in 6 minutes apart instead of 4 minutes started missing the cache. Nobody got an error. The bill just went up.

  2. No measurement
    The only way to verify any of the above is to parse cache_read_input_tokens and cache_creation_input_tokens from every single response, compute a hit rate, and compare against an expected baseline. Nobody does this. Most teams "set up caching" once, watch the first response come back with high cached tokens, and assume it works forever.

The wrapper I built
I shipped a small TypeScript package called prompt-cache-optimizer that fixes the measurement problem and warns about the other three.

It's a drop-in wrapper for @anthropic-ai/sdk. Use it exactly like the SDK:

import { CachedAnthropic, placeBreakpoints } from "prompt-cache-optimizer";

const client = new CachedAnthropic({
  apiKey: process.env.ANTHROPIC_API_KEY!,
  warnIfHitRateBelow: 0.6,
});

const { system, messages } = placeBreakpoints({
  system: longSystemPrompt,
  messages: conversation,
  strategy: "after-system",
});

const response = await client.messages.create({
  model: "claude-sonnet-4-6",
  max_tokens: 1024,
  system,
  messages,
});

console.log(response.cacheInfo);
// {
//   hit: true,
//   cachedTokens: 8420,
//   uncachedTokens: 312,
//   cacheWriteTokens: 0,
//   dollarsSaved: 0.024,
//   dollarsSpent: 0.001
// }

Enter fullscreen mode Exit fullscreen mode

Every response gets a cacheInfo field with the parsed numbers. The client also tracks aggregate stats:

console.log(client.stats());
// {
//   totalCalls: 142,
//   cacheHits: 124,
//   hitRate: 0.873,
//   totalCachedTokens: 1_240_000,
//   dollarsSaved: 3.72,
//   dollarsSpent: 1.41,
// }

Enter fullscreen mode Exit fullscreen mode

And when something looks wrong, it emits passive warnings instead of throwing:

  • cache-write-without-read → your cacheable prefix changed call-over-call (the silent failure mode)
  • low-hit-rate → rolling cache hit rate dropped below your threshold
  • no-cache-control-found → you forgot to mark anything cacheable
  • unknown-model → pricing unknown, dollar accounting skipped

Route them anywhere you like:

new CachedAnthropic({
  apiKey,
  onWarning: (event) => logger.warn(event),
});

Enter fullscreen mode Exit fullscreen mode

Real numbers
The included example processes 5 questions reusing a large system prompt. Here's the actual output:

Five calls. The first writes to cache (cost: a tiny bit more than uncached). Calls 2-5 each hit the cache.

  • 80% hit rate (4 hits, 1 miss — the first call always misses since that's when the cache gets written)
  • $0.017 saved on $0.020 spent
  • Same workload without caching would have cost $0.037 — a 46% reduction

At higher call volumes the proportions get even better. A chatbot answering 1000 questions/day with a 10K-token system prompt easily hits 70%+ cost reductions.

How big the install is
The package is ~50KB unpacked, has zero runtime dependencies, and treats @anthropic-ai/sdk as a peer dependency. It does not phone home, store payloads, or require an account.

Roadmap
v0.1 is intentionally focused on measurement and explicit helpers. Coming up:

  • v0.2 — auto-placement of cache_control breakpoints based on observed prompt stability (no more manual placeBreakpoints())
  • v0.3 — safe message/tool reordering to maximize the stable prefix
  • v0.4 — OpenAI and Gemini prompt caching support
  • v1.0 — persistent stats adapter, middleware mode

Try it

npm install prompt-cache-optimizer @anthropic-ai/sdk

Enter fullscreen mode Exit fullscreen mode

If you find it useful, a GitHub star is the single biggest signal that helps other developers find it. If it saves you real money on your Anthropic bill, I'd love to hear about it — file an issue or DM me.