cache-strategy

为 API 和 Web 应用设计与实现缓存层,使用 Redis 或 Memcached。适用于降低数据库负载、提升响应时间或应对流量高峰,涵盖 cache-aside、write-through、write-behind 模式、TTL 策略、缓存失效机制及缓存雪崩防护。触发词:缓存、Redis、Memcached、TTL、缓存失效、响应时间、吞吐量、速率限制。

仓库最近推送
GitHub Stars
219
Forks
38
Issues / PRs
7

安装方式

先用 Prompt 核对来源与依赖。也可下载安装包。

用 AI 助手安装

复制提示词,让助手先核对固定版本和依赖。

查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "cache-strategy":https://skillpi.com/zh/skills/deepskill-8631d122e5ace19005c852fa96ca0af2984ee85b1b81ae252ee41abe00b4fb4e。安装前核对上游来源和版本:https://github.com/TerminalSkills/skills。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

来源与配置

github.com

配置方式待核实

请查看原始来源中的适用工具、依赖和权限要求。

安装实测待补充

为 API 和 Web 应用设计与实现缓存层,使用 Redis 或 Memcached。适用于降低数据库负载、提升响应时间或应对流量高峰,涵盖 cache-aside、write-through、write-behind 模式、TTL 策略、缓存失效机制及缓存雪崩防护。触发词:缓存、Redis、Memcached、TTL、缓存失效、响应时间、吞吐量、速率限制。

0 下载

介绍来源: third_party · TerminalSkills · 1.0.0 参考来源

SkillPi 解读

实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
Frontmatter
name: cache-strategy
description: >-
  Design and implement caching layers for APIs and web applications using Redis
  or Memcached. Use when you need to reduce database load, improve response times,
  or handle traffic spikes. Covers cache-aside, write-through, and write-behind
  patterns, TTL strategies, cache invalidation, and stampede prevention.
  Trigger words: cache, Redis, Memcached, TTL, cache invalidation, response time,
  throughput, rate limiting.
license: Apache-2.0
compatibility: "Redis 7+ or Memcached 1.6+. Node.js 18+ or Python 3.10+."
metadata:
  author: terminal-skills
  version: "1.0.0"
  category: development
  tags: ["caching", "redis", "performance", "api-optimization"]

Cache Strategy

Overview

This skill helps you design and implement multi-layer caching strategies for high-traffic APIs. It covers choosing the right caching pattern for your data access profile, configuring TTLs, preventing cache stampedes, and setting up cache invalidation that actually works in production.

Instructions

1. Analyze the caching opportunity

Before adding caching, identify what to cache by examining query patterns:

// Instrument your API routes to log response times and call frequency
// Look for: high frequency + low change rate = best cache candidates
// Example analysis output:
// GET /api/products      → 12,000 req/min, changes every 30min → CACHE (TTL: 5min)
// GET /api/products/:id  → 8,000 req/min, changes on update   → CACHE (invalidate on write)
// POST /api/orders       → 200 req/min, always unique          → DO NOT CACHE
// GET /api/user/profile  → 3,000 req/min, changes rarely       → CACHE (TTL: 15min)

2. Implement cache-aside pattern (most common)

The application checks cache first, falls back to database, then populates cache:

import Redis from "ioredis";

const redis = new Redis({ host: "localhost", port: 6379, maxRetriesPerRequest: 3 });

async function getCached<T>(
  key: string,
  fetcher: () => Promise<T>,
  ttlSeconds: number = 300
): Promise<T> {
  const cached = await redis.get(key);
  if (cached) return JSON.parse(cached);

  const data = await fetcher();
  await redis.set(key, JSON.stringify(data), "EX", ttlSeconds);
  return data;
}

// Usage in route handler
app.get("/api/products/:id", async (req, res) => {
  const product = await getCached(
    `product:${req.params.id}`,
    () => db.products.findById(req.params.id),
    600 // 10 minutes
  );
  res.json(product);
});

3. Prevent cache stampedes

When a popular key expires, hundreds of requests hit the database simultaneously:

async function getCachedWithLock<T>(
  key: string,
  fetcher: () => Promise<T>,
  ttlSeconds: number = 300
): Promise<T> {
  const cached = await redis.get(key);
  if (cached) return JSON.parse(cached);

  const lockKey = `lock:${key}`;
  const acquired = await redis.set(lockKey, "1", "EX", 10, "NX");

  if (acquired) {
    try {
      const data = await fetcher();
      await redis.set(key, JSON.stringify(data), "EX", ttlSeconds);
      return data;
    } finally {
      await redis.del(lockKey);
    }
  }

  // Another process is refreshing — wait and retry
  await new Promise((r) => setTimeout(r, 100));
  return getCachedWithLock(key, fetcher, ttlSeconds);
}

4. Cache invalidation strategies

Pattern-based invalidation for related data:

