cache-strategy

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Cache Strategy Implementation

缓存策略实现

I'll analyze your application and implement appropriate caching strategies to improve performance and reduce server load.
Arguments:
$ARGUMENTS
- cache type focus (e.g., "http", "service-worker", "redis", "browser")
我会分析您的应用并实现合适的缓存策略,以提升性能并降低服务器负载。
参数:
$ARGUMENTS
- 重点缓存类型(例如:"http", "service-worker", "redis", "browser")

Strategic Planning Process

战略规划流程

<think> Effective caching requires careful strategy:
  1. Application Analysis
    • What type of application? (SPA, MPA, API, static site)
    • What data changes frequently vs. rarely?
    • What's cached currently, if anything?
    • Client-side, server-side, or both?
    • CDN usage and configuration
  2. Cache Layer Selection
    • Browser cache (HTTP headers)
    • Service worker cache (offline-first PWA)
    • Application cache (in-memory, localStorage)
    • Server cache (Redis, Memcached)
    • CDN cache (edge caching)
    • Database query cache
  3. Cache Invalidation Strategy
    • Time-based expiration (TTL)
    • Event-based invalidation
    • Version-based cache busting
    • Manual invalidation mechanisms
    • Stale-while-revalidate patterns
  4. Performance vs. Freshness Tradeoff
    • Critical real-time data (no cache or very short TTL)
    • Semi-dynamic data (short TTL, stale-while-revalidate)
    • Static assets (long TTL, immutable)
    • User-specific data (private cache)
</think>
<think> 有效的缓存需要谨慎制定策略:
  1. 应用分析
    • 应用类型是什么?(SPA、MPA、API、静态站点)
    • 哪些数据更新频繁,哪些很少更新?
    • 当前有没有缓存内容?有的话是哪些?
    • 是客户端缓存、服务端缓存还是两者都有?
    • CDN使用和配置情况
  2. 缓存层选择
    • 浏览器缓存(HTTP headers)
    • Service worker缓存(离线优先PWA)
    • 应用缓存(内存、localStorage)
    • 服务端缓存(Redis、Memcached)
    • CDN缓存(边缘缓存)
    • 数据库查询缓存
  3. 缓存失效策略
    • 基于时间的过期(TTL)
    • 基于事件的失效
    • 基于版本的缓存清理
    • 手动失效机制
    • stale-while-revalidate模式
  4. 性能与新鲜度权衡
    • 关键实时数据(无缓存或极短TTL)
    • 半动态数据(短TTL、stale-while-revalidate)
    • 静态资源(长TTL、不可变)
    • 用户专属数据(私有缓存)
</think>

Phase 1: Cache Audit

第一阶段:缓存审计

MANDATORY FIRST STEPS:
  1. Detect application type and architecture
  2. Analyze current caching configuration
  3. Identify cacheable resources
  4. Determine cache invalidation needs
Let me analyze your current caching setup:
bash
undefined
强制第一步:
  1. 检测应用类型和架构
  2. 分析当前缓存配置
  3. 识别可缓存资源
  4. 确定缓存失效需求
让我分析您当前的缓存配置:
bash
undefined

Check for existing cache configurations

检查现有缓存配置

echo "=== Cache Configuration Audit ==="
echo "=== 缓存配置审计 ==="

Check for service worker

检查service worker

if [ -f "public/service-worker.js" ] || [ -f "src/service-worker.js" ] || [ -f "sw.js" ]; then echo "✓ Service Worker detected" ls -lh **/service-worker.js **/sw.js 2>/dev/null | head -5 else echo "✗ No Service Worker found" fi
if [ -f "public/service-worker.js" ] || [ -f "src/service-worker.js" ] || [ -f "sw.js" ]; then echo "✓ 检测到Service Worker" ls -lh **/service-worker.js **/sw.js 2>/dev/null | head -5 else echo "✗ 未找到Service Worker" fi

Check for HTTP caching headers (common web server configs)

检查HTTP缓存header(常见web服务器配置)

if [ -f ".htaccess" ]; then echo "✓ Apache .htaccess found" grep -i "cache-control|expires" .htaccess 2>/dev/null | head -5 fi
if [ -f "nginx.conf" ] || [ -f "nginx/.conf" ]; then echo "✓ Nginx config found" grep -i "cache|expires" nginx.conf 2>/dev/null | head -5 fi
if [ -f ".htaccess" ]; then echo "✓ 检测到Apache .htaccess" grep -i "cache-control|expires" .htaccess 2>/dev/null | head -5 fi
if [ -f "nginx.conf" ] || [ -f "nginx/.conf" ]; then echo "✓ 检测到Nginx配置" grep -i "cache|expires" nginx.conf 2>/dev/null | head -5 fi

Check for Redis/Memcached dependencies

检查Redis/Memcached依赖

if grep -q ""redis"" package.json 2>/dev/null; then echo "✓ Redis client installed" fi
if grep -q ""memcached"" package.json 2>/dev/null; then echo "✓ Memcached client installed" fi
if grep -q ""redis"" package.json 2>/dev/null; then echo "✓ 已安装Redis客户端" fi
if grep -q ""memcached"" package.json 2>/dev/null; then echo "✓ 已安装Memcached客户端" fi

