caching-strategist — скилл для Claude Code
Скилл caching-strategist для Claude Code раскладывает кеширование по слоям и выдаёт готовые ключи, TTL, правила сброса и защиту от stampede. Превращает задачу «добавь кеш» в рабочий код.
MIT 278 установок ★ 64 обновлён 2026-01-12
npx skills add patricio0312rev/skills --skill caching-strategist -a claude-codeЧто делает caching-strategist
Скилл разбивает кеш на четыре слоя и назначает каждому работу. CDN отдаёт статику и публичные страницы. Redis держит ответы API и сессии. Результаты запросов к базе получают свой слой, последний живёт в браузере. Ключи строятся иерархией с версией в префиксе: подняли одну константу — и старые записи больше не мешают.
TTL заданы именованными константами, от десяти секунд для быстро меняющихся данных до недели для редких обновлений. Дальше идут паттерны: чтение через cache-aside, сброс записи и связанных списков при записи, инвалидация по тегам через множества Redis, прогрев популярных записей по cron и блокировка SET NX EX, чтобы истёкший ключ не обрушил на базу пачку одинаковых запросов. В конце — чеклист корректности.
Весь код написан под клиент redis: get, setex, del, sadd, smembers. С другим хранилищем примеры придётся переписать, а пользу останется нести схема ключей и чеклист. Отдельный его пункт требует не держать в кеше чувствительные данные без шифрования.
Какие задачи решает
- выбрать TTL для ответов API, сессий и статики
- сложить ключи кеша в иерархию с версией
- сбрасывать запись и связанные списки при обновлении
- удержать базу от шквала одинаковых запросов после истечения популярного ключа
- прогреть кеш популярных записей по расписанию
Примеры запросов агенту
- Продумай стратегию кеширования для API на Redis: имена ключей, TTL и что сбрасывать при обновлении пользователя.
- После истечения TTL база получает пачку одинаковых запросов. Добавь защиту от stampede через блокировку.
- Настрой прогрев кеша для самых читаемых постов по cron и проверь всё по чеклисту корректности.
Как установить caching-strategist
1Через Skills CLI (Vercel)
npx skills add patricio0312rev/skills --skill caching-strategist -a claude-code2Вручную: положить файлы
~/.claude/skills/caching-strategist/SKILL.mdПапка скилла целиком; для одного проекта — .claude/skills/caching-strategist/
1Через Skills CLI (Vercel)
npx skills add patricio0312rev/skills --skill caching-strategist -a codex2Вручную: положить файлы
.agents/skills/caching-strategist/SKILL.mdДля всех проектов — ~/.agents/skills/
1Через Skills CLI (Vercel)
npx skills add patricio0312rev/skills --skill caching-strategist -a cursor2Вручную: положить файлы
.cursor/skills/caching-strategist/SKILL.mdCursor читает и .agents/skills/, и .claude/skills/
1GitHub CLI
gh skill install patricio0312rev/skills backend/caching-strategist/SKILL.md2Вручную: положить файлы
.github/skills/caching-strategist/SKILL.md1Через Skills CLI (Vercel)
npx skills add patricio0312rev/skills --skill caching-strategist -a gemini-cli2Командой платформы
gemini skills install https://github.com/patricio0312rev/skills --path backend/caching-strategistВручную: положить файлы
.devin/skills/caching-strategist/SKILL.mdСтарый путь .windsurf/skills/ тоже читается
Через Skills CLI (Vercel)
npx skills add patricio0312rev/skills --skill caching-strategist -a opencodeClaude.ai
Упакуйте папку в zip и загрузите в Settings → Capabilities → Skills
По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов
Вопросы о caching-strategist
Как установить caching-strategist в Claude Code?
Выполните npx skills add patricio0312rev/skills --skill caching-strategist -a claude-code. Файл скилла появится по пути ~/.claude/skills/caching-strategist/SKILL.md.
Что делает caching-strategist?
Описывает слои кеша, схему ключей с версией, значения TTL, триггеры инвалидации и защиту от одновременных промахов. Всё это с примерами кода на TypeScript и чеклистом корректности.
Нужен ли Redis, чтобы пользоваться скиллом?
Примеры обращаются к клиенту redis: get, setex, del, sadd. С другим хранилищем останутся схема ключей и чеклист, а вызовы в коде надо будет заменить.
Исходный текст
SKILL.md · MIT
---
name: caching-strategist
description: Defines caching strategies with cache keys, TTL values, invalidation triggers, consistency patterns, and correctness checklist. Provides code examples for Redis, CDN, and application-level caching. Use when implementing "caching", "performance optimization", "cache strategy", or "Redis caching".
---
# Caching Strategist
Design effective caching strategies for performance and consistency.
## Cache Layers
**CDN**: Static assets, public pages (TTL: days/weeks)
**Application Cache** (Redis): API responses, sessions (TTL: minutes/hours)
**Database Cache**: Query results (TTL: seconds/minutes)
**Client Cache**: Browser/app local cache
## Cache Key Strategy
```typescript
// Hierarchical key structure
const CACHE_KEYS = {
user: (id: string) => `user:${id}`,
userPosts: (userId: string, page: number) => `user:${userId}:posts:${page}`,
post: (id: string) => `post:${id}`,
postComments: (postId: string) => `post:${postId}:comments`,
};
// Include version in keys for easy invalidation
const CACHE_VERSION = "v1";
const key = `${CACHE_VERSION}:${CACHE_KEYS.user(userId)}`;
```
## TTL Strategy
```typescript
const TTL = {
// Frequently changing
REALTIME: 10, // 10 seconds
SHORT: 60, // 1 minute
// Moderate updates
MEDIUM: 300, // 5 minutes
STANDARD: 3600, // 1 hour
// Rarely changing
LONG: 86400, // 1 day
VERY_LONG: 604800, // 1 week
};
// Usage
await redis.setex(key, TTL.MEDIUM, JSON.stringify(data));
```
## Cache-Aside Pattern
```typescript
export const getCachedUser = async (userId: string): Promise<User> => {
const key = CACHE_KEYS.user(userId);
// Try cache first
const cached = await redis.get(key);
if (cached) {
return JSON.parse(cached);
}
// Cache miss - fetch from DB
const user = await db.users.findById(userId);
// Store in cache
await redis.setex(key, TTL.STANDARD, JSON.stringify(user));
return user;
};
```
## Cache Invalidation
```typescript
// Invalidate on update
export const updateUser = async (userId: string, data: UpdateUserDto) => {
const user = await db.users.update(userId, data);
// Invalidate cache
await redis.del(CACHE_KEYS.user(userId));
// Invalidate related caches
await redis.del(CACHE_KEYS.userPosts(userId, "*"));
return user;
};
// Tag-based invalidation
const addCacheTags = (key: string, tags: string[]) => {
tags.forEach((tag) => {
redis.sadd(`cache_tag:${tag}`, key);
});
};
const invalidateByTag = async (tag: string) => {
const keys = await redis.smembers(`cache_tag:${tag}`);
if (keys.length) {
await redis.del(...keys);
await redis.del(`cache_tag:${tag}`);
}
};
```
## Cache Warming
```typescript
// Pre-populate cache for common queries
export const warmCache = async () => {
const popularPosts = await db.posts.findPopular(100);
for (const post of popularPosts) {
const key = CACHE_KEYS.post(post.id);
await redis.setex(key, TTL.LONG, JSON.stringify(post));
}
};
// Schedule warming
cron.schedule("0 */6 * * *", warmCache); // Every 6 hours
```
## Cache Stampede Prevention
```typescript
// Use locks to prevent multiple simultaneous fetches
export const getCachedWithLock = async (
key: string,
fetchFn: () => Promise<any>
) => {
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 {
// Fetch and cache
const data = await fetchFn();
await redis.setex(key, TTL.STANDARD, JSON.stringify(data));
return data;
} finally {
await redis.del(lockKey);
}
} else {
// Wait for other request to finish
await new Promise((resolve) => setTimeout(resolve, 100));
return getCachedWithLock(key, fetchFn);
}
};
```
## Cache Correctness Checklist
```markdown
- [ ] Cache keys are unique and predictable
- [ ] TTL is appropriate for data freshness
- [ ] Invalidation happens on all updates
- [ ] Related caches invalidated together
- [ ] Cache stampede prevention in place
- [ ] Fallback to DB if cache fails
- [ ] Monitoring cache hit rate
- [ ] Cache size doesn't grow unbounded
- [ ] Sensitive data not cached or encrypted
- [ ] Cache warming for critical paths
```
## Best Practices
- Cache immutable data aggressively
- Short TTLs for frequently changing data
- Invalidate on write, not on read
- Monitor hit rates and adjust
- Use tags for bulk invalidation
- Prevent cache stampedes
- Graceful degradation if cache down
## Output Checklist
- [ ] Cache key naming strategy
- [ ] TTL values per data type
- [ ] Invalidation triggers documented
- [ ] Cache-aside implementation
- [ ] Stampede prevention
- [ ] Cache warming strategy
- [ ] Monitoring/metrics setup
- [ ] Correctness checklist completed
© patricio0312rev · MIT · patricio0312rev/skills