大模型成本优化:基于 Redis 的可验证语义缓存架构
一句话结论 :缓存 LLM 结果的第一目标不是「多命中」,而是「不该命中时绝不命中」。语义相似不等于答案等价;没有错误率约束的缓存,是在用一次错误回答换几厘钱。
版本基线:Redis 8.x(内置 Query Engine;7.x 需 Redis Stack)/ redis-py 6.x / Python 3.12 / 一个可产生固定维度向量的嵌入服务。
前置阅读 :02 · 分层记忆
1. 先把「缓存」拆成四种,别混为一谈
| 层 | 命中依据 | 省什么 | 主要风险 |
|---|---|---|---|
| 精确结果缓存 | 规范化请求的哈希完全相等 | 一次完整 LLM 调用 | Key 设计漏字段导致串答案 |
| 语义结果缓存 | 查询向量相似度 ≥ 阈值 | 一次完整 LLM 调用 | 相似但不等价,错误复用 |
| 供应商 Prompt Cache | 相同前缀 token | 输入 token 费用/首 token 延迟 | 前缀不稳定导致不命中 |
| 检索结果缓存 | 查询 + 过滤条件 + 索引版本 | 向量/全文检索与重排 | 索引更新后读到旧结果 |
它们可以叠加,但不能互相替代:
- 供应商 Prompt Cache 仍然要调用模型,只是前缀更便宜;
- 语义缓存直接跳过模型,所以必须承担正确性责任;
- 检索缓存只省检索,不省生成。
本文重点讨论前两层,并在最后给出与 Prompt Cache 的组合方式。
#mermaid-svg-0nJli1FqmQdp7cls{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-0nJli1FqmQdp7cls .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-0nJli1FqmQdp7cls .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-0nJli1FqmQdp7cls .error-icon{fill:#552222;}#mermaid-svg-0nJli1FqmQdp7cls .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-0nJli1FqmQdp7cls .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-0nJli1FqmQdp7cls .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-0nJli1FqmQdp7cls .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-0nJli1FqmQdp7cls .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-0nJli1FqmQdp7cls .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-0nJli1FqmQdp7cls .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-0nJli1FqmQdp7cls .marker{fill:#333333;stroke:#333333;}#mermaid-svg-0nJli1FqmQdp7cls .marker.cross{stroke:#333333;}#mermaid-svg-0nJli1FqmQdp7cls svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-0nJli1FqmQdp7cls p{margin:0;}#mermaid-svg-0nJli1FqmQdp7cls .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-0nJli1FqmQdp7cls .cluster-label text{fill:#333;}#mermaid-svg-0nJli1FqmQdp7cls .cluster-label span{color:#333;}#mermaid-svg-0nJli1FqmQdp7cls .cluster-label span p{background-color:transparent;}#mermaid-svg-0nJli1FqmQdp7cls .label text,#mermaid-svg-0nJli1FqmQdp7cls span{fill:#333;color:#333;}#mermaid-svg-0nJli1FqmQdp7cls .node rect,#mermaid-svg-0nJli1FqmQdp7cls .node circle,#mermaid-svg-0nJli1FqmQdp7cls .node ellipse,#mermaid-svg-0nJli1FqmQdp7cls .node polygon,#mermaid-svg-0nJli1FqmQdp7cls .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-0nJli1FqmQdp7cls .rough-node .label text,#mermaid-svg-0nJli1FqmQdp7cls .node .label text,#mermaid-svg-0nJli1FqmQdp7cls .image-shape .label,#mermaid-svg-0nJli1FqmQdp7cls .icon-shape .label{text-anchor:middle;}#mermaid-svg-0nJli1FqmQdp7cls .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-0nJli1FqmQdp7cls .rough-node .label,#mermaid-svg-0nJli1FqmQdp7cls .node .label,#mermaid-svg-0nJli1FqmQdp7cls .image-shape .label,#mermaid-svg-0nJli1FqmQdp7cls .icon-shape .label{text-align:center;}#mermaid-svg-0nJli1FqmQdp7cls .node.clickable{cursor:pointer;}#mermaid-svg-0nJli1FqmQdp7cls .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-0nJli1FqmQdp7cls .arrowheadPath{fill:#333333;}#mermaid-svg-0nJli1FqmQdp7cls .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-0nJli1FqmQdp7cls .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-0nJli1FqmQdp7cls .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-0nJli1FqmQdp7cls .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-0nJli1FqmQdp7cls .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-0nJli1FqmQdp7cls .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-0nJli1FqmQdp7cls .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-0nJli1FqmQdp7cls .cluster text{fill:#333;}#mermaid-svg-0nJli1FqmQdp7cls .cluster span{color:#333;}#mermaid-svg-0nJli1FqmQdp7cls div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-0nJli1FqmQdp7cls .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-0nJli1FqmQdp7cls rect.text{fill:none;stroke-width:0;}#mermaid-svg-0nJli1FqmQdp7cls .icon-shape,#mermaid-svg-0nJli1FqmQdp7cls .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-0nJli1FqmQdp7cls .icon-shape p,#mermaid-svg-0nJli1FqmQdp7cls .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-0nJli1FqmQdp7cls .icon-shape rect,#mermaid-svg-0nJli1FqmQdp7cls .image-shape rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-0nJli1FqmQdp7cls .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-0nJli1FqmQdp7cls .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-0nJli1FqmQdp7cls :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 文档/知识更新
提升版本号
新命名空间
prompt/emb/retrieval version
失效事件 Stream
删除依赖缓存 Key
旧版本 TTL 自然过期
2. 什么内容「可以」缓存
在写任何代码之前,先给请求打标签。以下任一条件为真,就不应进入共享语义缓存:
| 条件 | 原因 | 替代方案 |
|---|---|---|
| 含用户隐私/权限相关上下文 | 跨用户复用会泄露数据 | 按用户隔离 + 短 TTL,或不缓存 |
| 有工具副作用(下单、退款、发邮件) | 重放缓存结果不等于重放副作用 | 只缓存「查询类」工具结果 |
temperature > 0 且答案需要多样性 |
缓存会抹掉采样差异 | 仅对确定性任务缓存 |
| 依赖实时数据(库存、价格、汇率) | 缓存即过期 | 短 TTL + 数据版本号 |
| 答案含具体实体/数字约束 | 相似问法可能指向不同实体 | 实体校验后再命中 |
| 多轮对话中的指代 | 「那它呢」离开上下文无意义 | 先用指代消解,再缓存消解后的意图 |
最安全的缓存对象是「FAQ / 知识型意图」:答案稳定、与用户无关、不触发副作用。把这类请求识别出来单独走语义缓存,比给所有请求加缓存更有效,也更安全。
3. 精确缓存:Key 设计决定正确性
3.1 不能只哈希用户 Query
同一个 Query,在不同模型、不同系统提示、不同工具集、不同检索上下文下,答案可能完全不同。Key 必须覆盖所有影响输出的输入:
python
import hashlib
import orjson
def exact_cache_key(
*,
tenant: str,
model: str,
prompt_version: str,
system_prompt: str,
messages: list[dict],
tools_schema: list[dict] | None,
retrieval_version: str | None,
user_scope: str,
temperature: float,
max_tokens: int,
) -> str:
payload = {
"tenant": tenant,
"model": model,
"prompt_version": prompt_version,
"system_prompt_sha": hashlib.sha256(system_prompt.encode()).hexdigest(),
"messages": messages,
"tools_sha": hashlib.sha256(
orjson.dumps(tools_schema or [], option=orjson.OPT_SORT_KEYS)
).hexdigest(),
"retrieval_version": retrieval_version,
"user_scope": user_scope,
"temperature": temperature,
"max_tokens": max_tokens,
}
canonical = orjson.dumps(payload, option=orjson.OPT_SORT_KEYS)
return "cache:exact:v3:" + hashlib.sha256(canonical).hexdigest()
几个容易漏的字段:
user_scope:用户/角色/权限范围。相同问题,不同权限的人不能共享答案;retrieval_version:RAG 索引版本。知识库更新后,旧答案必须失效;tools_sha:工具定义变化会改变模型行为;prompt_version:系统提示的显式版本,比哈希整个 prompt 更易运维。
不要做过度规范化:把大小写、标点、否定词都抹平,会把「可以退款吗」和「不可以退款吗」映射到同一个 Key。精确缓存只做无歧义的规范化(去首尾空白、统一换行),语义等价交给语义缓存并配合校验。
3.2 写入与读取
python
import asyncio
import time
import uuid
import orjson
import redis.asyncio as redis
_inflight: dict[str, asyncio.Task] = {}
async def cached_completion(
r: redis.Redis,
key: str,
compute,
ttl_seconds: int = 3600,
):
raw = await r.get(key)
if raw is not None:
try:
return orjson.loads(raw)
except orjson.JSONDecodeError:
# 旧 schema/损坏值:删除并当作 miss,不要让坏缓存永久生效
await r.delete(key)
task = _inflight.get(key)
if task is None:
async def _compute_and_store():
value = await compute()
# 只缓存正常完成的结果;异常/中断不写
await r.set(key, orjson.dumps(value), ex=ttl_seconds)
return value
task = asyncio.create_task(_compute_and_store())
_inflight[key] = task
task.add_done_callback(lambda _: _inflight.pop(key, None))
return await asyncio.shield(task)
这段代码解决的是进程内单飞(single-flight):同一 Key 的并发请求只触发一次计算。但它不解决多实例间的惊群:
- 10 个 Pod 同时 miss,仍会有 10 次 LLM 调用;
- 跨进程需要用 Redis 锁或「结果占位符 + 轮询/订阅」。
跨进程方案要谨慎:锁的持有者崩溃后,等待者不能永久阻塞。一个可接受的折中是「短锁 + 轮询缓存 + 超时后放行」:
python
async def cross_process_singleflight(r, key, compute, ttl, wait_ms=800):
lock_key = f"lock:{key}"
token = uuid.uuid4().hex
got = await r.set(lock_key, token, nx=True, px=5000)
if got:
try:
value = await compute()
await r.set(key, orjson.dumps(value), ex=ttl)
return value
finally:
# 只删自己的锁,避免误删他人续约后的锁
await r.eval(
"if redis.call('GET', KEYS[1]) == ARGV[1] then "
"return redis.call('DEL', KEYS[1]) else return 0 end",
1, lock_key, token,
)
deadline = time.monotonic() + wait_ms / 1000
while time.monotonic() < deadline:
raw = await r.get(key)
if raw is not None:
return orjson.loads(raw)
await asyncio.sleep(0.02)
# 等不到就自己算,避免缓存故障拖垮请求
return await compute()
这段锁不是「分布式正确性」的典范,只是降低惊群的工程手段 。真正的正确性仍由幂等计算和结果校验保证(第 5 篇会讲 Redlock 的争议)。Cluster 下
lock_key与key要用相同 hash tag 固定到同槽,否则脚本/事务的 Key 约束会把简单问题变复杂。
3.3 流式响应怎么缓存
不要缓存 token 流。缓存完整结果 + 元数据,命中时在应用层重放为 SSE/增量事件:
python
import time
CACHEABLE_FINISH_REASONS = {"stop", "end_turn"}
def now_ms() -> int:
return int(time.time() * 1000)
async def stream_and_cache(r, key, stream_fn, ttl=3600):
chunks: list[str] = []
async for event in stream_fn():
if event.type == "text_delta":
chunks.append(event.text)
yield event
elif event.type == "message_stop":
if event.finish_reason in CACHEABLE_FINISH_REASONS:
await r.set(key, orjson.dumps({
"text": "".join(chunks),
"finish_reason": event.finish_reason,
"cached_at": now_ms(),
}), ex=ttl)
yield event
被用户中断、超时、工具调用失败的流,不写缓存。半截答案比没有缓存更危险。
4. 语义缓存:相似度只是候选,不是结论
4.1 架构
#mermaid-svg-5cDYWNIK4lcRJC9e{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-5cDYWNIK4lcRJC9e .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-5cDYWNIK4lcRJC9e .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-5cDYWNIK4lcRJC9e .error-icon{fill:#552222;}#mermaid-svg-5cDYWNIK4lcRJC9e .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-5cDYWNIK4lcRJC9e .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-5cDYWNIK4lcRJC9e .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-5cDYWNIK4lcRJC9e .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-5cDYWNIK4lcRJC9e .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-5cDYWNIK4lcRJC9e .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-5cDYWNIK4lcRJC9e .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-5cDYWNIK4lcRJC9e .marker{fill:#333333;stroke:#333333;}#mermaid-svg-5cDYWNIK4lcRJC9e .marker.cross{stroke:#333333;}#mermaid-svg-5cDYWNIK4lcRJC9e svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-5cDYWNIK4lcRJC9e p{margin:0;}#mermaid-svg-5cDYWNIK4lcRJC9e .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-5cDYWNIK4lcRJC9e .cluster-label text{fill:#333;}#mermaid-svg-5cDYWNIK4lcRJC9e .cluster-label span{color:#333;}#mermaid-svg-5cDYWNIK4lcRJC9e .cluster-label span p{background-color:transparent;}#mermaid-svg-5cDYWNIK4lcRJC9e .label text,#mermaid-svg-5cDYWNIK4lcRJC9e span{fill:#333;color:#333;}#mermaid-svg-5cDYWNIK4lcRJC9e .node rect,#mermaid-svg-5cDYWNIK4lcRJC9e .node circle,#mermaid-svg-5cDYWNIK4lcRJC9e .node ellipse,#mermaid-svg-5cDYWNIK4lcRJC9e .node polygon,#mermaid-svg-5cDYWNIK4lcRJC9e .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-5cDYWNIK4lcRJC9e .rough-node .label text,#mermaid-svg-5cDYWNIK4lcRJC9e .node .label text,#mermaid-svg-5cDYWNIK4lcRJC9e .image-shape .label,#mermaid-svg-5cDYWNIK4lcRJC9e .icon-shape .label{text-anchor:middle;}#mermaid-svg-5cDYWNIK4lcRJC9e .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-5cDYWNIK4lcRJC9e .rough-node .label,#mermaid-svg-5cDYWNIK4lcRJC9e .node .label,#mermaid-svg-5cDYWNIK4lcRJC9e .image-shape .label,#mermaid-svg-5cDYWNIK4lcRJC9e .icon-shape .label{text-align:center;}#mermaid-svg-5cDYWNIK4lcRJC9e .node.clickable{cursor:pointer;}#mermaid-svg-5cDYWNIK4lcRJC9e .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-5cDYWNIK4lcRJC9e .arrowheadPath{fill:#333333;}#mermaid-svg-5cDYWNIK4lcRJC9e .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-5cDYWNIK4lcRJC9e .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-5cDYWNIK4lcRJC9e .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-5cDYWNIK4lcRJC9e .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-5cDYWNIK4lcRJC9e .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-5cDYWNIK4lcRJC9e .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-5cDYWNIK4lcRJC9e .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-5cDYWNIK4lcRJC9e .cluster text{fill:#333;}#mermaid-svg-5cDYWNIK4lcRJC9e .cluster span{color:#333;}#mermaid-svg-5cDYWNIK4lcRJC9e div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-5cDYWNIK4lcRJC9e .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-5cDYWNIK4lcRJC9e rect.text{fill:none;stroke-width:0;}#mermaid-svg-5cDYWNIK4lcRJC9e .icon-shape,#mermaid-svg-5cDYWNIK4lcRJC9e .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-5cDYWNIK4lcRJC9e .icon-shape p,#mermaid-svg-5cDYWNIK4lcRJC9e .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-5cDYWNIK4lcRJC9e .icon-shape rect,#mermaid-svg-5cDYWNIK4lcRJC9e .image-shape rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-5cDYWNIK4lcRJC9e .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-5cDYWNIK4lcRJC9e .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-5cDYWNIK4lcRJC9e :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 否
是
不通过
通过
用户 Query
规范化 + 租户/意图识别
Embedding
Redis KNN
租户/模型/版本过滤
相似度 ≥ 阈值?
调用 LLM
实体/约束校验
返回缓存答案
异步更新命中统计
写入缓存
向量 + 答案 + 元数据
关键点:KNN 返回的是候选,不是命中。 至少还要过三道闸:
- 元数据过滤:租户、模型、Prompt 版本、嵌入模型版本、有效期;
- 相似度阈值:按意图簇校准,不用全局常数;
- 语义校验:实体、数字、否定、时间约束是否一致;高风险场景再加一次小模型判定。
4.2 索引结构
text
FT.CREATE agent_cache ON HASH PREFIX 1 cache:sem:
SCHEMA
tenant TAG
intent TAG
model TAG
prompt_version TAG
emb_version TAG
expires_at NUMERIC
created_at NUMERIC
query_text TEXT
answer TEXT
vec VECTOR HNSW 6 TYPE FLOAT32 DIM 768 DISTANCE COSINE
TAG用于精确过滤,必须能区分租户与版本;NUMERIC的expires_at用于查询时排除过期条目;TEXT的query_text便于调试与人工审核;- 向量字段不返回给客户端,减少带宽;
- 不要把
hit_count放进被索引的 Hash:RediSearch 在文档字段变化时可能触发重新索引,高频计数会造成写放大。计数放独立 String 或应用侧聚合。
向量维度必须与嵌入模型一致。换模型时新建索引 或写入新的
emb_version并过滤,绝不允许不同维度的向量混在同一字段。
4.3 写入与查询
python
import hashlib
import struct
import time
import redis.asyncio as redis
INDEX = "agent_cache"
def now_ms() -> int:
return int(time.time() * 1000)
def to_f32(vec: list[float]) -> bytes:
return struct.pack(f"<{len(vec)}f", *vec)
def esc_tag(value: str) -> str:
# TAG 查询中的特殊字符需要转义;生产上建议租户 ID 只用 [a-zA-Z0-9_-]
special = r',.<>{}[]"\'`:;!@#$%^&*()-+=~|\\/'
out = []
for ch in value:
if ch in special:
out.append("\\")
out.append(ch)
return "".join(out)
async def cache_put(
r: redis.Redis,
*,
tenant: str,
intent: str,
model: str,
prompt_version: str,
emb_version: str,
query: str,
answer: str,
vec: list[float],
ttl_seconds: int,
) -> str:
digest = hashlib.sha256(
f"{query}\x00{model}\x00{prompt_version}".encode()
).hexdigest()[:32]
key = f"cache:sem:{tenant}:{digest}"
now = now_ms()
await r.hset(key, mapping={
"tenant": tenant,
"intent": intent,
"model": model,
"prompt_version": prompt_version,
"emb_version": emb_version,
"query_text": query,
"answer": answer,
"created_at": now,
"expires_at": now + ttl_seconds * 1000,
"vec": to_f32(vec),
})
await r.expire(key, ttl_seconds + 300)
return key
async def cache_lookup(
r: redis.Redis,
*,
tenant: str,
model: str,
prompt_version: str,
emb_version: str,
vec: list[float],
k: int = 5,
) -> list[dict]:
now = now_ms()
q = (
f"(@tenant:{{{esc_tag(tenant)}}} "
f"@model:{{{esc_tag(model)}}} "
f"@prompt_version:{{{esc_tag(prompt_version)}}} "
f"@emb_version:{{{esc_tag(emb_version)}}} "
f"@expires_at:[{now} +inf])"
f"=>[KNN {k} @vec $v AS dist]"
)
raw = await r.execute_command(
"FT.SEARCH", INDEX, q,
"PARAMS", 2, "v", to_f32(vec),
"SORTBY", "dist",
"RETURN", 4, "answer", "query_text", "dist", "expires_at",
"LIMIT", 0, k,
"DIALECT", 2,
)
return _parse_search(raw)
def _parse_search(raw) -> list[dict]:
# FT.SEARCH 返回: [total, key1, [field, value, ...], key2, ...]
out = []
for i in range(1, len(raw), 2):
fields = raw[i + 1]
row = {}
for j in range(0, len(fields), 2):
k = fields[j].decode() if isinstance(fields[j], bytes) else fields[j]
v = fields[j + 1]
row[k] = v.decode() if isinstance(v, bytes) else v
out.append(row)
return out
注意 DISTANCE COSINE 的返回值 :Redis Query Engine 返回的是余弦距离 1 - cosine_similarity。相似度要换算:
python
similarity = 1.0 - float(row["dist"])
如果直接拿 dist 和 0.93 比较,会把「距离越小越相似」误判成反方向。
4.4 阈值怎么定:用代价函数,不用拍脑袋
设:
c_llm:一次未命中调用的成本(钱 + 延迟折算);c_fp:一次错误命中的成本(错误答案、客诉、人工纠正);p_fp:候选被误判为等价的比例;p_hit:真正等价的比例。
一次候选命中的期望收益:
text
E = p_hit × c_llm − p_fp × c_fp
要 E > 0,需要:
text
p_fp / p_hit < c_llm / c_fp
算例(假设,不是实测):
c_llm |
c_fp |
允许的误判/正确比 | 含义 |
|---|---|---|---|
| 0.01 美元 | 0.05 美元 | < 20% | 低风险 FAQ,可放宽 |
| 0.01 美元 | 0.50 美元 | < 2% | 一般客服,需谨慎 |
| 0.01 美元 | 5.00 美元 | < 0.2% | 医疗/金融/法律,几乎不能错 |
这解释了为什么「相似度 0.85 就命中」在低风险场景可行,在高风险场景是灾难。阈值必须按业务代价校准,并按意图簇分别设定。
校准方法:
- 采样真实 Query,人工或强模型标注「是否可复用同一答案」;
- 对每对 Query 计算相似度,扫描阈值,得到 precision/recall 曲线;
- 在满足「误判率上限」的阈值中,选召回最高者;
- 上线后持续抽样复核,模型/数据漂移时重新校准。
python
def choose_threshold(pairs, max_fp_rate=0.002):
"""pairs: [(similarity, is_equivalent), ...]"""
best = None
for t in [i / 100 for i in range(70, 100)]:
tp = sum(1 for s, eq in pairs if s >= t and eq)
fp = sum(1 for s, eq in pairs if s >= t and not eq)
fn = sum(1 for s, eq in pairs if s < t and eq)
precision = tp / (tp + fp) if tp + fp else 1.0
recall = tp / (tp + fn) if tp + fn else 0.0
fp_rate = fp / (tp + fp) if tp + fp else 0.0
if fp_rate <= max_fp_rate and (best is None or recall > best[1]):
best = (t, recall, precision, fp_rate)
return best
4.5 语义校验:便宜但有效的闸门
相似度通过后,再做一次结构化比对:
python
import re
ENTITY_RE = re.compile(r"\b[A-Z]{2,}-\d+\b|\b\d{4}-\d{2}-\d{2}\b|\b\d+(?:\.\d+)?\b")
def constraints_compatible(q1: str, q2: str) -> bool:
# 实体、日期、数字、否定词必须一致
if set(ENTITY_RE.findall(q1)) != set(ENTITY_RE.findall(q2)):
return False
negations = ("不", "没有", "无法", "不能", "not ", "no ", "never ")
n1 = any(w in q1.lower() for w in negations)
n2 = any(w in q2.lower() for w in negations)
return n1 == n2
这不能覆盖所有语义,但能拦住最常见的「实体不同」「否定相反」。高风险场景再加一道小模型判定:
text
判断:问题 B 是否可以用问题 A 的答案回答?只输出 yes/no。
A: {cached_query}
B: {new_query}
约束:如果 B 指定了不同实体、时间、数量、权限范围,必须回答 no。
判定成本通常是一次短输出调用,远低于完整生成;但它也增加了延迟。只对「高风险意图 + 相似度处于灰区」的候选调用判定,不要每次都调。
4.6 租户隔离必须在过滤条件里,不能在结果后
错误做法:先 KNN 取 Top 10,再在应用层过滤掉其他租户。问题是:
- Top 10 可能全部来自其他租户,导致可用候选为 0,命中率骤降;
- 更糟的是,如果过滤逻辑有 bug,会直接把 A 租户的答案返回给 B 租户。
正确做法:把租户、模型版本、Prompt 版本、嵌入版本作为 TAG 过滤条件放进 KNN 查询本身(如 4.3 所示)。这样 ANN 只在合法子集里搜索,既正确又避免无效候选。
4.7 过期与向量索引卫生
Redis 的 Key TTL 会删除 Hash,但不要假设向量索引一定同步清理干净。生产上做三层防护:
- 查询里带
@expires_at:[now +inf]; - 后台 GC:定期
FT.SEARCH找expires_at < now的文档并DEL; - 监控
FT.INFO的文档数与实际 Key 数的偏差。
python
async def gc_expired(r, batch=500):
now = now_ms()
q = f"@expires_at:[-inf {now}]"
while True:
raw = await r.execute_command(
"FT.SEARCH", INDEX, q,
"NOCONTENT", "LIMIT", 0, batch, "DIALECT", 2,
)
keys = raw[1::2]
if not keys:
break
await r.unlink(*keys)
UNLINK 把内存释放放到后台线程,避免大 Key 删除阻塞主线程。
4.8 负缓存与拒答:把「没有答案」也缓存好
不是所有 miss 都该回源。对「确定不存在」「无权访问」「超出知识库范围」的查询,短 TTL 负缓存能挡住重复流量:
text
值: {"kind":"negative","reason":"not_found|forbidden|out_of_scope"}
TTL: 30--300 秒(远短于正常答案)
注意:
- 不要缓存临时错误(超时、限流、5xx),否则会把故障放大;
forbidden负缓存可能随权限变更失效,必须带权限版本/TTL;- 负缓存同样要做租户隔离,不能把 A 的「无权」复用到 B;
- 命中负缓存时返回明确的拒答/引导,而不是空字符串。
4.9 缓存与 RAG 的边界:别把两层结果混在一起
- 检索缓存缓存的是「query → 文档 ID/片段」,Key 必须包含索引版本、过滤条件、租户/ACL;
- 答案缓存缓存的是「query → 最终答案」,Key 必须包含 Prompt 版本、模型、工具、权限范围;
- 两层可以同时存在,但失效原因不同:索引更新应失效检索缓存,Prompt/模型更新应失效答案缓存;
- 不要把 RAG 片段直接当作答案缓存的 Key;片段顺序、截断、重排变化都会改变最终答案;
- 如果答案缓存命中了,是否还要跑检索?通常不需要,但审计/引用展示可能需要保留检索快照。
最小原则:每一层缓存只对其输入负责,不假设上游不变。
5. 布隆过滤器:用对地方才叫优化
5.1 它能做什么,不能做什么
布隆过滤器只有两种回答:
- 一定不存在(可靠);
- 可能存在(有假阳性)。
它不能删除元素 (标准布隆),不能枚举 ,不能告诉你元素的值。
因此,规划里「用布隆过滤器防缓存穿透」需要精确化:
- 如果布隆存的是「缓存中已有的 Query」,那么未命中缓存的新 Query 会被判为不存在,这恰好会拦住所有本来应该调用 LLM 的新请求------方向反了。
- 正确的用法是:对「合法 Key 的全集」建布隆 。例如合法商品 ID、合法用户 ID、已发布的文档 ID。请求进来先用
BF.EXISTS判断 ID 是否合法;不存在则直接拒绝,避免查缓存、查库、调模型。 - 对于「查了确实不存在」的 Query,用短 TTL 负缓存(值为特殊标记),而不是布隆。
5.2 参数与内存
text
BF.RESERVE valid:product 0.001 1000000
BF.ADD valid:product P123
BF.EXISTS valid:product P999 # 0 = 一定不存在;1 = 可能存在
BF.INFO valid:product
- 误差率
p越小、容量n越大,内存越多; - 近似内存:
m ≈ -n ln(p) / (ln 2)^2位,即1.44 × n × log2(1/p)位; - 100 万条、
p=0.001约 1.8 MB; BF.RESERVE默认EXPANSION 2:满容量后自动扩容,不需要手工重建;扩容后误判率会随子过滤器数量和填充度变化,需重新评估。若希望超容量直接报错,显式使用NONSCALING;- 数据删除后无法从布隆中移除,只能重建。对频繁增删的集合,用 Cuckoo Filter(
CF.ADD/CF.DEL)或直接查源数据;CF.*不是 Counting Bloom,二者不可混称。
python
async def ensure_bloom(r, key: str, error_rate=0.001, capacity=1_000_000):
try:
await r.execute_command("BF.RESERVE", key, error_rate, capacity)
except redis.ResponseError as exc:
if "exists" not in str(exc).lower():
raise
5.3 放在请求链路的哪里
text
请求 → 参数校验 → 布隆合法性预判 → 精确缓存 → 语义缓存 → RAG → LLM
布隆只应拦截「 ID 类资源不存在」这种确定性无效请求,不应拦截「新问题」。它的收益是保护后端不被打量,不是提高缓存命中率。
6. HyperLogLog:用 12 KB 估算覆盖度
语义缓存的命中率分母经常算错。你需要知道「有多少个不同的意图」,而不是「有多少次请求」。
text
每独立意图请求数 = 总请求 / PFCOUNT(intents)
缓存覆盖率 = 已缓存意图数 / PFCOUNT(intents)
python
async def record_intent(r, day: str, intent: str) -> None:
await r.pfadd(f"hll:intent:{day}", intent)
async def intent_cardinality(r, days: list[str]) -> int:
keys = [f"hll:intent:{d}" for d in days]
await r.pfmerge("hll:intent:tmp", *keys)
try:
return await r.pfcount("hll:intent:tmp")
finally:
await r.delete("hll:intent:tmp")
边界:
- 标准误差约 0.81%(16384 寄存器),不是精确计数;
- 不能判断某个元素是否存在;
- 稀疏编码省内存,稠密编码约 12 KB/Key;
- 适合日/周/月去重规模、意图覆盖度、独立用户数;不适合计费、配额、审计。
7. 热度管理与失效传播
7.1 ZSet 管的是「业务热度」,不是 LRU
Redis 自身的 allkeys-lfu 已经能做访问频率淘汰。ZSet 的价值在于业务级热度:
- Top N 缓存预热;
- 高价值答案延长 TTL;
- 低命中条目主动清理;
- 按租户/意图观察长尾分布。
python
import random
from datetime import date
def today() -> str:
return date.today().isoformat()
async def mark_hit(r, tenant: str, cache_key: str) -> None:
# 采样 1/10,降低写放大
if random.random() < 0.1:
zkey = f"hot:{tenant}:{today()}"
await r.zincrby(zkey, 1, cache_key)
await r.expire(zkey, 3 * 86400)
不要每次命中都 ZINCRBY:语义缓存本身是为了省成本,结果每命中一次写一次 ZSet,热 Key 会把省下的钱花在 Redis 上。采样 + 批量聚合更合理。
7.2 失效:TTL 是兜底,不是机制
三种失效手段按可靠性排序:
- 版本化命名空间 :
prompt_version、emb_version、retrieval_version进 Key/过滤条件;升级即天然隔离旧数据; - 依赖失效:文档更新时,删除与该文档相关的缓存条目;
- TTL:兜底,防止遗忘。
依赖失效的实现:
text
SADD dep:doc:{doc_id} cache_key1 cache_key2 ...
# 文档更新事件到达后
SMEMBERS dep:doc:{doc_id}
DEL cache_key1 cache_key2 ...
DEL dep:doc:{doc_id}
在 Cluster 下,dep 与缓存 Key 可能不同槽。两种处理:
- 用 hash tag 按租户聚槽,接受同租户共槽;
- 或者通过 Stream 异步失效,接受短暂不一致(配合短 TTL)。
依赖集合可能很大:不要 SMEMBERS 全量拉取再大 DEL ,用 SSCAN 分批 + UNLINK,并让失效任务可重试、可对账。
7.3 缓存雪崩与提前刷新
大量条目同时过期会引发 LLM 调用尖峰。两个手段:
- TTL 抖动 :
ttl = base + random(0, 0.1*base); - 概率提前刷新(XFetch):在过期前按概率主动刷新,把尖峰摊平。
python
import math, random, time
def should_refresh(expires_at: float, recompute_seconds: float, beta=1.0) -> bool:
# XFetch: 越接近过期,越可能提前刷新
now = time.time()
u = max(random.random(), 1e-12) # random() 可能返回 0,math.log(0) 会抛异常
return now - recompute_seconds * beta * math.log(u) >= expires_at
recompute_seconds 用观测到的 P95 生成耗时。beta 越大,越早刷新。这套策略适合可接受短暂旧值的 FAQ 缓存,不适合强一致数据。
7.4 冷启动与预热
缓存刚上线/刚扩容时命中率接近 0,容易误判「缓存没用」。预热策略:
- 从历史日志提取 Top 意图/高频 Query,离线生成答案并写入;
- 预热也要走阈值/校验,不能把离线错误答案批量灌入;
- 按租户/语言分批预热,避免一次性打满内存;
- 记录预热批次的
prompt_version/emb_version,版本升级后重新预热; - 预热是优化,不是正确性依赖;冷启动期间仍要能正常回源。
8. 成本与容量:把收益算清楚
8.1 收益公式
text
月节省 = N × (h_exact × c_llm + h_sem × (c_llm − c_embed) − h_sem × p_fp × c_fp) − c_redis
N:月请求;h_exact、h_sem:两层命中率(分母是全部请求);c_embed:查询嵌入成本(语义缓存每次都要算);p_fp:错误命中率;c_fp:错误成本;c_redis:内存 + 运维。
语义缓存的净收益对 p_fp × c_fp 极其敏感。 在高风险场景,先把 p_fp 压到 0.1% 以下,再谈命中率。
「成本降 70%」不是架构属性,而是特定假设下的结果:只有命中率接近 70%、嵌入与存储成本可忽略、错误命中成本足够低时,才可能成立。把这张公式带到自己的流量结构里算,不要引用别人的口号。
8.2 容量
text
向量内存 ≈ 条目数 × (维度 × 4 B + HNSW 图开销)
答案内存 ≈ 条目数 × 平均答案字节 × (1 + 碎片)
算例(假设):
- 50 万条缓存,768 维 float32:向量原始 1.5 GB,HNSW 图结构通常再增加显著比例,按 1.5--2 倍总向量内存估;
- 答案平均 1 KB:500 MB;
- 元数据/索引:数百 MB。
语义缓存不是「几乎不占内存」的优化。 它是用内存换 LLM 调用,必须把内存成本算进 TCO。
延迟与 QPS 也要单独算:
text
语义查找 QPS ≈ 总请求 QPS × 进入语义层的比例
命中延迟 ≈ 查询嵌入 + KNN + 校验(灰区才调用判定模型)
Redis QPS ≈ 语义查找 QPS × (KNN 1 次 + 命中后计数/取答案)
查询嵌入往往是延迟大头(远程 API 20--200 ms),Redis KNN 只是其中几毫秒。不要为了省一次 KNN 把缓存层做得更复杂;先优化嵌入服务与阈值,减少无效候选。
9. 失效模式清单
| 症状 | 根因 | 修复 |
|---|---|---|
| A 租户看到 B 租户答案 | 租户过滤在 KNN 之后 | 过滤条件进查询;租户进 Key |
| 换了模型仍命中旧答案 | Key 未包含模型/Prompt 版本 | 版本字段进 Key 与 TAG |
| 相似问法答错实体 | 只用向量相似度 | 实体/数字/否定校验 + 灰区判定 |
| 缓存永不失效 | TTL 过长 + 无依赖失效 | 版本化 + 事件失效 + 抖动 TTL |
| 命中率虚高 | 分母只算「已缓存请求」 | 分母用全部请求 + HLL 独立意图数 |
| 写入放大拖慢 Redis | 高频 HSET 被索引文档 / ZINCRBY |
计数外置、采样聚合 |
| 过期条目仍被召回 | 索引未同步清理 | expires_at 过滤 + GC |
| 换嵌入模型后检索崩 | 维度/语义空间不一致 | 新索引/新版本 TAG,禁止混写 |
| 流式响应缓存了半截 | 中断/超时也写入 | 只缓存正常结束的完整结果 |
| 布隆拦住了新问题 | 用缓存内容建布隆 | 布隆只用于合法 ID 全集 |
10. 生产检查清单
- 明确哪些请求允许进入共享缓存(无隐私、无副作用、低实时性);
- 精确缓存 Key 覆盖模型、Prompt、工具、检索版本、权限范围;
- 语义缓存带租户/版本 TAG 过滤,且过滤在 ANN 查询内;
- 阈值按业务代价校准,记录误判率而非只记录命中率;
- 命中前做实体/数字/否定校验;高风险意图加判定模型;
- 向量维度与嵌入版本绑定,换模型走新索引;
-
expires_at过滤 + 后台 GC,不依赖 TTL 清理索引; - 单飞/短锁限制惊群,等待有超时与兜底;
- 只缓存完整、正常结束的结果;
- 依赖失效可追溯,失效失败有对账;
- 监控:分层命中率、误判率、P99 开销、节省 token 数、内存成本。
参考资料
- Redis 官方文档:Query Engine(vector search、KNN、TAG/NUMERIC 过滤)、Bloom filter、HyperLogLog、Key eviction。
- RedisBloom 文档:
BF.RESERVE、BF.INFO、CF.*、扩容与误差率。 - Redis 官方文档:Client-side caching、LFU/LRU、
OBJECT FREQ。 - XFetch 论文:Optimal Probabilistic Cache Stampede Prevention(Vattani et al.)。
- Anthropic / OpenAI 关于 prompt caching 的官方文档(前缀缓存与计费规则)。