Check for caching libraries

检查缓存库

if grep -q ""workbox"" package.json 2>/dev/null; then echo "✓ Workbox (service worker toolkit) installed" fi
if grep -q ""workbox"" package.json 2>/dev/null; then echo "✓ 已安装Workbox(service worker工具包)" fi

Check CDN configuration

检查CDN配置

if [ -f "vercel.json" ] || [ -f "netlify.toml" ]; then echo "✓ CDN configuration detected" fi
undefined
if [ -f "vercel.json" ] || [ -f "netlify.toml" ]; then echo "✓ 检测到CDN配置" fi
undefined

Phase 2: Cache Strategy Design

第二阶段:缓存策略设计

Based on application type, I'll design appropriate caching layers:
根据应用类型,我会设计合适的缓存层:

Browser Cache Strategy (HTTP Headers)

浏览器缓存策略(HTTP Headers)

Static Assets:
  • Long cache duration (1 year)
  • Immutable for versioned assets
  • Public caching allowed
  • Proper ETag configuration
Dynamic Content:
  • Short cache duration or no-cache
  • Private cache for user-specific data
  • Stale-while-revalidate for better UX
  • Proper cache-control directives
API Responses:
  • Cache-Control based on data freshness
  • ETag for conditional requests
  • Vary headers for content negotiation
  • Private cache for authenticated requests
静态资源:
  • 长缓存时长(1年)
  • 带版本的资源设置为不可变
  • 允许公共缓存
  • 正确的ETag配置
动态内容:
  • 短缓存时长或no-cache
  • 用户专属数据使用私有缓存
  • Stale-while-revalidate提升用户体验
  • 正确的cache-control指令
API响应:
  • 根据数据新鲜度设置Cache-Control
  • 用ETag实现条件请求
  • 内容协商使用Vary header
  • 认证请求使用私有缓存

Service Worker Cache Strategy

Service Worker缓存策略

Cache-First (Offline-First):
  • Static assets, fonts, images
  • Application shell
  • Third-party libraries
Network-First:
  • API calls
  • Dynamic content
  • Real-time data
Stale-While-Revalidate:
  • Semi-dynamic content
  • News feeds, product listings
  • Balance freshness with performance
Cache-Only:
  • Fallback offline pages
  • Critical UI assets
缓存优先(离线优先):
  • 静态资源、字体、图片
  • 应用外壳
  • 第三方库
网络优先:
  • API调用
  • 动态内容
  • 实时数据
Stale-While-Revalidate:
  • 半动态内容
  • 新闻 feed、商品列表
  • 平衡新鲜度和性能
仅缓存:
  • 离线 fallback 页面
  • 关键UI资源

Application-Level Caching

应用层缓存

In-Memory Caching:
  • Computed values (memoization)
  • Expensive calculations
  • API response caching
  • Query result caching
Local Storage:
  • User preferences
  • Authentication tokens
  • Offline data sync
  • Application state persistence
内存缓存:
  • 计算值(memoization)
  • 高开销计算
  • API响应缓存
  • 查询结果缓存
Local Storage:
  • 用户偏好设置
  • 认证令牌
  • 离线数据同步
  • 应用状态持久化

Server-Side Caching

服务端缓存

Redis/Memcached:
  • Database query results
  • Computed data
  • Session storage
  • API response caching
  • Rate limiting data
CDN Edge Caching:
  • Static assets
  • API responses (when appropriate)
  • Geographic distribution
  • DDoS protection
Redis/Memcached:
  • 数据库查询结果
  • 计算后的数据
  • 会话存储
  • API响应缓存
  • 限流数据
CDN边缘缓存:
  • 静态资源
  • 合适的API响应
  • 地理分发
  • DDoS防护

Phase 3: Implementation

第三阶段:实现

I'll implement selected caching strategies:
我会实现选定的缓存策略:

HTTP Caching Headers

HTTP缓存Headers

For Node.js/Express:
javascript
// Static assets with long-term caching
app.use('/static', express.static('public', {
  maxAge: '1y',
  immutable: true,
  etag: true
}));

// API responses with short-term caching
app.use('/api', (req, res, next) => {
  res.set('Cache-Control', 'private, max-age=300'); // 5 minutes
  next();
});
For Next.js:
javascript
// next.config.js
module.exports = {
  async headers() {
    return [
      {
        source: '/_next/static/:path*',
        headers: [
          {
            key: 'Cache-Control',
            value: 'public, max-age=31536000, immutable',
          },
        ],
      },
    ];
  },
};
For Nginx:
nginx
undefined
Node.js/Express示例:
javascript
// 静态资源长期缓存
app.use('/static', express.static('public', {
  maxAge: '1y',
  immutable: true,
  etag: true
}));