async function invalidatePattern(pattern: string): Promise<void> {
  let cursor = "0";
  do {
    const [nextCursor, keys] = await redis.scan(cursor, "MATCH", pattern, "COUNT", 100);
    if (keys.length > 0) await redis.del(...keys);
    cursor = nextCursor;
  } while (cursor !== "0");
}

// On product update: invalidate product and any list containing it
async function onProductUpdate(productId: string): Promise<void> {
  await redis.del(`product:${productId}`);
  await invalidatePattern("products:list:*");
}

Examples

Example 1: API response caching

Prompt: "Add Redis caching to my Express API. The /api/catalog endpoint is called 15,000 times per minute but the data only changes when an admin publishes updates. I want sub-10ms response times."

Agent output:

  • Adds src/cache/redis-client.ts with connection pooling and retry config
  • Wraps /api/catalog with cache-aside pattern, 5-minute TTL
  • Adds stampede prevention with distributed locking
  • Creates src/cache/invalidation.ts — called from the admin publish endpoint to bust catalog cache
  • Adds cache hit/miss metrics via response headers (X-Cache: HIT / X-Cache: MISS)

Example 2: Multi-layer caching

Prompt: "Our product API serves 50,000 RPM. Add in-memory cache for the hottest 1,000 items and Redis for everything else. Products change when inventory updates."

Agent output:

  • Adds src/cache/memory-lru.ts using an LRU cache with 1,000 max entries and 60-second TTL
  • Adds src/cache/tiered-cache.ts that checks memory → Redis → database in sequence
  • Creates src/events/inventory-handler.ts that invalidates both cache layers on inventory change
  • Adds /admin/cache/stats endpoint showing hit rates for each layer

Guidelines

  • Cache-aside is the default — use write-through only when you need guaranteed cache freshness on writes.
  • Never cache without a TTL — even "permanent" data should have a long TTL (1 hour+) as a safety net.
  • Use key namespacing — prefix keys like products:v2:{id} so you can version your cache schema.
  • Monitor hit rate — below 80% means your TTL is too short or your data changes too fast for caching.
  • Serialize carefully — JSON.parse/stringify is fine for most cases but consider MessagePack for large payloads.
  • Plan for Redis downtime — your app should degrade gracefully to direct database queries, not crash.
  • Avoid caching user-specific data in shared caches without proper key isolation — data leaks are a security incident.

当前收录版本

1.0.0

核对来源版本 ↗

质量评测

满分100 · 来自 SkillPi LAB 实验室的评测报告。

场景价值92/100

待提升项

  • 缺少 When to Use 显式章节 原报告严重程度:轻微

    文档未设置独立的 When to Use 章节,使用场景描述分散在 Overview 和 Instructions 中。

    改进建议:建议添加独立的 When to Use 章节,集中说明适用场景和边界条件。

  • 示例未完整展示文件创建细节 原报告严重程度:轻微

    Example 1 和 Example 2 提到了创建多个文件(如 redis-client.ts、invalidation.ts),但未提供完整的文件内容或目录结构说明。

    改进建议:建议在示例中补充关键文件的代码片段或目录结构图,提升可操作性。

亮点

  • 覆盖缓存旁路、直写、延迟写等多种模式,满足不同数据一致性需求
  • 提供防缓存雪崩的分布式锁实现,提升系统稳定性
  • 包含多层缓存(内存+Redis)设计,适用于高并发场景
触发精准95/100

亮点

  • 触发词覆盖全面,包含技术栈(Redis/Memcached)、策略(TTL/失效)、目标(响应时间/吞吐量)
  • 边界清晰,不易与其他性能优化 Skill 混淆
结构规范90/100

待提升项

  • 文档结构可进一步优化 原报告严重程度:轻微

    Instructions 部分步骤划分清晰,但 Guidelines 与 Examples 之间可增加过渡说明。

    改进建议:建议在 Guidelines 前添加简短说明,解释其与前面实现步骤的关系。

亮点

  • Phase 划分清晰(分析→实现→防护→失效),符合实际开发流程
  • 提供端到端示例,涵盖单缓存层和多层缓存场景
  • frontmatter 完整,包含兼容性、作者、分类等信息
执行可靠88/100

待提升项

  • 错误处理可更完善 原报告严重程度:轻微

    getCachedWithLock 中的 fetcher() 异常未捕获,可能导致锁未释放。

    改进建议:建议在 try 块内添加 fetcher() 的异常捕获,确保锁在异常情况下也能释放。

亮点

  • 工具来源明确(ioredis),参数使用正确(EX、NX)
  • 覆盖缓存雪崩防护,使用分布式锁避免数据库击穿
  • 缓存失效支持模式匹配,适用于批量清理场景
证据可验 (前四项均值)91/100

取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。

正文静态检测

100 / 100 · skillpi-20261123-no-r3-v1

正文未命中当前规则。

分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

未从主文档识别到上述常见操作,不能据此判断无需权限或没有风险。

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

safe · 静态证据核验,不代表运行安全保证。

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。