caching-strategist
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".
What this skill does
# 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
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.