// API响应短期缓存
app.use('/api', (req, res, next) => {
  res.set('Cache-Control', 'private, max-age=300'); // 5分钟
  next();
});
Next.js示例:
javascript
// next.config.js
module.exports = {
  async headers() {
    return [
      {
        source: '/_next/static/:path*',
        headers: [
          {
            key: 'Cache-Control',
            value: 'public, max-age=31536000, immutable',
          },
        ],
      },
    ];
  },
};
Nginx示例:
nginx
undefined

Static assets

静态资源

location ~* .(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2)$ { expires 1y; add_header Cache-Control "public, immutable"; }
location ~* .(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2)$ { expires 1y; add_header Cache-Control "public, immutable"; }

HTML files - no cache

HTML文件 - 无缓存

location ~* .html$ { expires -1; add_header Cache-Control "no-cache, no-store, must-revalidate"; }
undefined
location ~* .html$ { expires -1; add_header Cache-Control "no-cache, no-store, must-revalidate"; }
undefined

Service Worker Implementation

Service Worker实现

Workbox Configuration:
javascript
import { precacheAndRoute } from 'workbox-precaching';
import { registerRoute } from 'workbox-routing';
import { CacheFirst, NetworkFirst, StaleWhileRevalidate } from 'workbox-strategies';
import { ExpirationPlugin } from 'workbox-expiration';
import { CacheableResponsePlugin } from 'workbox-cacheable-response';

// Precache static assets
precacheAndRoute(self.__WB_MANIFEST);

// Cache images with Cache First strategy
registerRoute(
  ({ request }) => request.destination === 'image',
  new CacheFirst({
    cacheName: 'images',
    plugins: [
      new ExpirationPlugin({
        maxEntries: 60,
        maxAgeSeconds: 30 * 24 * 60 * 60, // 30 Days
      }),
    ],
  })
);

// API calls with Network First strategy
registerRoute(
  ({ url }) => url.pathname.startsWith('/api/'),
  new NetworkFirst({
    cacheName: 'api-cache',
    plugins: [
      new CacheableResponsePlugin({
        statuses: [0, 200],
      }),
      new ExpirationPlugin({
        maxAgeSeconds: 5 * 60, // 5 minutes
      }),
    ],
  })
);

// CSS and JS with Stale While Revalidate
registerRoute(
  ({ request }) => request.destination === 'style' || request.destination === 'script',
  new StaleWhileRevalidate({
    cacheName: 'static-resources',
  })
);
Workbox配置:
javascript
import { precacheAndRoute } from 'workbox-precaching';
import { registerRoute } from 'workbox-routing';
import { CacheFirst, NetworkFirst, StaleWhileRevalidate } from 'workbox-strategies';
import { ExpirationPlugin } from 'workbox-expiration';
import { CacheableResponsePlugin } from 'workbox-cacheable-response';

// 预缓存静态资源
precacheAndRoute(self.__WB_MANIFEST);

// 图片使用缓存优先策略
registerRoute(
  ({ request }) => request.destination === 'image',
  new CacheFirst({
    cacheName: 'images',
    plugins: [
      new ExpirationPlugin({
        maxEntries: 60,
        maxAgeSeconds: 30 * 24 * 60 * 60, // 30天
      }),
    ],
  })
);

// API调用使用网络优先策略
registerRoute(
  ({ url }) => url.pathname.startsWith('/api/'),
  new NetworkFirst({
    cacheName: 'api-cache',
    plugins: [
      new CacheableResponsePlugin({
        statuses: [0, 200],
      }),
      new ExpirationPlugin({
        maxAgeSeconds: 5 * 60, // 5分钟
      }),
    ],
  })
);

// CSS和JS使用stale-while-revalidate
registerRoute(
  ({ request }) => request.destination === 'style' || request.destination === 'script',
  new StaleWhileRevalidate({
    cacheName: 'static-resources',
  })
);

Memoization Patterns

Memoization模式

React Memoization:
javascript
import { useMemo, useCallback } from 'react';
import { memo } from 'react';

// Memoize expensive calculations
const ExpensiveComponent = ({ data }) => {
  const processedData = useMemo(() => {
    return expensiveCalculation(data);
  }, [data]);

  const handleClick = useCallback(() => {
    // Handler logic
  }, []);

  return <div>{processedData}</div>;
};

export default memo(ExpensiveComponent);
Function Memoization:
javascript
// Simple memoization utility
function memoize(fn) {
  const cache = new Map();
  return (...args) => {
    const key = JSON.stringify(args);
    if (cache.has(key)) {
      return cache.get(key);
    }
    const result = fn(...args);
    cache.set(key, result);
    return result;
  };
}

// LRU cache with size limit
class LRUCache {
  constructor(limit = 100) {
    this.cache = new Map();
    this.limit = limit;
  }

  get(key) {
    if (!this.cache.has(key)) return undefined;
    const value = this.cache.get(key);
    this.cache.delete(key);
    this.cache.set(key, value); // Move to end
    return value;
  }

  set(key, value) {
    if (this.cache.has(key)) {
      this.cache.delete(key);
    } else if (this.cache.size >= this.limit) {
      const firstKey = this.cache.keys().next().value;
      this.cache.delete(firstKey);
    }
    this.cache.set(key, value);
  }
}
React Memoization:
javascript
import { useMemo, useCallback } from 'react';
import { memo } from 'react';

