Engineering notes
Managing AI Token Costs and Caching Strategies in Next.js
By Muhammad Shahid · · 31 min read
Quick answer
To reduce LLM API costs in Next.js, check the cheapest options first: an exact Redis cache keyed on the model, a hash of the prompt and the normalised question; then a semantic cache that reuses an answer to a reworded question, with a tested similarity threshold and a guard for words like on/off; then a per-user spend cap and a lock so identical questions trigger one call. Turn on the provider's prompt caching for the long system prompt and cap max_tokens. In a simulation of 1,000 support questions this cut the Claude Sonnet 5.5 bill from $7.55 to $0.17.
| Stack | Next.js App Router route handler, Redis 8, @anthropic-ai/sdk, transformers.js embeddings |
|---|---|
| Saving | $7.55 to $0.17 per 1,000 simulated questions on Claude Sonnet 5.5; $0.377 to $0.010 on Haiku 5.5 |
| Threshold | Similarity 0.80 plus a contrast-word guard: 11 of 30 rewordings reused, 0 wrong answers |
| Trap found | "Turn off 2FA" scored 0.90 against "turn on 2FA" with all-MiniLM-L6-v2 |
| Tested | Against Redis 8 in Docker with real local embeddings and a scripted Claude client |
Most AI features answer the same questions again and again, and pay for every answer. This tutorial shows how to cache LLM responses with Redis in Next.js to reduce AI API costs: an exact cache, a semantic cache for reworded questions, the provider's own prompt caching, a spend cap per user and a lock that stops a burst of identical questions from becoming a burst of identical bills. Everything was run against Redis 8 in Docker, with real local embeddings and a scripted Claude client that bills like the real API, and the test found two real problems along the way: one in my Redis parsing and one in the idea of semantic caching itself. Both are explained below.
Where does an LLM bill come from?
Every request pays for its input tokens (the system prompt, any documents and the question) and its output tokens (the answer, plus any thinking). Output is the expensive part per token: on Claude Sonnet 5.5 it is $10 per million tokens against $2 for input. But in a support bot or a docs assistant, the input is usually the bigger number in total, because a long system prompt with product facts is sent with every single question. So there are two levers: send fewer requests, and make each request's repeated part cheaper. Count your own prompt with the LLM token counter, and price it with the AI API cost calculator.
Five ways to cut the bill
| Technique | What it saves | Risk |
|---|---|---|
| Exact response cache | The whole call, for a repeated question | Stale answers if the prompt changes (fix: version the key) |
| Semantic response cache | The whole call, for a reworded question | Wrong answers to look-alike questions (fix: threshold plus guard) |
| Provider prompt caching | About 90% or more of the cost of the repeated prompt prefix | Silent misses if the prefix changes byte by byte |
| Spend caps and max_tokens | Runaway users and runaway answers | Answers cut short if max_tokens is too low |
| Request coalescing (lock) | Duplicate calls when many users ask at once | Waiting requests if the first call is slow |
The design
The order is the point. An exact lookup costs a Redis round trip. A semantic lookup costs one local embedding (about 2 ms on a laptop CPU) and a vector search. Only when both miss does the request touch the budget, take a lock and call the model, and the answer is stored for the next person. Every cache key includes the model and a hash of the system prompt, so a change to either starts a fresh cache instead of serving answers written under old instructions.
What do you need?
| Tool | Version used | Why |
|---|---|---|
| Next.js | 15 (App Router) | The route handler |
| Redis | 8 (Docker) | Exact cache, vector search, locks, spend counters |
| redis (npm) | 6.3 | Client with the Query Engine helpers (ft.create, ft.search) |
| @huggingface/transformers | 4 | Local embeddings with all-MiniLM-L6-v2 |
| @anthropic-ai/sdk | 1.8 | Claude with prompt caching |
| zod | 4 | Request validation |
Step 1: Set up
npm install @anthropic-ai/sdk redis @huggingface/transformers zod
docker run -d --name redis -p 6379:6379 redis:8 # Redis 8 includes the Query Engine (vector search)
echo "REDIS_URL=redis://localhost:6379" >> .env.local
echo "ANTHROPIC_API_KEY=sk-ant-..." >> .env.local
Redis 8 includes the Redis Query Engine, so vector search works in the standard image with no extra modules. Any Redis-compatible service that supports FT.SEARCH with vector fields will do in production.
Step 2: The exact cache, the semantic cache and the lock
import { createHash } from "node:crypto";
import { SCHEMA_FIELD_TYPE, SCHEMA_VECTOR_FIELD_ALGORITHM, type RedisClientType } from "redis";
// ---- 1. Exact cache: same model, same prompt version, same (normalised) question -> same answer
export function normalise(question: string) {
return question
.normalize("NFKC")
.toLowerCase()
.replace(/\s+/g, " ")
.replace(/[\s?!.。?!]+$/u, "")
.trim();
}
export function exactKey(model: string, promptVersion: string, question: string) {
const hash = createHash("sha256").update(JSON.stringify([model, promptVersion, normalise(question)])).digest("hex");
return "llm:exact:" + hash;
}
export interface CachedAnswer {
text: string;
model: string;
createdAt: string;
}
export async function getExact(redis: RedisClientType, key: string): Promise<CachedAnswer | null> {
const raw = await redis.get(key);
return raw ? (JSON.parse(raw) as CachedAnswer) : null;
}
export async function setExact(redis: RedisClientType, key: string, value: CachedAnswer, ttlSeconds: number) {
await redis.set(key, JSON.stringify(value), { EX: ttlSeconds });
}
// ---- 2. Semantic cache: a different wording of a question already answered
// Redis 8 includes the Query Engine, so vectors are stored in hashes and searched with FT.SEARCH KNN.
export const SEM_INDEX = "llm:sem:idx";
const SEM_PREFIX = "llm:sem:";
export async function ensureSemanticIndex(redis: RedisClientType, dims: number) {
try {
await redis.ft.create(
SEM_INDEX,
{
scope: { type: SCHEMA_FIELD_TYPE.TAG },
vec: {
type: SCHEMA_FIELD_TYPE.VECTOR,
ALGORITHM: SCHEMA_VECTOR_FIELD_ALGORITHM.HNSW,
TYPE: "FLOAT32",
DIM: dims,
DISTANCE_METRIC: "COSINE",
},
},
{ ON: "HASH", PREFIX: SEM_PREFIX },
);
} catch (err) {
if (!String(err).includes("Index already exists")) throw err;
}
}
const toBytes = (v: Float32Array) => Buffer.from(v.buffer, v.byteOffset, v.byteLength);
// Words that flip the meaning of an otherwise similar question ("turn ON 2FA" vs "turn OFF 2FA" scored 0.90).
// If both questions use a word from the same group and the words differ, the cached answer is not reused.
// Build these groups from your own product: plans, platforms, on/off actions.
const CONTRASTS: Map<string, string>[] = [
new Map([["on", "on"], ["enable", "on"], ["off", "off"], ["disable", "off"], ["reset", "reset"]]),
new Map([["free", "free"], ["plus", "plus"], ["pro", "pro"]]),
new Map([["windows", "windows"], ["mac", "mac"], ["macos", "mac"], ["macbook", "mac"], ["ios", "ios"], ["iphone", "ios"], ["android", "android"]]),
];
export function conflicts(a: string, b: string) {
const terms = (s: string, group: Map<string, string>) =>
[...new Set(normalise(s).split(/[^\p{L}\p{N}]+/u).flatMap((w) => (group.has(w) ? [group.get(w)!] : [])))].sort().join();
return CONTRASTS.some((group) => {
const ta = terms(a, group);
const tb = terms(b, group);
return ta !== "" && tb !== "" && ta !== tb;
});
}
// scope = model + prompt version: an answer is only reused under the same model and instructions
export async function findSimilar(redis: RedisClientType, scope: string, question: string, vec: Float32Array, minSimilarity: number) {
const { documents } = await redis.ft.search(
SEM_INDEX,
"(@scope:{" + scope.replace(/[^a-zA-Z0-9]/g, "\\$&") + "})=>[KNN 3 @vec $v AS dist]",
{ PARAMS: { v: toBytes(vec) }, SORTBY: "dist", RETURN: ["dist", "answer", "question"], DIALECT: 2 },
);
for (const doc of documents) {
const similarity = 1 - Number(doc.value.dist); // cosine distance -> similarity
if (similarity < minSimilarity) break; // sorted: the rest are further away
if (conflicts(question, String(doc.value.question))) continue;
return { answer: String(doc.value.answer), question: String(doc.value.question), similarity };
}
return null;
}
export async function storeSimilar(
redis: RedisClientType, scope: string, question: string, vec: Float32Array, answer: string, ttlSeconds: number,
) {
const key = SEM_PREFIX + createHash("sha256").update(scope + "|" + normalise(question)).digest("hex");
await redis.hSet(key, { scope, question, answer, vec: toBytes(vec) });
await redis.expire(key, ttlSeconds);
}
// ---- 3. Stampede protection: when 50 users ask the same new question at once, only one pays
export async function withLock<T>(
redis: RedisClientType, key: string, compute: () => Promise<T>, waitForOther: () => Promise<T | null>,
): Promise<T> {
const lockKey = key + ":lock";
const gotLock = await redis.set(lockKey, "1", { NX: true, PX: 30_000 });
if (!gotLock) {
for (let i = 0; i < 100; i++) {
await new Promise((r) => setTimeout(r, 100));
const done = await waitForOther();
if (done) return done;
}
// the other request took too long or failed: compute anyway
}
try {
return await compute();
} finally {
if (gotLock) await redis.del(lockKey);
}
}
The exact cache hashes the model, the prompt version and the normalised question (lower case, single spaces, no trailing punctuation), so "How do I cancel my subscription?" and " how do I cancel my subscription " share one entry. It is the cheapest layer and, in the simulation below, the one that saves the most.
The semantic cache stores each answered question with its embedding in a Redis hash and searches the three nearest neighbours with KNN, restricted to the same model and prompt version with a TAG filter. A neighbour is reused only if its similarity is above the threshold and it passes conflicts, the contrast-word guard explained next.
The lock uses SET NX with a 30-second expiry. The first request for a new question computes the answer; the others poll the exact cache for up to 10 seconds instead of paying for the same call. In the test, 20 identical questions sent at the same moment produced exactly one model call.
The first version of findSimilar sent a raw FT.SEARCH and parsed the reply as the classic flat array. The test caught that it never found anything: the redis 6 client speaks RESP3 by default and returns search results as a map. The ft.search helper used now returns { total, documents } whichever protocol is in use.
How similar is similar enough?
Semantic caching sounds like free money until you test it. With the small all-MiniLM-L6-v2 model, "How do I turn off two-factor authentication?" scored 0.90 against the cached "How do I turn on two-factor authentication?", higher than most genuine rewordings. "How much storage does the Pro plan have?" scored 0.80 against the free plan's question. Similarity alone served a wrong answer at every threshold below 0.95, and at 0.95 it reused just one rewording out of 30.
The fix is a contrast-word guard: small groups of words that flip the meaning of an otherwise similar question (on/off/enable/disable/reset, plan names, platforms). If both questions use a word from the same group and the words differ, the cached answer is not reused. With the guard, there were no wrong answers from a threshold of 0.75 upwards. This article uses 0.80, which reused 11 of 30 rewordings with no wrong answers on this set. Forty questions are a small sample: build your own labelled set from real traffic, include your own look-alike questions, and measure before you switch a semantic cache on. A stronger embedding model will also separate questions better than this small one.
Step 3: Local embeddings
// Local sentence embeddings with transformers.js: no API call, no per-request cost.
// all-MiniLM-L6-v2 gives 384-dimension vectors; the model (about 23 MB) downloads once and is cached.
import { pipeline, type FeatureExtractionPipeline } from "@huggingface/transformers";
export const EMBED_DIMS = 384;
let extractor: Promise<FeatureExtractionPipeline> | null = null;
export async function embed(text: string): Promise<Float32Array> {
extractor ??= pipeline("feature-extraction", "Xenova/all-MiniLM-L6-v2", { dtype: "fp32" });
const out = await (await extractor)(text, { pooling: "mean", normalize: true });
return out.data as Float32Array;
}
Running the embedding model inside the Node.js process means a semantic lookup costs no API call and no network round trip: about 1.9 ms per question on a laptop CPU in the test. The model downloads once (about 23 MB) and is reused. Because the route handler needs Node.js APIs and a long-lived model, it runs in the Node.js runtime, not the Edge runtime.
Step 4: Prompt caching and the model call
import { createHash } from "node:crypto";
import type Anthropic from "@anthropic-ai/sdk";
import type { RedisClientType } from "redis";
import { exactKey, findSimilar, getExact, setExact, storeSimilar, withLock } from "./cache";
// USD per million tokens (Claude pricing, November 2026). Cache writes cost 1.25x input, reads about 0.1x.
export const PRICES = {
"claude-haiku-5-5": { input: 0.1, output: 0.5, cacheWrite: 0.125, cacheRead: 0.01 },
"claude-sonnet-5-5": { input: 2, output: 10, cacheWrite: 2.5, cacheRead: 0.1 },
} as const;
export type Model = keyof typeof PRICES;
// The long, fixed part of every request: instructions plus product facts. Never put a date or user name here,
// or the provider's prompt cache misses on every request.
export const SYSTEM_PROMPT = [
"You are the support assistant for Acme Cloud Storage. Answer in at most 120 words.",
"Use only the product facts below. If they do not answer the question, say so and suggest contacting support.",
"PRODUCT FACTS:",
"- Plans: Free (5 GB), Plus (200 GB, $4/month), Pro (2 TB, $10/month). Annual billing saves 20%.",
"- Cancel any time in Settings > Billing; files stay readable for 30 days after cancelling.",
"- Password reset: Sign-in page > Forgot password. Links expire after 1 hour.",
"- Shared links can have a password and an expiry date (Plus and Pro).",
"- Deleted files stay in Trash for 30 days (Free) or 180 days (Plus, Pro).",
"- Two-factor authentication: Settings > Security, with an authenticator app or a passkey.",
"- Desktop apps for Windows and macOS; mobile apps for iOS and Android.",
].join("\n");
// Change this whenever the prompt or facts change: it is part of every cache key, so old answers stop matching.
export const PROMPT_VERSION = createHash("sha256").update(SYSTEM_PROMPT).digest("hex").slice(0, 12);
export const EXACT_TTL = 24 * 3600;
export const SEMANTIC_TTL = 7 * 24 * 3600;
export const MIN_SIMILARITY = 0.8; // chosen from labelled questions with the contrast-word guard on, see the test
export function costOf(model: Model, u: Anthropic.Usage) {
const p = PRICES[model];
return (
(u.input_tokens * p.input +
(u.cache_creation_input_tokens ?? 0) * p.cacheWrite +
(u.cache_read_input_tokens ?? 0) * p.cacheRead +
u.output_tokens * p.output) / 1_000_000
);
}
export interface Deps {
redis: RedisClientType;
claude: Anthropic;
embed: (text: string) => Promise<Float32Array>;
dailyBudgetUsd: number;
}
export type Source = "exact" | "semantic" | "model";
export async function answer(
deps: Deps, userId: string, question: string,
opts: { model?: Model; semantic?: boolean } = {}, // semantic: false for questions about private data
) {
const model = opts.model ?? "claude-haiku-5-5";
const useSemantic = opts.semantic ?? true;
const key = exactKey(model, PROMPT_VERSION, question);
const scope = model + "-" + PROMPT_VERSION;
// 1. Exact cache: free and instant
const exact = await getExact(deps.redis, key);
if (exact) return { text: exact.text, source: "exact" as Source, costUsd: 0 };
// 2. Semantic cache: one local embedding, no API call
const vec = useSemantic ? await deps.embed(question) : null;
const similar = vec ? await findSimilar(deps.redis, scope, question, vec, MIN_SIMILARITY) : null;
if (similar) {
await setExact(deps.redis, key, { text: similar.answer, model, createdAt: new Date().toISOString() }, EXACT_TTL);
return { text: similar.answer, source: "semantic" as Source, costUsd: 0 };
}
// 3. Spend cap per user per day, checked before paying for a call
const spendKey = "llm:spend:" + userId + ":" + new Date().toISOString().slice(0, 10);
const spent = Number((await deps.redis.get(spendKey)) ?? 0);
if (spent >= deps.dailyBudgetUsd) throw Object.assign(new Error("Daily AI budget used up"), { status: 429 });
// 4. Model call, once per new question even when many users ask it at the same moment
return withLock(
deps.redis,
key,
async () => {
const msg = await deps.claude.messages.create({
model,
max_tokens: 400, // caps the most expensive part of the bill: output tokens
output_config: { effort: "low" }, // short support answers do not need long thinking
system: [{ type: "text", text: SYSTEM_PROMPT, cache_control: { type: "ephemeral" } }],
messages: [{ role: "user", content: question }],
});
const text = msg.content.flatMap((b) => (b.type === "text" ? [b.text] : [])).join("");
const costUsd = costOf(model, msg.usage);
await deps.redis.incrByFloat(spendKey, costUsd);
await deps.redis.expire(spendKey, 2 * 24 * 3600);
// Only cache complete, normal answers: never a refusal or an answer cut off by max_tokens
if (msg.stop_reason === "end_turn" && text) {
await setExact(deps.redis, key, { text, model, createdAt: new Date().toISOString() }, EXACT_TTL);
if (vec) await storeSimilar(deps.redis, scope, question, vec, text, SEMANTIC_TTL);
}
return { text, source: "model" as Source, costUsd, usage: msg.usage };
},
async () => {
const done = await getExact(deps.redis, key);
return done ? { text: done.text, source: "exact" as Source, costUsd: 0 } : null;
},
);
}
A few lines do most of the saving on a miss. cache_control on the system prompt turns on Claude's prompt caching: the first request writes the prompt to the cache at 1.25 times the input price, and later requests within the cache's five-minute life, which each read refreshes, pay a fraction of it (on Sonnet 5.5, $0.10 per million cached tokens against $2). The prompt must be identical byte for byte, so it holds no dates or user names, and it must be longer than the model's minimum cacheable length (512 tokens on the current models): a short prompt silently does not cache. max_tokens caps the most expensive tokens, and effort: "low" keeps thinking short for simple support answers. Answers that were refused or cut off by max_tokens are never cached, so a bad answer is not served again for a day.
The spend cap counts real dollars per user per day from the API's own usage fields, and is checked only after both caches miss: cached answers stay free even for a user who has hit the cap. For questions about private data, call answer with semantic: false, and add the user ID to the exact key, so one user's answer is never served to another.
Step 5: The Next.js route handler
// app/api/ask/route.ts - Next.js App Router route handler
import Anthropic from "@anthropic-ai/sdk";
import { createClient, type RedisClientType } from "redis";
import { z } from "zod";
import { answer } from "@/lib/answer";
import { embed } from "@/lib/embed";
import { ensureSemanticIndex } from "@/lib/cache";
export const runtime = "nodejs"; // Redis TCP and local embeddings need Node.js, not the Edge runtime
export const dynamic = "force-dynamic"; // never let Next.js cache this route itself
// One Redis connection and one SDK client per server process, reused across requests
const g = globalThis as unknown as { redis?: Promise<RedisClientType> };
g.redis ??= (async () => {
const client = createClient({ url: process.env.REDIS_URL }) as RedisClientType;
await client.connect();
await ensureSemanticIndex(client, 384);
return client;
})();
const claude = new Anthropic();
const Body = z.object({ question: z.string().trim().min(3).max(1000) });
export async function POST(req: Request) {
const userId = req.headers.get("x-user-id"); // set by your auth middleware, never trusted from the browser
if (!userId) return Response.json({ error: "Sign in first" }, { status: 401 });
const parsed = Body.safeParse(await req.json().catch(() => null));
if (!parsed.success) return Response.json({ error: "Ask a question of 3 to 1000 characters" }, { status: 400 });
try {
const result = await answer({ redis: await g.redis!, claude, embed, dailyBudgetUsd: 0.5 }, userId, parsed.data.question);
return Response.json(
{ answer: result.text, source: result.source },
{ headers: { "Cache-Control": "private, no-store", "X-Answer-Source": result.source } },
);
} catch (err) {
const status = (err as { status?: number }).status === 429 ? 429 : 502;
return Response.json({ error: status === 429 ? "Daily AI budget used up" : "Try again in a moment" }, { status });
}
}
The handler keeps one Redis connection per server process on globalThis, so hot reloads in development and repeated invocations in production do not open a new connection per request. dynamic = "force-dynamic" stops Next.js from caching the route itself, and Cache-Control: private, no-store keeps answers out of shared HTTP caches. The X-Answer-Source header tells you, request by request, which layer answered: log it and you have your hit rate. To stream answers to the page, collect the text while streaming and store it when the stream finishes; the guide to streaming LLM responses in React shows the streaming part.
Testing it
// Labelled test questions: each intent has the first wording that reaches the cache, then three rewordings.
// "traps" look similar to a cached question but need a different answer.
export const intents: Record<string, string[]> = {
cancel: ["How do I cancel my subscription?", "how can i cancel my plan", "I want to stop my subscription, how?", "Cancel my Acme plan please"],
reset: ["How do I reset my password?", "forgot my password, what do I do", "Password reset steps?", "I can't remember my password"],
price: ["How much does the Pro plan cost?", "What is the price of Pro?", "Pro plan pricing", "how much is acme pro per month"],
trash: ["How long are deleted files kept?", "How long do files stay in the trash?", "Can I recover a file I deleted last week?", "trash retention period"],
share: ["Can I password-protect a shared link?", "How do I add a password to a share link?", "Is it possible to protect shared links with a password?", "share link password"],
twofa: ["How do I turn on two-factor authentication?", "Enable 2FA", "How can I set up two-step verification?", "Can I use a passkey to secure my account?"],
apps: ["Is there a desktop app for Mac?", "Do you have a macOS app?", "Can I install Acme on my MacBook?", "Mac desktop client"],
annual: ["Is there a discount for paying yearly?", "Do annual plans cost less?", "How much do I save with annual billing?", "yearly billing discount"],
free: ["How much storage does the free plan have?", "What is the free plan storage limit?", "How many GB do I get for free?", "free tier storage"],
after: ["What happens to my files after I cancel?", "Can I still access my files if I cancel?", "Do my files get deleted when I cancel?", "files after cancelling"],
};
export const traps: [string, string][] = [
["How do I cancel a shared link?", "cancel"],
["How do I reset my two-factor authentication?", "reset"],
["How much does the Plus plan cost?", "price"],
["How long do shared links stay valid?", "trash"],
["Can I password-protect a folder on my desktop?", "share"],
["How do I turn off two-factor authentication?", "twofa"],
["Is there a desktop app for Windows?", "apps"],
["Is there a discount for students?", "annual"],
["How much storage does the Pro plan have?", "free"],
["What happens to my files after I delete my account?", "after"],
];
// ...plus 60 less common, distinct questions (longTail) used in the cost simulation
import assert from "node:assert/strict";
import { createClient, type RedisClientType } from "redis";
import type Anthropic from "@anthropic-ai/sdk";
import { answer, costOf, MIN_SIMILARITY, PROMPT_VERSION, type Model } from "../lib/answer";
import { conflicts, ensureSemanticIndex, exactKey } from "../lib/cache";
import { embed, EMBED_DIMS } from "../lib/embed";
import { intents, longTail, traps } from "./questions";
const redis = createClient({ url: "redis://localhost:56380" }) as RedisClientType;
await redis.connect();
await redis.flushAll();
await ensureSemanticIndex(redis, EMBED_DIMS);
// A scripted Claude client that bills like the real API for a support bot with a 3,000-token system
// prompt: about 25 tokens per question and 150 per answer. The prompt cache is written on the first call
// and read on later calls (all of them start within its 5-minute life here).
const SYSTEM_TOKENS = 3000;
function fakeClaude(stop = "end_turn") {
let calls = 0;
let written = false;
const client = {
messages: {
create: async (p: { system: { cache_control?: unknown }[]; messages: { content: string }[] }) => {
calls++;
await new Promise((r) => setTimeout(r, 30));
const cached = Boolean(p.system[0]?.cache_control);
const usage = {
input_tokens: 25 + (cached ? 0 : SYSTEM_TOKENS),
cache_creation_input_tokens: cached && !written ? SYSTEM_TOKENS : 0,
cache_read_input_tokens: cached && written ? SYSTEM_TOKENS : 0,
output_tokens: 150,
};
if (cached) written = true;
return { stop_reason: stop, content: [{ type: "text", text: "Answer: " + p.messages[0].content }], usage };
},
},
};
return { client: client as unknown as Anthropic, calls: () => calls };
}
// ---- 1) Where should the similarity threshold be?
const firsts = Object.entries(intents).map(([intent, qs]) => ({ intent, q: qs[0] }));
const firstVecs = await Promise.all(firsts.map((f) => embed(f.q)));
const dot = (a: Float32Array, b: Float32Array) => a.reduce((s, x, i) => s + x * b[i], 0);
async function closest(q: string) {
const v = await embed(q);
let similarity = -1, intent = "";
firstVecs.forEach((b, i) => {
const s = dot(v, b);
if (s > similarity) { similarity = s; intent = firsts[i].intent; }
});
return { similarity, intent, guarded: conflicts(q, intents[intent][0]) };
}
const rewordings = [];
for (const [intent, qs] of Object.entries(intents)) for (const q of qs.slice(1)) rewordings.push({ want: intent, ...(await closest(q)) });
const trapResults = [];
for (const [q] of traps) trapResults.push(await closest(q));
console.log("threshold | similarity only: right of 30, wrong of 40 | with contrast-word guard: right, wrong");
for (const t of [0.7, 0.75, 0.8, 0.85, 0.9, 0.95]) {
const hit = (r: { similarity: number }) => r.similarity >= t;
const all = [...rewordings, ...trapResults.map((r) => ({ ...r, want: "" }))];
const right = rewordings.filter((r) => hit(r) && r.intent === r.want).length;
const wrong = all.filter((r) => hit(r) && r.intent !== r.want).length;
const gRight = rewordings.filter((r) => hit(r) && !r.guarded && r.intent === r.want).length;
const gWrong = all.filter((r) => hit(r) && !r.guarded && r.intent !== r.want).length;
console.log(" " + t.toFixed(2) + " | " + String(right).padStart(2) + " right, " + wrong + " wrong" + " | " + String(gRight).padStart(2) + " right, " + gWrong + " wrong");
}
// ---- 2) The cache layers, end to end against Redis 8
const fake = fakeClaude();
const deps = { redis, claude: fake.client, embed, dailyBudgetUsd: 100 };
const q0 = intents.cancel[0];
assert.equal((await answer(deps, "u1", q0)).source, "model");
assert.equal((await answer(deps, "u2", q0)).source, "exact");
assert.equal((await answer(deps, "u3", " HOW do I cancel my subscription ")).source, "exact"); // normalised
const reworded = rewordings.find((r) => r.want === "cancel" && r.similarity >= MIN_SIMILARITY);
if (reworded) assert.equal((await answer(deps, "u4", intents.cancel[rewordings.indexOf(reworded) + 1])).source, "semantic");
assert.equal((await answer(deps, "u5", traps[0][0])).source, "model"); // "cancel a shared link" is a different question
await answer(deps, "u6", intents.twofa[0]); // "turn on 2FA" is now cached
assert.equal((await answer(deps, "u7", "How do I turn off two-factor authentication?")).source, "model"); // 0.90 similar, opposite meaning
assert.notEqual(exactKey("claude-haiku-5-5", PROMPT_VERSION, q0), exactKey("claude-haiku-5-5", "new-prompt", q0));
console.log("layers: model, then exact, normalised exact" + (reworded ? ", semantic" : "") + "; a look-alike question still goes to the model; a new prompt version misses");
// Stampede: 20 users ask the same new question at the same moment
const before = fake.calls();
const burst = await Promise.all(Array.from({ length: 20 }, (_, i) => answer(deps, "s" + i, "Does Acme support WebDAV?")));
assert.equal(fake.calls() - before, 1);
console.log("stampede: 20 simultaneous identical questions -> " + (fake.calls() - before) + " model call, sources " + [...new Set(burst.map((b) => b.source))].join("/"));
// Truncated answers are never cached
const cut = fakeClaude("max_tokens");
const cutDeps = { ...deps, claude: cut.client };
await answer(cutDeps, "t1", "Explain every setting in detail");
await answer(cutDeps, "t1", "Explain every setting in detail");
assert.equal(cut.calls(), 2);
// Spend cap per user per day
const capped = { ...deps, claude: fakeClaude().client, dailyBudgetUsd: 0.0004 };
await answer(capped, "heavy", "First question about quotas?");
await assert.rejects(answer(capped, "heavy", "Can I change the email address on my account?"), /budget/); // cached answers stay free
console.log("safety: answers cut by max_tokens are not cached; the daily spend cap returns 429");
// ---- 3) What does each layer save? 1,000 requests: 70% from the 40 common wordings, 30% from 60 less common questions
let seed = 7;
const rand = () => ((seed = (seed * 48271) % 2147483647) / 2147483647);
const common = Object.values(intents).flat();
const traffic = Array.from({ length: 1000 }, (_, i) =>
rand() < 0.7 ? common[Math.floor(rand() * common.length)] : longTail[Math.floor(rand() * longTail.length)],
);
const intentOf = new Map<string, string>();
for (const [id, qs] of Object.entries(intents)) for (const q of qs) intentOf.set(q, id);
async function run(label: string, model: Model, mode: "none" | "prompt" | "exact" | "all") {
await redis.flushAll();
await ensureSemanticIndex(redis, EMBED_DIMS);
const f = fakeClaude();
let cost = 0;
let suspect = 0;
const answered = new Set<string>();
if (mode === "none" || mode === "prompt") {
for (const q of traffic) {
const msg = await (f.client.messages.create as unknown as (p: object) => Promise<{ usage: Anthropic.Usage }>)({
system: [mode === "prompt" ? { cache_control: { type: "ephemeral" } } : {}], messages: [{ content: q }],
});
cost += costOf(model, msg.usage);
}
} else {
const d = { redis, claude: f.client, embed, dailyBudgetUsd: 1000 };
for (const q of traffic) {
const r = await answer(d, "sim", q, { model, semantic: mode === "all" });
cost += r.costUsd;
// a long-tail question answered from the semantic cache borrowed another question's answer
if (r.source === "semantic" && !intentOf.has(q)) suspect++;
answered.add(q);
}
}
return { label, calls: f.calls(), cost, suspect };
}
for (const model of ["claude-haiku-5-5", "claude-sonnet-5-5"] as Model[]) {
const results = [
await run("no caching", model, "none"),
await run("+ prompt caching", model, "prompt"),
await run("+ exact cache", model, "exact"),
await run("+ semantic cache", model, "all"),
];
console.log(model + " per 1,000 requests: " + results.map((r) => r.label + " " + r.calls + " calls $" + r.cost.toFixed(3)).join(" | "));
console.log(" semantic answers given to a long-tail question (probably wrong): " + results[3].suspect);
}
// Embedding cost: local, but not free in time
const t0 = performance.now();
for (const q of common) await embed(q);
console.log("embedding: " + ((performance.now() - t0) / common.length).toFixed(1) + " ms per question on this laptop's CPU");
await redis.quit();
console.log("ALL CACHE TESTS PASS");
docker run -d --name cache-redis -p 56380:6379 redis:8
npx tsx test/cache.test.ts # no API key: the Claude client is scripted
Output:
threshold | similarity only: right of 30, wrong of 40 | with contrast-word guard: right, wrong
0.70 | 16 right, 6 wrong | 16 right, 1 wrong
0.75 | 14 right, 3 wrong | 14 right, 0 wrong
0.80 | 11 right, 1 wrong | 11 right, 0 wrong
0.85 | 8 right, 1 wrong | 8 right, 0 wrong
0.90 | 3 right, 1 wrong | 3 right, 0 wrong
0.95 | 1 right, 0 wrong | 1 right, 0 wrong
layers: model, then exact, normalised exact, semantic; a look-alike question still goes to the model; a new prompt version misses
stampede: 20 simultaneous identical questions -> 1 model call, sources model/exact
safety: answers cut by max_tokens are not cached; the daily spend cap returns 429
claude-haiku-5-5 per 1,000 requests: no caching 1000 calls $0.377 | + prompt caching 1000 calls $0.108 | + exact cache 100 calls $0.011 | + semantic cache 89 calls $0.010
semantic answers given to a long-tail question (probably wrong): 0
claude-sonnet-5-5 per 1,000 requests: no caching 1000 calls $7.550 | + prompt caching 1000 calls $1.857 | + exact cache 100 calls $0.192 | + semantic cache 89 calls $0.172
semantic answers given to a long-tail question (probably wrong): 0
embedding: 1.9 ms per question on this laptop's CPU
ALL CACHE TESTS PASS
The scripted client bills like a support bot with a 3,000-token system prompt, 25-token questions and 150-token answers, using the prices in PRICES. The test runs the real answer function against Redis 8 and real embeddings, so the cache keys, the vector search, the guard, the lock, the spend cap and the rule against caching truncated answers are all exercised.
What does each layer save?
In the simulation, 70% of 1,000 requests came from 40 common wordings and 30% from 60 less common questions, so 100 distinct questions made up the traffic. Prompt caching alone cut the Sonnet bill by about 75%, because the 3,000-token prompt was read from cache. The exact cache then removed 900 of the 1,000 calls. The semantic cache removed 11 more, with no answer borrowed by an unrelated question. How much you save depends almost entirely on how repetitive your traffic is, so log the answer source and measure your real hit rate before you promise a number.
An earlier version of this simulation used made-up one-off questions that differed only by a number ("question 5 about folder sync", "question 6..."). The semantic cache happily answered 290 of them with one answer. Real long-tail questions are more varied, but the lesson stands: questions that differ only in a number, a name or an ID look the same to an embedding model.
Cache invalidation: keeping answers fresh
- Version the key:
PROMPT_VERSIONis a hash of the system prompt and its facts, so editing them makes every old answer unreachable at once, with no cache flush. - Use TTLs: 24 hours for exact answers and 7 days for the semantic index here. Shorter for facts that change often, like prices or stock.
- Delete on events: when a product fact changes, bump the prompt version; for content tied to one document, include the document's version in the key.
- Keep model upgrades separate: the model name is part of every key, so moving from Haiku to Sonnet never serves an answer written by the other model.
What should never be cached
Do not share cached answers across users when the question involves their own data (orders, invoices, messages); either skip the semantic cache and add the user ID to the key, or do not cache at all. Do not cache answers that depend on the time, live stock or prices, unless the TTL is short. Do not cache refusals, errors or truncated answers. And be careful with personal data in cached questions: the cache is a copy of what users typed, so give it a TTL and include it in your data deletion process.
Common mistakes and how to fix them
| Mistake | What happens | Fix |
|---|---|---|
| A timestamp or user name in the system prompt | Prompt cache never hits; exact cache keys never repeat | Keep the prompt fixed; put per-request data in the message |
| Cache key without model or prompt version | Old answers served after a prompt change | Hash model and prompt into the key |
| Semantic threshold picked by feel | Opposite questions get the same answer | Measure on labelled questions; add a contrast-word guard |
| Caching truncated or refused answers | A bad answer is served all day | Cache only stop_reason "end_turn" |
| No lock on new questions | A traffic spike pays for the same answer many times | SET NX lock; others wait for the cached answer |
| Parsing raw FT.SEARCH replies by hand | Results silently missing under RESP3 | Use the client's ft.search helper |
| Shared cache for personal questions | One user sees another's answer | Per-user keys, no semantic cache for private data |
Limitations
The costs here come from a simulation with a scripted client, not a production bill: real token counts, real hit rates and the real behaviour of the prompt cache under your traffic will differ, so measure with the usage fields and the answer-source header. The threshold was chosen on 40 labelled questions, which is enough to show the risk but not to prove a value for your product. The contrast-word guard only knows the words you give it. And a cache cannot help a product whose questions are all different, such as a coding assistant working on private code; there, prompt caching and model choice matter more.
Measuring it in production
Log four numbers per request: the answer source (exact, semantic or model), input and output tokens, cached input tokens from cache_read_input_tokens, and the cost. From those you get the hit rate of each layer, the prompt cache hit rate and the cost per answered question. Review a sample of semantic hits every week and add any wrong pair to your labelled set and, where it fits, to the contrast-word groups. For the security side of the same endpoint, rate limits and prompt injection, see the guide to securing AI APIs; for answers grounded in your own documents, see the RAG pipeline in Next.js.
Frequently asked questions
How do I cache LLM responses in Next.js?
In a route handler on the Node.js runtime, hash the model, a version of the prompt and the normalised question into a Redis key, return the stored answer if it exists, and otherwise call the model and store the complete answer with a TTL.
What is a semantic cache?
A cache that reuses an answer when a new question means the same as one already answered, found by comparing embeddings with a vector search instead of matching the text exactly.
What similarity threshold should a semantic cache use?
Measure it on your own labelled questions. In this article's test, 0.80 with a contrast-word guard reused 11 of 30 rewordings with no wrong answers; similarity alone gave wrong answers below 0.95.
Can a semantic cache give wrong answers?
Yes. "Turn off 2FA" scored 0.90 against "turn on 2FA" in the test. Add a guard for words that flip meaning and test on look-alike questions.
What is the difference between prompt caching and response caching?
Prompt caching is done by the model provider and makes the repeated start of a prompt cheaper on every call. Response caching is done by you and skips the call entirely when the answer is already known.
How much does Claude prompt caching save?
Cache writes cost 1.25 times the input price and reads a small fraction of it; on Claude Sonnet 5.5 reads are $0.10 per million tokens against $2. In the simulation it cut the bill by about 75%.
Why is my prompt cache not hitting?
The prefix must be identical byte for byte and longer than the model's minimum (512 tokens on current Claude models). A date, a user name or a reordered tool list in the prompt breaks it.
What is a cache stampede and how do I prevent it?
Many requests for the same uncached item arriving at once, each doing the expensive work. A Redis SET NX lock lets one request call the model while the others wait for its cached answer.
Should I cache answers about a user's own data?
Not in a shared cache. Add the user ID to the key and turn off the semantic cache for those questions, or do not cache them.
How do I invalidate cached LLM answers when my prompt changes?
Put a hash of the prompt in every cache key. A changed prompt produces new keys, so old answers are never served, and TTLs clean them up.
Can I use Redis for vector search?
Yes. Redis 8 includes the Query Engine, which supports vector fields with HNSW indexes and KNN queries through FT.SEARCH.
Does caching work with streaming responses?
Yes. Stream the answer to the user, collect the text as it arrives, and store it in the cache once the stream ends normally.