# 在 Next.js 中管理 AI Token 成本与缓存策略

URL: https://byshahid.com/zh/engineering/llm-token-costs-redis-caching-nextjs/
Author: Muhammad Shahid, Senior AI Software Engineer & Full Stack Developer (https://byshahid.com/)
Published: 2026-11-12

**快速解答:** 要降低 Next.js 中的 LLM API 成本，先检查最便宜的选项：以模型、提示哈希和规范化问题为键的 Redis 精确缓存；然后是语义缓存，用经过测试的相似度阈值和针对 on/off 等词的防护，为换了说法的问题复用答案；再是每个用户的消费上限和一把锁，让相同问题只触发一次调用。为较长的系统提示开启服务商的提示缓存，并限制 max_tokens。在 1,000 个客服问题的模拟中，Claude Sonnet 5.5 的费用从 7.55 美元降到了 0.17 美元。

- **技术栈:** Next.js App Router 路由处理器、Redis 8、@anthropic-ai/sdk、transformers.js 向量
- **节省:** Claude Sonnet 5.5 上每 1,000 个模拟问题从 7.55 美元降到 0.17 美元；Haiku 5.5 从 0.377 美元降到 0.010 美元
- **阈值:** 相似度 0.80 加反义词防护：30 个改写问题中复用 11 个，0 个错误答案
- **发现的陷阱:** 使用 all-MiniLM-L6-v2 时，"Turn off 2FA" 与 "turn on 2FA" 的相似度为 0.90
- **测试:** 在 Docker 中的 Redis 8 上运行，使用真实的本地向量和脚本化的 Claude 客户端

大多数 AI 功能一遍又一遍地回答相同的问题，并为每个答案付费。本教程介绍如何**在 Next.js 中用 Redis 缓存 LLM 响应**来**降低 AI API 成本**：精确缓存、针对改写问题的语义缓存、服务商自带的提示缓存、每个用户的消费上限，以及一把锁，防止一波相同的问题变成一波相同的账单。所有代码都在 Docker 中的 Redis 8 上运行过，使用真实的本地向量和一个按真实 API 方式计费的脚本化 Claude 客户端。测试过程中发现了两个真实问题：一个在我的 Redis 解析代码里，另一个在语义缓存这个思路本身。下文都会说明。

## LLM 账单从哪里来？

每个请求都要为输入 token（系统提示、文档和问题）和输出 token（答案，以及可能的思考过程）付费。按单个 token 算，输出更贵：Claude Sonnet 5.5 上输出每百万 token 10 美元，输入为 2 美元。但在客服机器人或文档助手中，输入的总量通常更大，因为带有产品信息的长系统提示会随每个问题一起发送。所以有两个杠杆：少发请求，以及让每个请求中重复的部分更便宜。用 [LLM token 计数器](/zh/tools/llm-token-counter/)统计你的提示长度，再用 [AI API 成本计算器](/zh/tools/ai-api-cost-calculator/)估算价格。

## 降低账单的五种方法

| 方法 | 节省什么 | 风险 |
| --- | --- | --- |
| 精确响应缓存 | 重复问题的整次调用 | 提示变更后返回过时答案（解决：在键中加入版本） |
| 语义响应缓存 | 改写问题的整次调用 | 对相似但不同的问题给出错误答案（解决：阈值加防护） |
| 服务商提示缓存 | 重复提示前缀成本的约 90% 或更多 | 前缀哪怕差一个字节也会悄悄失效 |
| 消费上限和 max_tokens | 失控的用户和失控的长答案 | max_tokens 太低会截断答案 |
| 请求合并（锁） | 大量用户同时提问时的重复调用 | 第一次调用较慢时其他请求需要等待 |

## 设计

![一个问题的处理路径：Redis 精确缓存，然后是使用本地向量、Redis 8 KNN 搜索和反义词防护的语义缓存，然后是每个用户的每日消费上限，然后是 Redis 锁保证只有一个请求调用 Claude，最后是开启提示缓存、max_tokens 和低 effort 的 Claude 调用；完整答案以 24 小时的精确缓存 TTL 和 7 天的语义缓存 TTL 保存](https://byshahid.com/blog/img/engineering/llm-token-costs-redis-caching-nextjs/layers.svg)

*最便宜的检查先执行，大多数问题根本不会到达模型。*

顺序是关键。精确查找只需一次 Redis 往返。语义查找需要一次本地向量计算（笔记本 CPU 上约 2 毫秒）和一次向量搜索。只有两者都未命中时，请求才会检查预算、获取锁并调用模型，答案会保存给下一个提问的人。每个缓存键都包含模型和系统提示的哈希，所以改动其中任何一个都会开始新的缓存，而不会返回按旧指令写出的答案。

## 需要准备什么？

| 工具 | 使用版本 | 用途 |
| --- | --- | --- |
| Next.js | 15（App Router） | 路由处理器 |
| Redis | 8（Docker） | 精确缓存、向量搜索、锁、消费计数 |
| redis（npm） | 6.3 | 带 Query Engine 辅助方法的客户端（ft.create、ft.search） |
| @huggingface/transformers | 4 | 使用 all-MiniLM-L6-v2 的本地向量 |
| @anthropic-ai/sdk | 1.8 | 支持提示缓存的 Claude |
| zod | 4 | 请求校验 |

## 步骤 1：环境准备

```bash
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 内置 Redis Query Engine，所以标准镜像无需额外模块即可进行向量搜索。生产环境中，任何支持带向量字段的 `FT.SEARCH` 的 Redis 兼容服务都可以。

## 步骤 2：精确缓存、语义缓存和锁

```ts
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);
  }
}
```

**精确缓存**对模型、提示版本和规范化后的问题（小写、单个空格、去掉末尾标点）做哈希，所以 "How do I cancel my subscription?" 和 "  how do I cancel my subscription " 共用一条记录。它是最便宜的一层，在下面的模拟中也是节省最多的一层。

**语义缓存**把每个已回答的问题和它的向量存进 Redis 哈希，用 `KNN` 搜索最近的三个邻居，并通过 TAG 过滤限定为同一模型和同一提示版本。只有相似度高于阈值并通过 `conflicts`（下面会解释的反义词防护）的邻居才会被复用。

**锁**使用带 30 秒过期时间的 `SET NX`。新问题的第一个请求负责计算答案；其他请求在最多 10 秒内轮询精确缓存，而不是为同样的调用付费。测试中，同一时刻发送的 20 个相同问题只产生了一次模型调用。

`findSimilar` 的第一个版本直接发送原始 `FT.SEARCH`，并把回复当作传统的扁平数组解析。测试发现它从来找不到任何结果：redis 6 客户端默认使用 RESP3，搜索结果以 map 形式返回。现在使用的 `ft.search` 辅助方法无论哪种协议都返回 `{ total, documents }`。

## 多相似才算足够相似？

![按相似度阈值 0.70 到 0.95 分组的柱状图：从缓存回答的改写问题从 30 个中的 16 个降到 1 个；仅凭相似度的错误答案为 6、3、1、1、1、0；加上反义词防护后，0.70 时为 1，0.75 及以上为 0](https://byshahid.com/blog/img/engineering/llm-token-costs-redis-caching-nextjs/threshold.svg)

*在 10 个已缓存问题、它们的 30 个改写版本和 10 个答案不同的相似问题上测得。*

语义缓存听起来像白捡的钱，直到你测试它。使用小模型 all-MiniLM-L6-v2 时，"How do I turn off two-factor authentication?" 与已缓存的 "How do I turn on two-factor authentication?" 相似度达到 0.90，比大多数真正的改写还高。"How much storage does the Pro plan have?" 与免费版的问题相似度为 0.80。仅凭相似度，在 0.95 以下的每个阈值都会给出错误答案，而在 0.95 时 30 个改写问题中只复用了 1 个。

解决办法是**反义词防护**：一小组会翻转相似问题含义的词（on/off/enable/disable/reset、套餐名称、平台）。如果两个问题都使用了同一组中的词且词不同，就不复用缓存的答案。加上防护后，阈值在 0.75 及以上时没有错误答案。本文使用 0.80，在这组数据上复用了 30 个改写中的 11 个，且没有错误答案。四十个问题是很小的样本：请用真实流量建立自己的标注集，加入你自己产品中的相似问题，在开启语义缓存前先测量。更强的向量模型也会比这个小模型更好地区分问题。

## 步骤 3：本地向量

```ts
// 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;
}
```

在 Node.js 进程中运行向量模型，意味着语义查找没有 API 调用，也没有网络往返：测试中在笔记本 CPU 上每个问题约 1.9 毫秒。模型只下载一次（约 23 MB）并重复使用。由于路由处理器需要 Node.js API 和长期存在的模型，它运行在 Node.js 运行时，而不是 Edge 运行时。

## 步骤 4：提示缓存和模型调用

```ts
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;
    },
  );
}
```

未命中时，少数几行代码完成了大部分节省。系统提示上的 `cache_control` 开启了 Claude 的提示缓存：第一个请求以输入价格的 1.25 倍把提示写入缓存，之后在缓存五分钟有效期内（每次读取都会刷新）的请求只需支付其中一小部分（Sonnet 5.5 上缓存 token 每百万 0.10 美元，正常为 2 美元）。提示必须逐字节一致，所以里面不能有日期或用户名，而且必须超过模型的最小可缓存长度（当前模型为 512 token）：太短的提示会悄悄不被缓存。`max_tokens` 限制最贵的 token，`effort: "low"` 让简单客服回答的思考保持简短。被拒绝或被 `max_tokens` 截断的答案永远不会被缓存，这样坏答案不会被反复返回一整天。

消费上限根据 API 自身的 `usage` 字段统计每个用户每天的真实花费，并且只在两层缓存都未命中后才检查：即使用户已达上限，缓存答案仍然免费。对于涉及私人数据的问题，调用 `answer` 时传入 `semantic: false`，并把用户 ID 加入精确缓存键，这样一个用户的答案永远不会返回给另一个用户。

## 步骤 5：Next.js 路由处理器

```ts
// 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 });
  }
}
```

处理器在 `globalThis` 上为每个服务器进程保留一个 Redis 连接，所以开发时的热重载和生产中的重复调用都不会为每个请求新建连接。`dynamic = "force-dynamic"` 阻止 Next.js 缓存路由本身，`Cache-Control: private, no-store` 让答案不进入共享 HTTP 缓存。`X-Answer-Source` 响应头会逐个请求告诉你是哪一层给出的答案：记录下来就得到了命中率。若要把答案流式输出到页面，在流式传输时收集文本，流结束后再存入缓存；[React 中流式输出 LLM 响应的指南](/zh/engineering/react-streaming-llm-responses-sse/)介绍了流式部分。

## 测试

```ts
// 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
```

```ts
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");
```

```bash
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
```

输出：

```text
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
```

脚本化客户端按一个客服机器人的情况计费：3,000 token 的系统提示、25 token 的问题和 150 token 的答案，价格取自 `PRICES`。测试针对 Redis 8 和真实向量运行真正的 `answer` 函数，所以缓存键、向量搜索、防护、锁、消费上限以及"不缓存截断答案"的规则都得到了验证。

## 每一层能省多少？

![1,000 个客服问题在 Claude Sonnet 5.5 上的模拟成本柱状图：无缓存 7.55 美元，加提示缓存 1.86 美元，加 Redis 精确缓存 0.19 美元，加语义缓存 0.17 美元；Haiku 5.5 上同样步骤分别为 0.377、0.108、0.011 和 0.010 美元](https://byshahid.com/blog/img/engineering/llm-token-costs-redis-caching-nextjs/cost.svg)

*精确缓存完成了大部分工作，因为人们会重复提问；语义缓存在此基础上再省一点。*

模拟中，1,000 个请求有 70% 来自 40 种常见说法，30% 来自 60 个不太常见的问题，所以流量由 100 个不同的问题组成。仅提示缓存就让 Sonnet 账单降低了约 75%，因为 3,000 token 的提示是从缓存中读取的。随后精确缓存去掉了 1,000 次调用中的 900 次。语义缓存又去掉了 11 次，没有任何答案被不相关的问题借用。能省多少几乎完全取决于你的流量重复程度，所以在承诺具体数字之前，记录答案来源并测量真实命中率。

这个模拟的早期版本使用了只有数字不同的虚构一次性问题（"question 5 about folder sync"、"question 6..."）。语义缓存用同一个答案回答了其中 290 个。真实的长尾问题会更多样，但教训不变：只在数字、名称或 ID 上不同的问题，在向量模型看来几乎一样。

## 缓存失效：保持答案新鲜

- **在键中加入版本：**`PROMPT_VERSION` 是系统提示及其事实的哈希，修改它们会让所有旧答案立即无法访问，无需清空缓存。

- **使用 TTL：**这里精确答案为 24 小时，语义索引为 7 天。对价格或库存这类经常变化的信息要更短。

- **按事件删除：**产品信息变化时提升提示版本；与某个文档相关的内容，把文档版本加入键中。

- **模型升级分开处理：**模型名是每个键的一部分，所以从 Haiku 换到 Sonnet 时，永远不会返回另一个模型写的答案。

## 哪些内容绝不应该缓存

当问题涉及用户自己的数据（订单、发票、消息）时，不要在用户之间共享缓存答案；要么跳过语义缓存并把用户 ID 加入键中，要么干脆不缓存。不要缓存依赖时间、实时库存或价格的答案，除非 TTL 很短。不要缓存拒绝、错误或被截断的答案。也要小心缓存问题中的个人数据：缓存是用户输入内容的副本，所以给它设置 TTL，并纳入你的数据删除流程。

## 常见错误及修复方法

| 错误 | 后果 | 修复 |
| --- | --- | --- |
| 系统提示中有时间戳或用户名 | 提示缓存从不命中；精确缓存键从不重复 | 保持提示固定；把每次请求的数据放进消息 |
| 缓存键中没有模型或提示版本 | 提示修改后仍返回旧答案 | 把模型和提示哈希进键 |
| 凭感觉选择语义阈值 | 含义相反的问题得到同样的答案 | 在标注问题上测量；加入反义词防护 |
| 缓存截断或被拒绝的答案 | 坏答案被返回一整天 | 只缓存 stop_reason 为 "end_turn" 的答案 |
| 新问题没有加锁 | 流量高峰为同一个答案付费多次 | SET NX 锁；其他请求等待缓存答案 |
| 手动解析原始 FT.SEARCH 回复 | 在 RESP3 下结果悄悄丢失 | 使用客户端的 ft.search 辅助方法 |
| 个人问题使用共享缓存 | 一个用户看到另一个用户的答案 | 按用户区分键，私人数据不使用语义缓存 |

## 局限

这里的成本来自使用脚本化客户端的模拟，而不是真实账单：在你的流量下，真实的 token 数、命中率和提示缓存的行为都会不同，所以请用 `usage` 字段和答案来源头进行测量。阈值是在 40 个标注问题上选出的，足以说明风险，但不足以为你的产品确定数值。反义词防护只认识你提供给它的词。而且缓存帮不了所有问题都不同的产品，比如处理私有代码的编程助手；那种情况下，提示缓存和模型选择更重要。

## 在生产环境中测量

每个请求记录四个数字：答案来源（精确、语义或模型）、输入和输出 token、来自 `cache_read_input_tokens` 的缓存输入 token，以及成本。由此可以得到每一层的命中率、提示缓存命中率和每个已回答问题的成本。每周抽查一批语义命中，把出错的问题对加入标注集，并在合适时加入反义词组。关于同一接口的安全问题（限流和提示注入），请参阅 [AI API 安全指南](/zh/engineering/secure-llm-api-rate-limiting-prompt-injection/)；关于基于自有文档回答，请参阅 [Next.js 中的 RAG 流水线](/zh/engineering/nextjs-rag-pipeline-pgvector/)。

## 常见问题

### 如何在 Next.js 中缓存 LLM 响应？

在运行于 Node.js 运行时的路由处理器中，把模型、提示版本和规范化问题哈希成 Redis 键；如果已有存储的答案就直接返回，否则调用模型，并把完整答案带 TTL 存入缓存。

### 什么是语义缓存？

当新问题与已回答的问题意思相同时复用答案的缓存，通过向量搜索比较向量来查找，而不是精确匹配文本。

### 语义缓存应该用多高的相似度阈值？

用你自己的标注问题测量。本文测试中，0.80 加反义词防护复用了 30 个改写中的 11 个且没有错误答案；仅凭相似度时，0.95 以下都会出现错误答案。

### 语义缓存会给出错误答案吗？

会。测试中 "Turn off 2FA" 与 "turn on 2FA" 的相似度为 0.90。要为翻转含义的词加防护，并用相似但不同的问题测试。

### 提示缓存和响应缓存有什么区别？

提示缓存由模型服务商完成，让每次调用中重复的提示开头更便宜。响应缓存由你自己完成，在答案已知时完全跳过调用。

### Claude 的提示缓存能省多少？

写入缓存的价格是输入价格的 1.25 倍，读取只需其中一小部分；Claude Sonnet 5.5 上读取为每百万 token 0.10 美元，正常为 2 美元。模拟中它让账单降低了约 75%。

### 为什么我的提示缓存没有命中？

前缀必须逐字节一致，并且长于模型的最小长度（当前 Claude 模型为 512 token）。提示中的日期、用户名或工具顺序变化都会破坏缓存。

### 什么是缓存击穿，如何防止？

大量请求同时请求同一个未缓存的内容，每个请求都去做昂贵的工作。Redis SET NX 锁让一个请求调用模型，其他请求等待它缓存的答案。

### 应该缓存关于用户自己数据的答案吗？

不要放在共享缓存中。把用户 ID 加入键，并对这类问题关闭语义缓存，或者干脆不缓存。

### 提示修改后如何让缓存的 LLM 答案失效？

在每个缓存键中加入提示的哈希。提示变化后会产生新键，旧答案不会再被返回，TTL 会清理它们。

### 可以用 Redis 做向量搜索吗？

可以。Redis 8 内置 Query Engine，支持带 HNSW 索引的向量字段，并可通过 FT.SEARCH 进行 KNN 查询。

### 缓存能和流式响应一起使用吗？

可以。把答案流式发送给用户，边接收边收集文本，在流正常结束后存入缓存。

## 来源

- [Anthropic Docs: Prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching)
- [Anthropic Docs: Claude API pricing](https://platform.claude.com/docs/en/about-claude/pricing)
- [Redis Docs: Vector search](https://redis.io/docs/latest/develop/ai/search-and-query/vectors/)
- [Redis Docs: SET (NX, PX)](https://redis.io/docs/latest/commands/set/)
- [Redis Docs: Semantic caching for LLMs](https://redis.io/docs/latest/develop/ai/redisvl/user_guide/llmcache/)
- [node-redis client](https://github.com/redis/node-redis)
- [Hugging Face: Xenova/all-MiniLM-L6-v2](https://huggingface.co/Xenova/all-MiniLM-L6-v2)
- [Transformers.js documentation](https://huggingface.co/docs/transformers.js/index)
- [Next.js Docs: Route handlers](https://nextjs.org/docs/app/api-reference/file-conventions/route)
- [Next.js Docs: Route segment config](https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config)

查看相关服务: https://byshahid.com/zh/hire/ai-integration-engineer/