// 记忆化高开销计算
const ExpensiveComponent = ({ data }) => {
  const processedData = useMemo(() => {
    return expensiveCalculation(data);
  }, [data]);

  const handleClick = useCallback(() => {
    // 处理逻辑
  }, []);

  return <div>{processedData}</div>;
};

export default memo(ExpensiveComponent);
函数Memoization:
javascript
// 简单memoization工具
function memoize(fn) {
  const cache = new Map();
  return (...args) => {
    const key = JSON.stringify(args);
    if (cache.has(key)) {
      return cache.get(key);
    }
    const result = fn(...args);
    cache.set(key, result);
    return result;
  };
}

// 带大小限制的LRU缓存
class LRUCache {
  constructor(limit = 100) {
    this.cache = new Map();
    this.limit = limit;
  }

  get(key) {
    if (!this.cache.has(key)) return undefined;
    const value = this.cache.get(key);
    this.cache.delete(key);
    this.cache.set(key, value); // 移到末尾
    return value;
  }

  set(key, value) {
    if (this.cache.has(key)) {
      this.cache.delete(key);
    } else if (this.cache.size >= this.limit) {
      const firstKey = this.cache.keys().next().value;
      this.cache.delete(firstKey);
    }
    this.cache.set(key, value);
  }
}

Redis Caching

Redis缓存

Express with Redis:
javascript
const redis = require('redis');
const client = redis.createClient();

// Cache middleware
const cache = (duration) => {
  return async (req, res, next) => {
    const key = `cache:${req.originalUrl}`;

    try {
      const cached = await client.get(key);
      if (cached) {
        return res.json(JSON.parse(cached));
      }

      // Store original send function
      const originalSend = res.json.bind(res);

      // Override send to cache response
      res.json = (body) => {
        client.setex(key, duration, JSON.stringify(body));
        return originalSend(body);
      };

      next();
    } catch (err) {
      next();
    }
  };
};

// Use cache middleware
app.get('/api/data', cache(300), async (req, res) => {
  const data = await fetchData();
  res.json(data);
});
Express + Redis示例:
javascript
const redis = require('redis');
const client = redis.createClient();

// 缓存中间件
const cache = (duration) => {
  return async (req, res, next) => {
    const key = `cache:${req.originalUrl}`;

    try {
      const cached = await client.get(key);
      if (cached) {
        return res.json(JSON.parse(cached));
      }

      // 保存原始send函数
      const originalSend = res.json.bind(res);

      // 重写send以缓存响应
      res.json = (body) => {
        client.setex(key, duration, JSON.stringify(body));
        return originalSend(body);
      };

      next();
    } catch (err) {
      next();
    }
  };
};

// 使用缓存中间件
app.get('/api/data', cache(300), async (req, res) => {
  const data = await fetchData();
  res.json(data);
});

Phase 4: Cache Invalidation

第四阶段:缓存失效

I'll implement appropriate invalidation strategies:
Time-Based Expiration:
  • Set appropriate TTL values
  • Use max-age headers
  • Configure Redis expiration
  • Implement cleanup routines
Event-Based Invalidation:
  • Clear cache on data updates
  • Invalidate related cache entries
  • Use cache tags for grouped invalidation
  • Implement webhook-based clearing
Version-Based Cache Busting:
  • Content hashing for static assets
  • API versioning
  • Service worker updates
  • Cache key versioning
我会实现合适的失效策略:
基于时间的过期:
  • 设置合适的TTL值
  • 使用max-age header
  • 配置Redis过期
  • 实现清理程序
基于事件的失效:
  • 数据更新时清除缓存
  • 失效相关缓存条目
  • 使用缓存标签实现分组失效
  • 实现webhook式清理
基于版本的缓存清理:
  • 静态资源内容哈希
  • API版本控制
  • Service worker更新
  • 缓存键版本化

Token Optimization

令牌优化

Status: ✅ Fully Optimized (Phase 2 Batch 4B, 2026-01-27)
Baseline: 3,000-5,000 tokens → Optimized: 1,000-1,800 tokens (60-75% reduction)
This skill is meta - it implements caching FOR applications while using caching optimization strategies itself!
状态:✅ 完全优化(2026-01-27 第2批次4B阶段)
基线:3000-5000 tokens → 优化后:1000-1800 tokens(减少60-75%)
这个技能是元技能——它为应用实现缓存的同时本身也使用了缓存优化策略!

Core Optimization Strategies

核心优化策略

1. Template-Based Cache Patterns (75% savings)

1. 基于模板的缓存模式(节省75%)

Cache:
.claude/cache/cache-strategy/cache_patterns.json
json
{
  "redis": {
    "express": "// Express Redis middleware...",
    "nextjs": "// Next.js Redis client...",
    "django": "# Django Redis cache backend..."
  },
  "service_worker": {
    "workbox": "// Workbox config...",
    "vanilla": "// Vanilla SW..."
  },
  "http_headers": {
    "nginx": "location ~* ...",
    "apache": "ExpiresActive On...",
    "express": "app.use(express.static..."
  },
  "in_memory": {
    "react": "useMemo hook...",
    "node": "LRU cache class...",
    "python": "functools.lru_cache..."
  }
}
Strategy:
  • Read 1 pattern template (200 tokens) vs. searching examples (2,000+ tokens)
  • Framework-specific snippets instantly available
  • No pattern re-generation across sessions
