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

推荐订阅源

Jina AI
Jina AI
Recent Announcements
Recent Announcements
Attack and Defense Labs
Attack and Defense Labs
P
Proofpoint News Feed
WordPress大学
WordPress大学
雷峰网
雷峰网
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - 叶小钗
I
Intezer
Hugging Face - Blog
Hugging Face - Blog
博客园 - 司徒正美
月光博客
月光博客
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
T
Threat Research - Cisco Blogs
有赞技术团队
有赞技术团队
T
Tailwind CSS Blog
S
Securelist
Cyberwarzone
Cyberwarzone
云风的 BLOG
云风的 BLOG
V
Visual Studio Blog
Stack Overflow Blog
Stack Overflow Blog
T
Tor Project blog
Project Zero
Project Zero
腾讯CDC
Recorded Future
Recorded Future
Help Net Security
Help Net Security
Spread Privacy
Spread Privacy
T
The Blog of Author Tim Ferriss
阮一峰的网络日志
阮一峰的网络日志
The Register - Security
The Register - Security
Google DeepMind News
Google DeepMind News
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
L
Lohrmann on Cybersecurity
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Security Latest
Security Latest
Cisco Talos Blog
Cisco Talos Blog
A
Arctic Wolf
N
News and Events Feed by Topic
D
DataBreaches.Net
V
Vulnerabilities – Threatpost
L
LangChain Blog
博客园 - 【当耐特】
V2EX - 技术
V2EX - 技术
Simon Willison's Weblog
Simon Willison's Weblog
Engineering at Meta
Engineering at Meta
The Last Watchdog
The Last Watchdog
Security Archives - TechRepublic
Security Archives - TechRepublic
D
Docker
C
CXSECURITY Database RSS Feed - CXSecurity.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 in LLMs: The Hidden Optimization Saving Millions of GPU Hours
Shrijith Venkatramana · 2026-06-15 · via DEV Community

Hello, I'm Shrijith Venkatramana. I'm building git-lrc, an AI code reviewer that runs on every commit. Star Us to help devs discover the project. Do give it a try and share your feedback for improving the product.


Every developer eventually discovers the same frustrating pattern.

Your application sends a 20,000-token prompt to an LLM. The first request takes 2 seconds. The next request contains the exact same 20,000 tokens plus a tiny user message at the end.

And somehow the model processes the entire thing again.

At least, that's what many developers assume.

Modern LLM systems have a trick called prompt caching that can dramatically reduce latency and cost by reusing work from previous requests. But unlike traditional application caches, prompt caching isn't storing generated text. It's storing something much deeper inside the model.

To understand how prompt caching works, we need to follow a prompt all the way through the transformer itself.

The Expensive Part of Processing a Prompt

When a prompt enters a transformer model, it isn't immediately generating text.

First, the model must process every input token through every layer of the network.

Imagine a prompt like:

System: You are a helpful coding assistant.

Project Documentation:
[20,000 tokens of documentation]

User: How does authentication work?

Before generating a single output token, the model performs:

  1. Tokenization
  2. Embedding lookup
  3. Multi-head attention
  4. Feed-forward networks
  5. Layer normalization

...across dozens or even hundreds of transformer layers.

For a large model, this preprocessing is often more expensive than generating a short answer.

If another user asks:

System: You are a helpful coding assistant.

Project Documentation:
[Same 20,000 tokens]

User: Explain the database schema.

Most of the prompt is identical.

Without caching, the model would recompute everything from scratch.

Prompt caching exists to avoid that waste.

The Key Insight: Cache Internal Transformer State, Not Text

A common misconception is that prompt caching stores prompt text.

That's not particularly useful because the model would still need to process the text again.

Instead, modern systems cache the transformer's internal representations.

After processing a token through the network, the model produces vectors that represent the token's state at various stages.

The most important cached data is usually:

  • Key vectors (K)
  • Value vectors (V)

These are generated during self-attention.

Once a prefix has been processed, those K/V tensors can often be reused.

Conceptually:

Prompt
  ↓
Token Embeddings
  ↓
Transformer Layers
  ↓
Key/Value Tensors
  ↓
Cache

When a future request begins with the same prefix, the system loads the cached tensors rather than recomputing them.

The model effectively starts from the middle of the computation.

Understanding KV Cache First

Prompt caching builds directly on a mechanism called the KV cache.

During inference, each attention layer creates:

Q = Query
K = Key
V = Value

Attention is computed roughly as:

\text{Attention}(Q,K,V)=\text{softmax}\left(\frac{QK^T}{\sqrt{d}}\right)V

When generating token 501, the model doesn't want to recompute attention for tokens 1-500.

Instead it stores the previous K and V tensors.

This is the standard KV cache used during autoregressive generation.

Prompt caching extends the same idea across requests.

Instead of caching:

Request A token 1-500

it caches:

Shared prompt prefix

which can then be reused by:

Request B
Request C
Request D

as long as the prefix remains identical.

What Actually Gets Stored?

Let's use a realistic example.

Suppose we have:

