/claude-kit:llm-caching-strategiesfrom Claude Kit SDLC
Covers LLM-specific caching strategies: provider prompt/prefix caching, semantic response caching, similarity thresholds, scope gates, and invalidation. Use when cutting LLM cost or latency.
Ships in Claude Kit SDLC. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
An LLM application does not have "a cache" — it has several, they reuse different things, and they fail in different ways. Prompt/prefix caching is provider-side, matches exactly on a leading span of the request, and can only ever make a call cheaper. Semantic caching is application-side, matches approximately on meaning, and skips the model call entirely — which is where the savings are and where the risk of confidently answering the wrong question lives. This skill covers how to pick, key, gate, invalidate, and measure each layer. For conventional key-value caching mechanics (Redis clients, namespacing, SCAN invalidation, stampede protection, eviction policy) use redis-caching-patterns; this skill assumes that substrate and stays on the LLM-specific concerns.
Four distinct things get called "the cache". Say which one you mean in the design doc, because the win, the risk, and the owner differ:
| Layer | Reuses | Saves | Primary failure |
|---|---|---|---|
| Exact response cache | Normalized request → stored answer | The whole call | Covers very little real traffic |
| Semantic response cache | Similar intent → stored answer | The whole call | False hit — wrong or stale answer served confidently |
| Prompt / context cache | Already-processed input prefix (provider-side) | Input tokens and prefill latency | Output is still generated, so savings cap out on the input side |
| KV / prefix cache | Attention state inside the serving runtime | Prefill work, routing locality | Memory pressure; tenant boundaries inside a shared runtime |
These compose. A well-built system runs an exact cache in front of a semantic cache in front of a prompt-cached model call. Confusing them produces cost projections wrong by an order of magnitude. Take one support question that shows up ten thousand times: with prompt caching you pay for ten thousand generations, each somewhat cheaper on its input side. With a semantic response cache, only the first one runs at all.
The KV/prefix layer is only yours to tune if you operate the inference runtime. On a hosted API it is the provider's implementation detail, surfaced to you as the prompt cache.
A reusable prefix extends exactly as far as the first token that changes. Everything after the first volatile byte is recomputed. So prompt layout, not prompt content, is the dominant lever on hit rate.
Order request content by descending stability:
Invalidation is hierarchical: change a block and you invalidate it plus everything after it. A prompt that leads with a timestamp has no cacheable prefix at all, no matter how stable the following 40k tokens are.
The recurring cache killers are all prefix contaminants, and all of them look harmless in review:
Relocating per-request scratch state from the system block down to a trailing user turn is usually the highest-leverage single fix available. One published case reports a hit rate climbing from roughly 7% to 84% on that change alone, with overall spend down about 59%. Treat that as the shape of the win, not a promise.
Two practical constraints to check against your provider's current documentation rather than memory: there is a minimum cacheable prefix length (on the order of a thousand-plus tokens for larger models, several thousand for the small ones — below that the provider simply will not cache), and a cap on the number of cache breakpoints per request (a small single-digit number). Place breakpoints deliberately at the boundaries you listed above; do not sprinkle them.
Do not reflexively wrap the cache boundary around the entire context. There is published evidence that indiscriminately caching everything can make latency worse, because the bookkeeping outweighs the reuse once the tail of the context turns over on every call. Put the boundary where the content is genuinely stable and nowhere else.
Prompt caching is not free. Providers differ, but the shape is: a cache read costs a fraction of the base input rate (on the order of a tenth), while populating an entry may cost a write premium above base input — materially so for longer-lived cache tiers, and not at all on providers that cache implicitly.
Model the blended cost relative to base input as:
blended = (1 - hitRate) * writeMultiplier + hitRate * readMultiplier
Two consequences worth putting in the design doc:
Because the write is a real cost, the traffic pattern matters as much as the prompt: a stable prefix touched once an hour against a five-minute TTL never reads its own write. Move to a longer-lived tier, batch the traffic, or do not cache. Where the provider supports it, you can pre-warm an entry ahead of a known burst — send one request that generates almost no output, then check the usage payload to confirm the entry was actually written before the traffic arrives.
Rates change frequently. Re-derive the break-even from current pricing at design time; never hard-code a multiplier into a runbook.
A semantic cache embeds the incoming query, does a nearest-neighbour lookup against previously answered queries, and — if the best match clears a similarity threshold — returns the stored answer without consulting the model. That last clause is the entire risk. You are electing to answer some share of user questions out of a lookup table indexed by approximate meaning.
The error costs are asymmetric and this asymmetry should drive every decision below:
So: start conservative, loosen only against evidence.
Do not adopt a number from a blog post. Cosine scores are not comparable across embedding models, across versions of the same model, or across domains — a 0.92 that is a safe hit in one corpus is a false hit in another. Derive it:
Thresholds are per answer class, not global. A keyboard-shortcut question and a refund-eligibility question should not share a number. Model this explicitly: attach an answer class to each cached entry, and let each class carry its own threshold, TTL, and whether it is cacheable at all.
Also budget for the cache's own cost. Every miss now pays an embedding call plus a vector search before it pays for the model. On low-volume or highly heterogeneous traffic that tax exceeds the savings. A useful adoption heuristic: unless you expect the cache to serve a clear majority of calls — around 60% is the commonly cited floor — the machinery rarely repays what it costs to build and operate, and you will buy more perceived speed for less operational surface by trimming the prompt or streaming the response.
A vector score alone must not authorize a hit. Attach structured metadata to each entry and require an exact match on every gate before the answer is served. Any gate that fails or is unknown forces a miss:
Encode these in the cache key or as filter predicates on the vector query, not as a post-hoc check that a future refactor can drop. The key design that holds up is: a partition per hard boundary (tenant, locale, product version), similarity search only within the partition, and metadata gates on the candidate before returning it. Never rely on the embedding to encode a tenant ID — it will not, and semantically identical questions from different tenants will collide by design.
Some responses should not enter a shared semantic cache under any threshold:
Caching promotes a throwaway exchange into stored data, and storage changes its compliance posture. PII screening and redaction therefore carry more weight on the write path into the cache than on the display path out of the model — apply them to the query text and the answer text alike, before either is committed, not only when something is rendered. Retention limits, deletion-request handling, and encryption-at-rest obligations now attach to your cache store. Coordinate the tenant-boundary side of this with multi-tenancy-patterns.
Treat cached answers as derived data with a traceable lineage. Store alongside each entry: the source document IDs and content hashes, the prompt/policy version, the model and embedding-model identifiers, the answer class, and the creation timestamp. Without provenance you cannot purge selectively and will be forced into a full flush every time a document changes.
Three separable invalidation strategies, all of which you will eventually need:
redis-caching-patterns already covers for conventional caches; the origin being protected here is an inference backend with a hard quota, so the consequence of getting it wrong is throttling rather than merely load.Ship a kill switch that disables semantic hits per class, per tenant, or globally without a deploy. When an incorrect answer is reported, the first action is to stop serving it; root cause comes second.
Prompt caching is inherently provider-side; your only decision is prompt layout and cache-breakpoint placement.
For the semantic layer, prefer a shared LLM gateway in the request path over per-service implementations. The hit rate compounds as more services route through one cache, thresholds and TTLs are tuned centrally, scope and opt-in/opt-out become per-route configuration rather than code, and savings are attributable back to the calling application. The cost is a new component in the hot path and a shared blast radius — which is precisely why the per-route opt-out and the kill switch above are load-bearing.
For the store itself, there is a ladder and the rungs compose rather than compete: process-local memory (development only — unshareable across processes and lost on restart), a local embedded database, then an external distributed store with vector search. Anything multi-process or multi-instance needs the external tier; see redis-caching-patterns for the operational mechanics.
Hit rate on its own will mislead you, because the cheapest way to raise it is to lower the threshold — which is also the cheapest way to start being wrong. Instrument:
Wire these through your existing LLM tracing so cache decisions appear on the same trace as the generation they replaced — see langfuse-llm-tracing. A cached response with no trace is an invisible answer.
Never enable semantic hits directly into production traffic. Run the cache in shadow: compute the lookup, record what it would have returned, call the model anyway, and compare. Score the shadow hits offline against the live answers, sample them for human review, and only then serve — one answer class at a time, starting with the most tolerant class, with the kill switch already wired.
The acceptance criterion is not a hit rate. It is that the cache saves money without users noticing it exists. If they can tell, the threshold is wrong.
A starting posture, to be argued with rather than adopted blindly:
| Workload | Prompt cache | Semantic cache |
|---|---|---|
| Repeated tool schemas and long system prompts | Yes, always | No |
| Public docs and FAQ Q&A | Yes | Yes — the best case for it |
| Long-document analysis, multi-step agent loops | Yes — the win multiplies per step | Only on stable sub-questions |
| Account-specific support | Yes | Cache the generic explanation only; fill live data at request time |
| Regulated or compliance answers | Yes | Only with a high-precision threshold, strict freshness, and audit |
| Coding agents | Yes | Rarely on the final answer; the context is too caller-specific |
| Incident and system status | Yes | No — truth changes faster than any TTL |
| Creative or personalised generation | Yes | No — sameness is the defect |
Two demand profiles worth noting because they are routinely underweighted. In agentic multi-step systems the same large context is re-processed at every step and agents rephrase the same sub-question across runs, so both layers pay off harder than the request count suggests. In on-prem or GPU-constrained deployments the cache is not shaving an API bill at all — it is stretching fixed inference capacity, which changes the business case entirely.
redis-caching-patterns. This layer only adds the LLM-specific semantics on top.redis-caching-patterns — the cache substrate; namespacing, TTL config, invalidation, stampede protection, evictionmulti-tenancy-patterns — tenant isolation and context propagation for the scope gateslangfuse-llm-tracing — recording cache decisions on the same trace as the generationperformance-optimization — latency budgets and where caching sits among other leversREADME.md (opens in a new tab)references/aie-054-prompt-caching-vs-semantic-caching-how-to-make-ai-agents-f.md (opens in a new tab)references/aie-055-the-cache-has-layers-prompt-caching-semantic-caching-and-w.md (opens in a new tab)references/aie-056-prompt-caching-cut-llm-costs-keep-quality.md (opens in a new tab)references/aie-057-semantic-caching-boost-llm-speed-and-reduce-costs.md (opens in a new tab)references/aie-058-optimize-llm-response-costs-and-latency-with-effective-cac.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub ajyadav013/claude-kit --plugin claude-kit127 skills in this plugin
/accessibility-reviewUI accessibility (WCAG) review — keyboard operability, focus, ARIA semantics, color contrast, touch targets. Returns prioritized fixes. Distinct from performance/visual review./alembic-migrationsAlembic migration setup and patterns for async SQLAlchemy — async engine + run_sync in env.py, autogenerate, RLS/multi-tenant migrations. Use for alembic init, writing migrations, or debugging migration errors./anthropic-vertex-integrationClaude on Vertex AI via the AnthropicVertex SDK — lazy ADC client init, env-based project/region resolution, async helpers, backoff retry. Use when calling Claude via GCP Vertex AI (not direct Anthropic API)./api-and-interface-designStable API and interface design patterns. Use when designing REST/GraphQL endpoints, module boundaries, type contracts between modules or frontend/backend, or changing public interfaces./api-integrationWire the app to a backend API — data fetching, caching, error handling, loading states. Use when connecting to an endpoint, adding a fetch layer, or fixing API error and loading behaviour. React-query detail lives in tanstack-react-query-patterns./api-pagination-filtering-sortingHTTP query parameter conventions for pagination, filtering, sorting, and search with standardized response metadata. Use when designing list endpoints or building repositories that turn query params into SQL.Other plugins' skills for the same job