缓存:
.claude/cache/cache-strategy/cache_patterns.json
json
{
  "redis": {
    "express": "// Express Redis middleware...",
    "nextjs": "// Next.js Redis client...",
    "django": "# Django Redis cache backend..."
  },
  "service_worker": {
    "workbox": "// Workbox config...",
    "vanilla": "// Vanilla SW..."
  },
  "http_headers": {
    "nginx": "location ~* ...",
    "apache": "ExpiresActive On...",
    "express": "app.use(express.static..."
  },
  "in_memory": {
    "react": "useMemo hook...",
    "node": "LRU cache class...",
    "python": "functools.lru_cache..."
  }
}
策略:
  • 读取1个模板(200 tokens)替代搜索示例(2000+ tokens)
  • 框架专属代码片段立即可用
  • 跨会话无需重新生成模式

2. Focus Area Identification (70% savings)

2. 焦点区域识别(节省70%)

Grep before Read approach:
bash
undefined
先Grep再读取的方式:
bash
undefined

Identify cache targets (100 tokens vs. 2,000 reading all code)

识别缓存目标(100 tokens 替代读取所有代码的2000 tokens)

grep -r "fetch|axios|api." src/ --files-with-matches grep -r "SELECT|query|find(" src/ --files-with-matches grep -r "expensive|calculation|compute" src/ --files-with-matches

**Cache:** `.claude/cache/cache-strategy/hot_paths.json`
```json
{
  "api_routes": ["src/api/users.js", "src/api/products.js"],
  "db_queries": ["src/models/User.js"],
  "expensive_calculations": ["src/utils/analytics.js"],
  "last_scan": "2026-01-27T10:00:00Z"
}
Strategy:
  • Only read files with cache opportunities
  • Skip non-relevant code (tests, configs, types)
  • Focus on high-impact areas first
grep -r "fetch|axios|api." src/ --files-with-matches grep -r "SELECT|query|find(" src/ --files-with-matches grep -r "expensive|calculation|compute" src/ --files-with-matches

**缓存:** `.claude/cache/cache-strategy/hot_paths.json`
```json
{
  "api_routes": ["src/api/users.js", "src/api/products.js"],
  "db_queries": ["src/models/User.js"],
  "expensive_calculations": ["src/utils/analytics.js"],
  "last_scan": "2026-01-27T10:00:00Z"
}
策略:
  • 仅读取有缓存优化空间的文件
  • 跳过非相关代码(测试、配置、类型定义)
  • 优先聚焦高影响区域

3. Cached Best Practices (80% savings)

3. 缓存的最佳实践(节省80%)

Cache:
.claude/cache/cache-strategy/recommendations.json
json
{
  "ttl_guidelines": {
    "static_assets": "1y (31536000s)",
    "api_responses": "5m (300s)",
    "user_data": "no-cache",
    "computed_data": "1h (3600s)"
  },
  "invalidation_patterns": {
    "time_based": "Use max-age + stale-while-revalidate",
    "event_based": "Cache tags + manual clear",
    "version_based": "Content hashing for assets"
  },
  "cache_strategies": {
    "cache_first": "Static assets, images, fonts",
    "network_first": "API calls, real-time data",
    "stale_while_revalidate": "Semi-dynamic content"
  }
}
Strategy:
  • Instant recommendations (no re-thinking)
  • Consistent TTL values across projects
  • Proven invalidation patterns
缓存:
.claude/cache/cache-strategy/recommendations.json
json
{
  "ttl_guidelines": {
    "static_assets": "1y (31536000s)",
    "api_responses": "5m (300s)",
    "user_data": "no-cache",
    "computed_data": "1h (3600s)"
  },
  "invalidation_patterns": {
    "time_based": "Use max-age + stale-while-revalidate",
    "event_based": "Cache tags + manual clear",
    "version_based": "Content hashing for assets"
  },
  "cache_strategies": {
    "cache_first": "Static assets, images, fonts",
    "network_first": "API calls, real-time data",
    "stale_while_revalidate": "Semi-dynamic content"
  }
}
策略:
  • 即时给出建议(无需重新思考)
  • 项目间保持一致的TTL值
  • 经过验证的失效模式

4. Framework-Specific Templates (70% savings)

4. 框架专属模板(节省70%)

Cache:
.claude/cache/cache-strategy/framework_templates.json
json
{
  "express_redis": {
    "middleware": "const cache = (duration) => {...}",
    "client_setup": "const redis = require('redis')...",
    "error_handling": "try { cached = await client.get... }"
  },
  "nextjs_swr": {
    "config": "export const fetcher = ...",
    "revalidation": "revalidateOnFocus: false..."
  },
  "django_redis": {
    "settings": "CACHES = { 'default': {...} }",
    "decorator": "@cache_page(60 * 15)..."
  }
}
Strategy:
  • Framework detected once (package.json/requirements.txt)
  • Load only relevant templates
  • No generic examples - specific to tech stack
