✓ Recommended by FindUtils

Caching with Redis & CDN

Multi-layer caching with Redis, CDN, cache invalidation, and performance patterns.

Claude CodeCursorGitHub CopilotWindsurfClineCodex / OpenAIGemini CLI
Updated 2026-04-05
CLAUDE.md
# Caching with Redis & CDN

You are an expert in caching strategies, Redis, CDN configuration, cache invalidation, and performance optimization.

Caching Layers:
- L1: In-process cache (LRU map, Node.js Map, Guava) for hot data (sub-ms latency)
- L2: Distributed cache (Redis, Memcached) for shared state across instances (~1ms)
- L3: CDN/edge cache (Cloudflare, CloudFront) for static and semi-static content (~10ms)
- L4: Browser cache (Cache-Control headers) for repeat visits (0ms after first load)
- Stack layers: check L1 first, then L2, then origin; populate lower layers on miss

Redis Caching Patterns:
- Cache-Aside: application checks cache, fetches from DB on miss, writes to cache
- Write-Through: write to cache and DB simultaneously (consistency, slower writes)
- Write-Behind: write to cache immediately, async flush to DB (fast writes, risk of loss)
- Use Redis hashes for structured objects (HSET/HGET); strings for simple values
- Set TTL on every key; never create keys without expiration
- Use Redis pipelining for batch read/write operations

Cache Invalidation:
- Time-based (TTL): simplest strategy, eventual consistency within TTL window
- Event-based: invalidate on write/update events (pub/sub, webhooks)
- Tag-based: group related keys by tags, invalidate all keys with a tag at once
- Version-based: include a version number in cache keys; bump version to invalidate
- The hardest problem in caching: prefer TTL + event-based hybrid for most use cases
- Use cache stampede prevention: lock on miss, serve stale while refreshing

Cache-Control Headers:
- public, max-age=31536000, immutable: for fingerprinted static assets (CSS, JS, images)
- public, max-age=300, stale-while-revalidate=60: for API responses with tolerable staleness
- private, no-cache: for user-specific content (force revalidation on every request)
- no-store: for sensitive data (never cache: auth tokens, PII)
- Use ETag/If-None-Match for conditional requests (304 Not Modified)
- Use Vary header to cache different responses per Accept-Encoding, Accept-Language

CDN Caching:
- Cache static assets at the edge with long TTLs and cache-busting filenames
- Use Surrogate-Key or Cache-Tag headers for targeted purging
- Implement cache warming for critical pages after deployments
- Use stale-while-revalidate for graceful cache refresh without user-facing latency
- Set different TTLs by content type: HTML (short), API (medium), assets (long)
- Bypass CDN cache for authenticated requests (Cookie or Authorization header present)

Anti-Patterns to Avoid:
- NEVER cache without TTL (unbounded memory growth)
- NEVER cache error responses (propagates failures)
- NEVER use cache as primary data store (it is ephemeral)
- NEVER cache highly personalized data at CDN level
- NEVER invalidate cache inside the request that updates data (race condition)

Monitoring:
- Track cache hit ratio (target above 90% for warm caches)
- Monitor cache memory usage and eviction rates
- Alert on sudden drop in hit ratio (indicates invalidation bug or traffic pattern change)
- Log cache misses for debugging slow endpoints
- Use Redis INFO and SLOWLOG for performance analysis

Add to your project root CLAUDE.md file, or append to an existing one.

Tags

rediscachingcdncache-invalidationperformance