cache-strategy
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.
What this skill does
# 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:
```typescript
// 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:
```typescript
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:
```typescript
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:
```typescript
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.
Related in Design
contribute
IncludedLocal-only OSS contribution command center. Auto-refreshes the user's in-flight PR and issue state on invoke so conversations start with full context — no need to brief Claude on what's in flight. Helps the user find issues to contribute to on GitHub, builds per-repo dossiers of what each upstream expects (CLA, DCO, branch convention, AI policy, draft-first, review bots, issue templates), runs deterministic gates before any external action so AI-assisted contributions don't reach maintainers as slop. State is markdown-only: candidate files at ~/.contribute-system/candidates/, repo dossiers at ~/.contribute-system/research/, append-only event log at ~/.contribute-system/log.jsonl. No database, no cloud calls. Use when the user asks about their PRs / issues / contributions, wants to find new work to take on, claim an issue, build/refresh a repo's dossier, or draft a Design Issue or PR. Trigger with "/contribute", "what's my PR status", "find a contribution", "claim issue X", "draft a Design Issue for Y", "refresh dossier for Z".
architectural-analysis
IncludedUser-triggered deep architectural analysis of a codebase or scoped subtree across eight modes — information architecture, data flow, integration points, UI surfaces, interaction patterns, data model, control flow, and failure modes. This skill should be used when the user asks to "diagram this codebase," "map the architecture," "show the data flow," "give me an ERD," "trace control flow," "find the integration points," "verify the layout pattern," "audit the UX architecture," or any similar request whose primary deliverable is mermaid diagrams plus cited reports under docs/architecture/. Dispatches haiku/sonnet sub-agents in parallel for per-mode exploration, then verifies every citation mechanically before any node lands in a diagram. Not for one-off prose explanations of code (use code-explanation) or for high-level system design from scratch (use system-design).
mcp
IncludedModel Context Protocol (MCP) server development and tool management. Languages: Python, TypeScript. Capabilities: build MCP servers, integrate external APIs, discover/execute MCP tools, manage multi-server configs, design agent-centric tools. Actions: create, build, integrate, discover, execute, configure MCP servers/tools. Keywords: MCP, Model Context Protocol, MCP server, MCP tool, stdio transport, SSE transport, tool discovery, resource provider, prompt template, external API integration, Gemini CLI MCP, Claude MCP, agent tools, tool execution, server config. Use when: building MCP servers, integrating external APIs as MCP tools, discovering available MCP tools, executing MCP capabilities, configuring multi-server setups, designing tools for AI agents.
react-native-skia
IncludedDesign, build, debug, and optimise high-polish animated graphics in React Native or Expo using @shopify/react-native-skia, Reanimated, and Gesture Handler. Use when the user wants canvas-driven UI, shaders, paths, rich text, image filters, sprite fields, Skottie, video frames, snapshots, web CanvasKit setup, or performance tuning for custom motion-heavy elements such as loaders, hero art, cards, charts, progress indicators, particle systems, or gesture-driven surfaces. Also use when the user asks for fluid, glow, glass, blob, parallax, 60fps/120fps, or GPU-friendly animated effects in React Native, even if they do not explicitly say "Skia". Do not use for ordinary form/layout work with standard views.
plaid
IncludedProduct Led AI Development — guides founders from idea to launched product. Six capabilities: Idea (discover a product idea), Validate (pressure-test the idea against fatal flaws, problem reality, competition, and 2-week MVP feasibility), Plan (vision intake + document generation), Design (translate image references into a design.md spec), Launch (go-to-market strategy), and Build (roadmap execution). Use when someone says "PLAID", "plaid idea", "help me find an idea", "product idea", "idea from my business", "idea from my expertise", "plaid validate", "validate my idea", "pressure-test", "is this idea good", "find fatal flaws", "validate the problem", "plan a product", "define my vision", "generate a PRD", "product strategy", "plaid design", "design from image", "translate image to design", "create design.md", "extract design tokens", "plaid launch", "go-to-market", "launch plan", "GTM strategy", "launch playbook", "plaid build", "build the app", "start building", or "execute the roadmap".
nextjs-framer-motion-animations
IncludedAdds production-safe Motion for React or Framer Motion animations to Next.js apps, including reveal, hover and tap micro-interactions, whileInView, stagger, AnimatePresence, layout and layoutId transitions, reorder, scroll-linked UI, and lightweight route-content transitions. Use when the user asks to add, refactor, or debug Motion or Framer Motion in App Router or Pages Router codebases, especially around server/client boundaries, reduced motion, LazyMotion, bundle size, hydration, or route transitions. Avoid for GSAP-style timelines, WebGL or 3D scenes, heavy scroll storytelling, or CSS-only effects unless Motion is explicitly requested.