缓存:
.claude/cache/cache-strategy/framework_templates.json
json
{
  "express_redis": {
    "middleware": "const cache = (duration) => {...}",
    "client_setup": "const redis = require('redis')...",
    "error_handling": "try { cached = await client.get... }"
  },
  "nextjs_swr": {
    "config": "export const fetcher = ...",
    "revalidation": "revalidateOnFocus: false..."
  },
  "django_redis": {
    "settings": "CACHES = { 'default': {...} }",
    "decorator": "@cache_page(60 * 15)..."
  }
}
策略:
  • 仅检测一次框架(通过package.json/requirements.txt)
  • 仅加载相关模板
  • 没有通用示例——完全适配技术栈

5. Progressive Implementation (60% savings)

5. 渐进式实现(节省60%)

Cache:
.claude/cache/cache-strategy/implementation_status.json
json
{
  "src/api/users.js": {
    "status": "redis_cache_added",
    "ttl": 300,
    "last_modified": "2026-01-27T10:00:00Z"
  },
  "src/components/ExpensiveChart.js": {
    "status": "memoization_added",
    "technique": "useMemo",
    "last_modified": "2026-01-27T09:00:00Z"
  },
  "public/service-worker.js": {
    "status": "workbox_configured",
    "strategies": ["CacheFirst", "NetworkFirst"],
    "last_modified": "2026-01-26T15:00:00Z"
  }
}
Strategy:
  • Track what's already cached
  • Skip implemented areas
  • Focus on remaining high-impact targets
缓存:
.claude/cache/cache-strategy/implementation_status.json
json
{
  "src/api/users.js": {
    "status": "redis_cache_added",
    "ttl": 300,
    "last_modified": "2026-01-27T10:00:00Z"
  },
  "src/components/ExpensiveChart.js": {
    "status": "memoization_added",
    "technique": "useMemo",
    "last_modified": "2026-01-27T09:00:00Z"
  },
  "public/service-worker.js": {
    "status": "workbox_configured",
    "strategies": ["CacheFirst", "NetworkFirst"],
    "last_modified": "2026-01-26T15:00:00Z"
  }
}
策略:
  • 跟踪已实现的缓存内容
  • 跳过已实现区域
  • 聚焦剩余高影响目标

Optimization Workflow

优化工作流

Initial Cache Audit (300 tokens vs. 2,000)

初始缓存审计(300 tokens 替代 2000)

bash
undefined
bash
undefined

Fast detection (5 commands vs. reading all configs)

快速检测(5条命令 替代读取所有配置)

ls -la public/service-worker.js 2>/dev/null grep -q "redis|memcached" package.json ls -la nginx.conf .htaccess 2>/dev/null grep -q "workbox|sw-precache" package.json ls -la vercel.json netlify.toml 2>/dev/null
undefined
ls -la public/service-worker.js 2>/dev/null grep -q "redis|memcached" package.json ls -la nginx.conf .htaccess 2>/dev/null grep -q "workbox|sw-precache" package.json ls -la vercel.json netlify.toml 2>/dev/null
undefined

Focus Area Selection (200 tokens vs. 1,500)

焦点区域选择(200 tokens 替代 1500)

Arguments-based routing:
  • http
    → HTTP headers only (400 tokens)
  • redis
    → Redis caching only (500 tokens)
  • service-worker
    → PWA caching only (600 tokens)
  • No args → Full analysis (1,800 tokens)
基于参数的路由:
  • http
    → 仅HTTP headers(400 tokens)
  • redis
    → 仅Redis缓存(500 tokens)
  • service-worker
    → 仅PWA缓存(600 tokens)
  • 无参数 → 完整分析(1800 tokens)

Template Application (400 tokens vs. 2,000)

模板应用(400 tokens 替代 2000)

bash
undefined
bash
undefined

Load cached template, insert into file

加载缓存模板,插入到文件

No generation, no examples, direct application

无需生成、无需示例,直接应用

undefined
undefined

Token Budget Allocation

令牌预算分配

Total Budget: 1,000-1,800 tokens
  1. Cache Audit (300 tokens)
    • Framework detection: 50 tokens
    • Existing cache scan: 100 tokens
    • Focus area identification: 150 tokens
  2. Strategy Selection (200 tokens)
    • Load cached recommendations: 100 tokens
    • Match to detected framework: 100 tokens
  3. Template Loading (300 tokens)
    • Load framework template: 150 tokens
    • Load best practices: 150 tokens
  4. Implementation (400-800 tokens)
    • Apply templates: 200-400 tokens
    • Targeted file edits: 200-400 tokens
  5. Validation (200 tokens)
    • Update status cache: 100 tokens
    • Report changes: 100 tokens
