agentleFS
lamxylamxy/agent-prompt-rules-system/skills/skills-backend-dev/cache-design/SKILL.md

cache-design

Skill4 starsChanged 6 months agoMITView on GitHub

为 Go 后端设计 Redis 缓存:key 命名、数据类型、TTL、一致性策略、容量评估与降级。用户说「加缓存」「设计缓存」「Redis key 怎么设计」「缓存一致性」「排行榜/计数器/分布式锁怎么做」,或要把数据放进 Redis 时使用。只读取或排查已有缓存代码时不使用。

The file

Files
SKILL.md

缓存设计

逐条规则在 .claude/rules/redis.md,编辑缓存相关文件时自动加载;理由、内存编码、go-redis 参数与实测见 references/redis.md;读写、锁、限流、排行榜、队列取舍的 Go 模板见 references/patterns.md;代码放在哪一层、string 键值组件与 hash / set / zset 的完整示例见 references/layered-examples.md。

1. 先确认需要缓存

记录要解决的问题(读延迟、数据库压力),以及可以接受的数据延迟。数据源仍是数据库;不需要持久化的数据也不放进 Redis 当存储用。

2. 选数据类型

场景类型
普通键值、计数器string(计数用 INCR)
有多个属性的对象(只读写部分字段时)hash
最新 N 条、简单列表list(配合 LTRIM 控制长度)
去重集合、标签、推荐候选set
排行榜、按分数或时间排序zset

单个 key 的元素会持续增长时,按业务维度或哈希取模拆成多个 key。对象整体读写用 string 存序列化值;只改个别字段或计数用 hash,字段多(超过 listpack 阈值)时 hash 反而更占内存(见 references/redis.md)。

3. 设计 key 与 TTL

  • 按 <系统>:<模块>:<用途>:<数据类型>:<标识> 拼出 key,在代码中集中定义。
  • TTL = 基础时长 + 随机偏移(例如基础时长的 10%)。

4. 一致性与异常

默认用旁路缓存(cache-aside):

  • 读:查缓存 → 未命中查数据库 → 写回缓存。
  • 写:先更新数据库,再删除缓存(不是更新缓存);删除失败时重试或依靠 TTL 兜底。

同时说明以下问题的处理方式(Go 模板见 references/patterns.md 第 1、2 节):

问题常用做法
穿透(查询不存在的数据)缓存空值并设较短 TTL,或布隆过滤器
击穿(热点 key 过期)singleflight 合并回源请求;多实例仍压垮数据库时加分布式互斥或逻辑过期
雪崩(大量 key 同时过期或 Redis 不可用)TTL 随机偏移;客户端熔断后直接读数据库并限流

涉及分布式锁、计数器、限流、排行榜、延时任务或用 Redis 传递消息时,按 references/patterns.md 第 3~5 节选型,并写明锁失效时由什么保证正确性。

5. 容量与架构

先询问用户可用的资源上限(内存、CPU、节点数),再结合业务现状估算 key 数量 × 平均 value 大小 × 冗余系数,以及峰值 QPS。容量方案是建议,写明计算过程,由用户或负责的工程师决定(运维侧规划见 dev-ops middleware-ops)。单个主从实例承载不了时改用集群,并确认代码中没有集群不支持的跨 slot 多 key 操作(必要时按 rules/redis.md 在标识段加 hash tag,如 {u2001},让相关 key 落在同一 slot)。

6. 产出

在设计文档(docs/design/)中写明:key 清单(格式、类型、TTL、预估数量与大小)、一致性策略、降级方式、容量估算。实现后自查 .claude/rules/redis.md。

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.