System Prompt: 2,000 tokens
Repository Documentation: 18,000 tokens
User Message: 100 tokens

Total:

20,100 tokens

Assume a model has:

  • 80 layers
  • Hidden size 8,192
  • Multiple attention heads

For each layer, the system stores K and V tensors for every processed token.

Conceptually:

Layer 1:
  K[20000]
  V[20000]

Layer 2:
  K[20000]
  V[20000]

...

Layer 80:
  K[20000]
  V[20000]

The cache may occupy hundreds of megabytes or even gigabytes depending on:

  • Context length
  • Layer count
  • Precision (FP16, BF16, FP8)
  • Number of heads

This is why prompt caching isn't free.

The system trades memory for computation.

GPU memory is expensive, but recomputing a 20,000-token prompt repeatedly is often even more expensive.

Prefix Matching: Why Exact Equality Matters

Most production systems perform prompt caching using prefix matching.

Consider:

[System Prompt]
[Documentation]
User: Explain auth

and

[System Prompt]
[Documentation]
User: Explain database

The shared prefix is:

[System Prompt]
[Documentation]

Everything after that differs.

The cache can be reused because the transformer state for the shared prefix is identical.

But even small changes can invalidate the cache:

Version 1:
Repository version: 2.1

Version 2:
Repository version: 2.2

That tiny change alters tokenization.

Different tokens produce different embeddings.

Different embeddings produce different K/V tensors.

The entire downstream computation changes.

This is why prompt caching systems often require exact token-level matches rather than semantic similarity.

How Providers Implement Prompt Caching

Different providers implement prompt caching differently, but the general architecture is similar.

Incoming Request
       ↓
Prefix Detection
       ↓
Cache Lookup
       ↓
Cache Hit?
    /      \
  Yes      No
   |         |
Load KV   Compute KV
   |         |
Generate Response

The difficult engineering problems include:

Cache Eviction

GPU memory is limited.

Providers must decide:

  • Which caches stay resident?
  • Which caches get removed?
  • Which users receive priority?

This resembles operating system page management more than traditional web caching.

Distributed Inference

Large serving systems spread requests across many GPUs.

A cached prefix may exist on GPU A while the next request arrives on GPU B.

Providers must either:

  • Move cache data
  • Route requests intelligently
  • Recompute the prefix

Multi-Tenant Isolation

A cache created for one customer should not leak information to another customer.

Production systems must maintain strict isolation boundaries.

Why RAG Applications Benefit So Much

Retrieval-Augmented Generation systems are perfect candidates for prompt caching.

Imagine a code assistant.

Every request includes:

System Prompt
Repository Rules
Architecture Docs
Coding Standards

Only the user question changes.

Without caching:

20,000 tokens processed
20,000 tokens processed
20,000 tokens processed
20,000 tokens processed

With caching:

20,000-token prefix processed once

Request 2:
reuse cache

Request 3:
reuse cache

Request 4:
reuse cache

Latency drops.

GPU utilization drops.

Cost drops.

This is one reason why modern coding assistants can feel much faster than their raw context sizes would suggest.

The Future: Beyond Exact Prefix Caching

Today's prompt caching mostly relies on exact token matches.

Researchers are exploring more ambitious ideas:

  • Partial-prefix reuse
  • Semantic cache matching
  • Attention state compression
  • Cross-session cache persistence
  • Hierarchical context caching

The challenge is preserving correctness.

Exact matches guarantee identical transformer states.

Approximate matches introduce uncertainty.

Future systems may combine both approaches, using exact caches when possible and semantic reuse when beneficial.

Final Thoughts

Prompt caching is one of the least visible but most impactful optimizations in modern LLM serving.

The important realization is that the cache is not storing text and it is not storing generated responses.

It is storing the expensive internal transformer state—primarily key and value tensors—that would otherwise need to be recomputed.

Once you understand that, prompt caching starts looking less like an application-level optimization and more like a CPU instruction cache or an operating system memory cache: a mechanism for avoiding repeated work by preserving computation that has already been paid for.

As context windows continue growing from tens of thousands to millions of tokens, do you think exact prefix caching will remain dominant, or will future LLM systems need semantic and approximate caching techniques to stay efficient?


*AI agents write code fast. They also silently remove logic, change behavior, and introduce bugs -- without telling you. You often find out in production.

git-lrc fixes this. It hooks into git commit and reviews every diff before it lands. 60-second setup. Completely free.*

Any feedback or contributors are welcome! It's online, source-available, and ready for anyone to use.


AI agents write code fast. They also silently remove logic, change behavior, and introduce bugs -- without telling you. You often find out in production.

git-lrc fixes this. It hooks into git commit and reviews every diff before it lands. 60-second setup. Completely free.

See It In Action

See git-lrc catch serious security issues such as leaked credentials, expensive cloud operations, and sensitive material in log statements

git-lrc-intro-60s.mp4

Why

  • 🤖 AI agents silently break things. Code removed. Logic changed. Edge cases gone. You won't notice until production.
  • 🔍 Catch it before it ships. AI-powered inline comments show you exactly what changed and what looks wrong.