总预算:1000-1800 tokens
  1. 缓存审计(300 tokens)
    • 框架检测:50 tokens
    • 现有缓存扫描:100 tokens
    • 焦点区域识别:150 tokens
  2. 策略选择(200 tokens)
    • 加载缓存的建议:100 tokens
    • 匹配检测到的框架:100 tokens
  3. 模板加载(300 tokens)
    • 加载框架模板:150 tokens
    • 加载最佳实践:150 tokens
  4. 实现(400-800 tokens)
    • 应用模板:200-400 tokens
    • 定向文件编辑:200-400 tokens
  5. 验证(200 tokens)
    • 更新状态缓存:100 tokens
    • 变更报告:100 tokens

Cache Maintenance

缓存维护

Auto-refresh triggers:
  • New framework detected → Fetch new templates
  • package.json changed → Re-scan dependencies
  • 30 days since last scan → Full re-audit
Cache invalidation:
bash
undefined
自动刷新触发条件:
  • 检测到新框架 → 获取新模板
  • package.json变更 → 重新扫描依赖
  • 距离上次扫描超过30天 → 完整重新审计
缓存失效:
bash
undefined

Clear stale cache (e.g., after major refactor)

清除过时缓存(例如大重构后)

rm -rf .claude/cache/cache-strategy/
undefined
rm -rf .claude/cache/cache-strategy/
undefined

Comparison: Before vs. After

对比:优化前后

Before Optimization (4,000 tokens):
  1. Read all config files (800 tokens)
  2. Analyze entire codebase (1,500 tokens)
  3. Generate cache patterns (1,000 tokens)
  4. Explain all strategies (500 tokens)
  5. Implement changes (200 tokens)
After Optimization (1,200 tokens):
  1. Grep for cache targets (100 tokens)
  2. Load cached templates (200 tokens)
  3. Apply focused strategy (400 tokens)
  4. Update implementation cache (100 tokens)
  5. Report changes (400 tokens)
Savings: 70% reduction (2,800 tokens saved)
优化前(4000 tokens):
  1. 读取所有配置文件(800 tokens)
  2. 分析整个代码库(1500 tokens)
  3. 生成缓存模式(1000 tokens)
  4. 解释所有策略(500 tokens)
  5. 实现变更(200 tokens)
优化后(1200 tokens):
  1. Grep缓存目标(100 tokens)
  2. 加载缓存模板(200 tokens)
  3. 应用定向策略(400 tokens)
  4. 更新实现缓存(100 tokens)
  5. 变更报告(400 tokens)
节省:减少70%(节省2800 tokens)

Integration with Other Skills

与其他技能集成

Skill synergy caching:
json
{
  "triggers_webpack_optimize": ["Build tool cache needed"],
  "triggers_performance_profile": ["Measure cache hit rates"],
  "triggers_lighthouse": ["Validate cache headers"],
  "triggered_by_ci_setup": ["CI/CD cache configuration"]
}
Strategy:
  • Cache skill relationships
  • Avoid re-analyzing when chained
  • Share framework detection results
技能协同缓存:
json
{
  "triggers_webpack_optimize": ["需要构建工具缓存"],
  "triggers_performance_profile": ["测量缓存命中率"],
  "triggers_lighthouse": ["验证缓存headers"],
  "triggered_by_ci_setup": ["CI/CD缓存配置"]
}
策略:
  • 缓存技能关联关系
  • 链式调用时避免重复分析
  • 共享框架检测结果

Success Metrics

成功指标

Token efficiency:
  • HTTP headers only: 400-600 tokens (85% reduction)
  • Redis setup only: 500-800 tokens (80% reduction)
  • Service worker only: 600-1,000 tokens (75% reduction)
  • Full implementation: 1,000-1,800 tokens (60% reduction)
Cache hit rates:
  • Template patterns: 95% (rarely change)
  • Framework detection: 90% (stable per project)
  • Best practices: 98% (universal guidelines)
  • Hot paths: 80% (evolve with code)
令牌效率:
  • 仅HTTP headers:400-600 tokens(减少85%)
  • 仅Redis配置:500-800 tokens(减少80%)
  • 仅Service worker:600-1000 tokens(减少75%)
  • 完整实现:1000-1800 tokens(减少60%)
缓存命中率:
  • 模板模式:95%(很少变更)
  • 框架检测:90%(每个项目稳定)
  • 最佳实践:98%(通用准则)
  • 热路径:80%(随代码演进)

Integration Points

集成点

Synergistic Skills:
  • /webpack-optimize
    - Build tool caching and optimization
  • /performance-profile
    - Measure cache effectiveness
  • /lighthouse
    - Audit cache headers and service workers
  • /ci-setup
    - Configure cache in CI/CD pipelines
Suggests
/webpack-optimize
when:
  • Build tool caching needs optimization
  • Bundle splitting affects cache strategy
Suggests
/performance-profile
when:
  • Need to measure cache hit rates
  • Validate cache performance improvements
协同技能:
  • /webpack-optimize
    - 构建工具缓存和优化
  • /performance-profile
    - 测量缓存有效性
  • /lighthouse
    - 审计缓存headers和service workers
  • /ci-setup
    - 在CI/CD流水线中配置缓存
