Cache Strategy & Invalidation Expert
Design and implement caching architectures using Redis, application-level caching, and CDN layers with reliable invalidation strategies.
Activation Triggers
Activate on: "caching", "Redis cache", "cache invalidation", "cache-aside", "write-through", "TTL", "stale-while-revalidate", "cache stampede", "cache warming"
NOT for: CDN/proxy configuration → api-gateway-reverse-proxy-expert | Database query tuning → data-warehouse-optimizer | Connection pooling → database-connection-pool-manager
Quick Start
- Identify cache candidates — read-heavy, expensive to compute, tolerant of staleness
- Choose pattern — cache-aside (most common), write-through (consistency), write-behind (performance)
- Set TTL strategy — short TTL for volatile data (60s), long TTL + event invalidation for stable data
- Prevent stampede — use probabilistic early refresh or mutex lock on cache miss
- Monitor hit rate — target >90% hit rate; below 70% means your cache strategy is wrong
Core Capabilities
| Domain |
Technologies |
| In-Memory |
Redis 7.4+, Valkey, DragonflyDB, KeyDB |
| Application |
Node LRU cache, Cacheable, unstorage |
| HTTP/CDN |
Cache-Control, stale-while-revalidate, Surrogate-Key |
| Multi-Layer |
L1 (in-process) → L2 (Redis) → L3 (CDN) |
| Invalidation |
Event-driven purge, TTL, tag-based (Surrogate-Key) |
Architecture Patterns
Cache-Aside with Stampede Prevention
import { Redis } from 'ioredis';
const redis = new Redis();
const LOCK_TTL = 5; // seconds
async function cacheAside<T>(
key: string,
ttl: number,
fetcher: () => Promise<T>
): Promise<T> {
// Try cache first
const cached = await redis.get(key);
if (cached) return JSON.parse(cached);
// Acquire lock to prevent stampede
const lockKey = `lock:${key}`;
const acquired = await redis.set(lockKey, '1', 'EX', LOCK_TTL, 'NX');
if (!acquired) {
// Another process is fetching — wait and retry
await new Promise(r => setTimeout(r, 100));
return cacheAside(key, ttl, fetcher);
}
try {
const data = await fetcher();
await redis.set(key, JSON.stringify(data), 'EX', ttl);
return data;
} finally {
await redis.del(lockKey);
}
}
Multi-Layer Cache Architecture
Request → L1: In-Process (LRU, 100ms TTL, ~1000 items)
│ miss
↓
L2: Redis (5-60min TTL, shared across instances)
│ miss
↓
L3: CDN (Cache-Control headers, edge-cached)
│ miss
↓
Origin (database/API)
Invalidation flows BACKWARD:
Database change → Purge L2 (Redis DEL) → L1 expires via short TTL
→ Purge L3 (Surrogate-Key purge / CDN API)
Event-Driven Invalidation
// On data change, publish invalidation event
async function updateUser(userId: string, data: UserUpdate) {
await db.users.update(userId, data);
// Invalidate all cache layers
await redis.del(`user:${userId}`);
await redis.del(`user:${userId}:profile`);
// Publish for other instances' L1 caches
await redis.publish('cache:invalidate', JSON.stringify({
pattern: `user:${userId}:*`,
timestamp: Date.now(),
}));
// CDN purge by surrogate key
await cdn.purgeTag(`user-${userId}`);
}
Anti-Patterns
- Cache everything — caching write-heavy, rarely-read data wastes memory and creates invalidation headaches
- No TTL — every cache entry must expire; relying solely on explicit invalidation will eventually leave stale data
- Cache-then-forget — monitor hit rate, eviction rate, and memory usage; an unmonitored cache silently degrades
- Serializing full objects — cache only what you need; storing entire ORM models bloats memory and couples cache to schema
- Invalidation by pattern scan —
KEYS user:* blocks Redis; use sets to track related keys or hash structures
Quality Checklist
1---2license: Apache-2.03name: cache-strategy-invalidation-expert4description: "Redis caching patterns, cache-aside, write-through, TTL strategies, and invalidation. Activate on: caching, Redis, cache invalidation, cache-aside, write-through, TTL, CDN cache, stale-while-revalidate. NOT for: CDN/reverse proxy setup (use api-gateway-reverse-proxy-expert), database query optimization (use data-warehouse-optimizer)."5allowed-tools: Read,Write,Edit,Bash(npm:*,npx:*,redis-cli:*)6category: Backend & Infrastructure7tags:8 - caching9 - redis10 - invalidation11 - performance12 - ttl13pairs-with:14 - skill: api-rate-limiting-throttling-expert15 reason: Redis powers both caching and rate limiting16 - skill: websocket-realtime-expert17 reason: Cache invalidation can trigger real-time updates18 - skill: multi-tenant-architecture-expert19 reason: Cache keys must be tenant-scoped in multi-tenant systems20metadata:21 source: https://skillmd.com/skills/curiositech/cache-strategy-invalidation-expert22---2324# Cache Strategy & Invalidation Expert2526Design and implement caching architectures using Redis, application-level caching, and CDN layers with reliable invalidation strategies.2728## Activation Triggers2930**Activate on:** "caching", "Redis cache", "cache invalidation", "cache-aside", "write-through", "TTL", "stale-while-revalidate", "cache stampede", "cache warming"3132**NOT for:** CDN/proxy configuration → `api-gateway-reverse-proxy-expert` | Database query tuning → `data-warehouse-optimizer` | Connection pooling → `database-connection-pool-manager`3334## Quick Start35361. **Identify cache candidates** — read-heavy, expensive to compute, tolerant of staleness372. **Choose pattern** — cache-aside (most common), write-through (consistency), write-behind (performance)383. **Set TTL strategy** — short TTL for volatile data (60s), long TTL + event invalidation for stable data394. **Prevent stampede** — use probabilistic early refresh or mutex lock on cache miss405. **Monitor hit rate** — target >90% hit rate; below 70% means your cache strategy is wrong4142## Core Capabilities4344| Domain | Technologies |45|--------|-------------|46| **In-Memory** | Redis 7.4+, Valkey, DragonflyDB, KeyDB |47| **Application** | Node LRU cache, Cacheable, unstorage |48| **HTTP/CDN** | Cache-Control, stale-while-revalidate, Surrogate-Key |49| **Multi-Layer** | L1 (in-process) → L2 (Redis) → L3 (CDN) |50| **Invalidation** | Event-driven purge, TTL, tag-based (Surrogate-Key) |5152## Architecture Patterns5354### Cache-Aside with Stampede Prevention5556```typescript57import { Redis } from 'ioredis';5859const redis = new Redis();60const LOCK_TTL = 5; // seconds6162async function cacheAside<T>(63 key: string,64 ttl: number,65 fetcher: () => Promise<T>66): Promise<T> {67 // Try cache first68 const cached = await redis.get(key);69 if (cached) return JSON.parse(cached);7071 // Acquire lock to prevent stampede72 const lockKey = `lock:${key}`;73 const acquired = await redis.set(lockKey, '1', 'EX', LOCK_TTL, 'NX');7475 if (!acquired) {76 // Another process is fetching — wait and retry77 await new Promise(r => setTimeout(r, 100));78 return cacheAside(key, ttl, fetcher);79 }8081 try {82 const data = await fetcher();83 await redis.set(key, JSON.stringify(data), 'EX', ttl);84 return data;85 } finally {86 await redis.del(lockKey);87 }88}89```9091### Multi-Layer Cache Architecture9293```94Request → L1: In-Process (LRU, 100ms TTL, ~1000 items)95 │ miss96 ↓97 L2: Redis (5-60min TTL, shared across instances)98 │ miss99 ↓100 L3: CDN (Cache-Control headers, edge-cached)101 │ miss102 ↓103 Origin (database/API)104105Invalidation flows BACKWARD:106 Database change → Purge L2 (Redis DEL) → L1 expires via short TTL107 → Purge L3 (Surrogate-Key purge / CDN API)108```109110### Event-Driven Invalidation111112```typescript113// On data change, publish invalidation event114async function updateUser(userId: string, data: UserUpdate) {115 await db.users.update(userId, data);116117 // Invalidate all cache layers118 await redis.del(`user:${userId}`);119 await redis.del(`user:${userId}:profile`);120121 // Publish for other instances' L1 caches122 await redis.publish('cache:invalidate', JSON.stringify({123 pattern: `user:${userId}:*`,124 timestamp: Date.now(),125 }));126127 // CDN purge by surrogate key128 await cdn.purgeTag(`user-${userId}`);129}130```131132## Anti-Patterns1331341. **Cache everything** — caching write-heavy, rarely-read data wastes memory and creates invalidation headaches1352. **No TTL** — every cache entry must expire; relying solely on explicit invalidation will eventually leave stale data1363. **Cache-then-forget** — monitor hit rate, eviction rate, and memory usage; an unmonitored cache silently degrades1374. **Serializing full objects** — cache only what you need; storing entire ORM models bloats memory and couples cache to schema1385. **Invalidation by pattern scan** — `KEYS user:*` blocks Redis; use sets to track related keys or hash structures139140## Quality Checklist141142- [ ] Cache-aside pattern with stampede prevention (mutex or probabilistic refresh)143- [ ] TTL set on every key (no eternal cache entries)144- [ ] Hit rate monitored and >90% for primary caches145- [ ] Invalidation strategy defined: TTL-based, event-driven, or hybrid146- [ ] Cache keys include all relevant context (tenant, locale, version)147- [ ] Redis memory policy set (allkeys-lru for cache workloads)148- [ ] No `KEYS *` or `SCAN` in hot paths (use sets for key tracking)149- [ ] Multi-layer cache with clear TTL hierarchy (L1 < L2 < L3)150- [ ] Graceful degradation: app works (slower) if cache is down151- [ ] Cache warming strategy for cold starts after deployments