caching-strategy — скилл для Claude Code: кэш в Redis и CDN
Помогает агенту спроектировать кэширование в приложении: Redis, Memcached, CDN и инвалидация. Пригодится, когда запросы к базе тормозят отклик.
npx skills add aj-geddes/useful-ai-prompts --skill caching-strategy -a claude-codeЧто делает caching-strategy
Скилл описывает рабочие схемы кэша и разбирает, где они ломаются. Внутри — минимальный пример сервиса на ioredis с TTL по умолчанию 3600 секунд, повторными подключениями и обработкой ошибок, а также набор справочников в каталоге references/: реализация кэша на Node.js, декоратор кэша на Python, многоуровневый кэш, стратегии инвалидации и заголовки HTTP-кэширования.
Агенту заданы и правила гигиены: разумные TTL, прогрев критичных данных, паттерн cache-aside для чтения, мониторинг попаданий, аккуратное поведение при отказе кэша, пространства имён для ключей и защита от cache stampede. Отдельным списком идёт то, чего делать не стоит: кэшировать всё подряд, прятать за кэшем плохую схему базы, хранить чувствительные данные без шифрования, ставить слишком долгий TTL для быстро меняющихся данных.
Пример в скилле неполный — полные реализации лежат в справочниках, поэтому для работы понадобится сам Redis по адресу подключения, который вы передаёте в конструктор. Без запущенного Redis сервис из примера не поднимется.
Какие задачи решает
- снять нагрузку с базы частыми однотипными запросами
- ускорить ответы API за счёт кэша
- выбрать стратегию инвалидации без устаревших данных
- собрать многоуровневый кэш с CDN для статики
- защититься от cache stampede при массовом промахе
Примеры запросов агенту
- Настрой кэширование ответов API на Redis с TTL 600 секунд и ключами с префиксом по сервису
- Покажи, как инвалидировать кэш карточки товара после обновления в базе
- Собери многоуровневый кэш: локальный в памяти и общий в Redis
Как установить caching-strategy
1Через Skills CLI (Vercel)
npx skills add aj-geddes/useful-ai-prompts --skill caching-strategy -a claude-code2Вручную: положить файлы
~/.claude/skills/caching-strategy/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/caching-strategy/
1Через Skills CLI (Vercel)
npx skills add aj-geddes/useful-ai-prompts --skill caching-strategy -a codex2Вручную: положить файлы
.agents/skills/caching-strategy/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add aj-geddes/useful-ai-prompts --skill caching-strategy -a cursor2Вручную: положить файлы
.cursor/skills/caching-strategy/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install aj-geddes/useful-ai-prompts caching-strategy2Вручную: положить файлы
.github/skills/caching-strategy/SKILL.md1Через Skills CLI (Vercel)
npx skills add aj-geddes/useful-ai-prompts --skill caching-strategy -a gemini-cli2Командой платформы
gemini skills install https://github.com/aj-geddes/useful-ai-prompts --path skills/caching-strategyВручную: положить файлы
.devin/skills/caching-strategy/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Через Skills CLI (Vercel)
npx skills add aj-geddes/useful-ai-prompts --skill caching-strategy -a opencodeClaude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Вопросы о caching-strategy
Как установить caching-strategy в Claude Code?
Выполните npx skills add aj-geddes/useful-ai-prompts --skill caching-strategy -a claude-code. Скилл появится в ~/.claude/skills/caching-strategy/SKILL.md.
Что делает скилл caching-strategy?
Даёт агенту готовые схемы кэширования на Redis, Memcached и CDN вместе с паттернами инвалидации. Внутри есть справочники по реализации на Node.js и Python.
Что нужно, чтобы пример из скилла заработал?
Пример на ioredis подключается к Redis по переданному адресу. Нужен запущенный Redis и установленный пакет ioredis.
Исходный текст
SKILL.md · MIT
---
name: caching-strategy
description: >
Implement efficient caching strategies using Redis, Memcached, CDN, and cache
invalidation patterns. Use when optimizing application performance, reducing
database load, or improving response times.
---
# Caching Strategy
## Table of Contents
- [Overview](#overview)
- [When to Use](#when-to-use)
- [Quick Start](#quick-start)
- [Reference Guides](#reference-guides)
- [Best Practices](#best-practices)
## Overview
Implement effective caching strategies to improve application performance, reduce latency, and decrease load on backend systems.
## When to Use
- Reducing database query load
- Improving API response times
- Handling high traffic loads
- Caching expensive computations
- Storing session data
- CDN integration for static assets
- Implementing distributed caching
- Rate limiting and throttling
## Quick Start
Minimal working example:
```typescript
import Redis from "ioredis";
interface CacheOptions {
ttl?: number; // Time to live in seconds
prefix?: string;
}
class CacheService {
private redis: Redis;
private defaultTTL = 3600; // 1 hour
constructor(redisUrl: string) {
this.redis = new Redis(redisUrl, {
retryStrategy: (times) => {
const delay = Math.min(times * 50, 2000);
return delay;
},
maxRetriesPerRequest: 3,
});
this.redis.on("connect", () => {
console.log("Redis connected");
});
this.redis.on("error", (error) => {
// ... (see reference guides for full implementation)
```
## Reference Guides
Detailed implementations in the `references/` directory:
| Guide | Contents |
|---|---|
| [Redis Cache Implementation (Node.js)](references/redis-cache-implementation-nodejs.md) | Redis Cache Implementation (Node.js) |
| [Cache Decorator (Python)](references/cache-decorator-python.md) | Cache Decorator (Python) |
| [Multi-Level Cache](references/multi-level-cache.md) | Multi-Level Cache |
| [Cache Invalidation Strategies](references/cache-invalidation-strategies.md) | Cache Invalidation Strategies |
| [HTTP Caching Headers](references/http-caching-headers.md) | HTTP Caching Headers |
## Best Practices
### ✅ DO
- Set appropriate TTL values
- Implement cache warming for critical data
- Use cache-aside pattern for reads
- Monitor cache hit rates
- Implement graceful degradation on cache failure
- Use compression for large cached values
- Namespace cache keys properly
- Implement cache stampede prevention
- Use consistent hashing for distributed caching
- Monitor cache memory usage
### ❌ DON'T
- Cache everything indiscriminately
- Use caching as a fix for poor database design
- Store sensitive data without encryption
- Forget to handle cache misses
- Set TTL too long for frequently changing data
- Ignore cache invalidation strategies
- Cache without monitoring
- Store large objects without consideration
© aj-geddes · MIT · aj-geddes/useful-ai-prompts