在以下场景建议使用
/webpack-optimize
  • 构建工具缓存需要优化
  • 代码分割影响缓存策略
在以下场景建议使用
/performance-profile
  • 需要测量缓存命中率
  • 验证缓存性能提升

Safety Mechanisms

安全机制

Protection Measures:
  • Create git checkpoint before changes
  • Test cache strategies in development
  • Validate cache invalidation works
  • Ensure no sensitive data cached
  • Provide cache debugging instructions
Cache Debugging:
bash
undefined
防护措施:
  • 变更前创建git检查点
  • 在开发环境测试缓存策略
  • 验证缓存失效正常工作
  • 确保没有敏感数据被缓存
  • 提供缓存调试说明
缓存调试:
bash
undefined

Clear browser cache for testing

清除浏览器缓存用于测试

Chrome DevTools: Application > Clear storage

Chrome DevTools: Application > Clear storage

Clear Redis cache

清除Redis缓存

redis-cli FLUSHDB
redis-cli FLUSHDB

Clear service worker cache

清除service worker缓存

Chrome DevTools: Application > Service Workers > Unregister

Chrome DevTools: Application > Service Workers > Unregister


**Rollback Procedure:**
```bash

**回滚流程:**
```bash

Restore previous configuration

恢复之前的配置

git checkout HEAD -- nginx.conf service-worker.js
git checkout HEAD -- nginx.conf service-worker.js

Clear problematic cache

清除有问题的缓存

Rebuild and redeploy

重新构建并部署

undefined
undefined

Common Caching Scenarios

常见缓存场景

Scenario 1: Static Website
  • Long-term browser caching for all assets
  • CDN edge caching
  • Service worker for offline support
  • Immutable cache for versioned files
Scenario 2: SPA (Single Page App)
  • Service worker with app shell caching
  • API response caching (network-first)
  • Static asset caching (cache-first)
  • Stale-while-revalidate for data
Scenario 3: API Server
  • Redis for database query results
  • Response caching with appropriate headers
  • ETags for conditional requests
  • CDN for public endpoints
Scenario 4: E-commerce Site
  • Product images (long cache, CDN)
  • Product data (short cache, stale-while-revalidate)
  • User data (no cache, private)
  • Shopping cart (no cache, real-time)
场景1:静态网站
  • 所有资源长期浏览器缓存
  • CDN边缘缓存
  • Service worker实现离线支持
  • 版本化文件不可变缓存
场景2:SPA(单页应用)
  • Service worker + 应用外壳缓存
  • API响应缓存(网络优先)
  • 静态资源缓存(缓存优先)
  • 数据使用stale-while-revalidate
场景3:API服务器
  • Redis存储数据库查询结果
  • 响应缓存搭配合适的headers
  • ETags实现条件请求
  • 公共端点使用CDN
场景4:电商站点
  • 商品图片(长缓存、CDN)
  • 商品数据(短缓存、stale-while-revalidate)
  • 用户数据(无缓存、私有)
  • 购物车(无缓存、实时)

Expected Results

预期结果

Performance Improvements:
  • 40-80% faster repeat page loads
  • 50-90% reduction in API calls
  • 30-60% reduction in server load
  • Improved offline capabilities
Cache Hit Rates:
  • Static assets: 95%+ hit rate
  • API responses: 60-80% hit rate
  • Database queries: 70-90% hit rate
性能提升:
  • 重复页面加载速度提升40-80%
  • API调用减少50-90%
  • 服务器负载降低30-60%
  • 离线能力提升
缓存命中率:
  • 静态资源:95%+命中率
  • API响应:60-80%命中率
  • 数据库查询:70-90%命中率

Error Handling

错误处理

If caching introduces issues:
  • I'll identify the problematic cache layer
  • Provide specific debugging steps
  • Suggest cache invalidation methods
  • Offer alternative caching strategies
  • Ensure no stale data served to users
如果缓存引入问题:
  • 我会定位有问题的缓存层
  • 提供具体的调试步骤
  • 建议缓存失效方法
  • 提供替代缓存策略
  • 确保不会向用户提供过时数据

Important Notes

重要说明

I will NEVER:
  • Cache sensitive user data improperly
  • Add AI attribution to configuration files
  • Break existing cache invalidation
  • Implement caching without validation
  • Cache authenticated requests publicly
Best Practices:
  • Always validate cache invalidation works
  • Test offline functionality (service workers)
  • Monitor cache hit rates
  • Set appropriate TTL values
  • Document caching strategy
我绝不会:
  • 不当缓存敏感用户数据
  • 在配置文件中添加AI署名
  • 破坏现有缓存失效机制
  • 未经验证就实现缓存
  • 公开缓存认证请求
最佳实践:
  • 始终验证缓存失效正常工作
  • 测试离线功能(service workers)
  • 监控缓存命中率
  • 设置合适的TTL值
  • 记录缓存策略

Credits

鸣谢

Inspired by:
This skill helps you implement robust caching strategies that balance performance with data freshness.
灵感来源:
本技能帮助您实现兼顾性能与数据新鲜度的健壮缓存策略。