caching-strategies
Skill4 starsChanged 9 months agoMITView on GitHub
Implement effective caching at every layer: in-memory, Redis, CDN, and browser. Activate whenever the user asks about caching, performance optimization for repeated data access, Redis patterns, CDN configuration, cache invalidation, HTTP cache headers, memoization, or stale-while-revalidate strategies.
- Reads credentials
9 other projects use a version of this.
Adopted by
Most recently taken up by
- novatic-cu/nova-skillstheir own version, first seen Sep 20, 2026
- 2867203296/hermes-agenttheir own version, first seen Aug 19, 2026
- Bappoz/My-Claude-Skillstheir own version, first seen Jul 15, 2026
- vanara-agents/skillstheir own version, first seen Jul 14, 2026
- shinzoxD/knackboxtheir own version, first seen Jul 10, 2026
- KraitDev/skiLL.Mdtheir own version, first seen May 15, 2026
Other versions9 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 9
- wshaddix/dotnet-skills★ 79same name
- vanara-agents/skills★ 9same name
- KraitDev/skiLL.Md★ 6same name
- ffsshhttiikk/opencode-agents-skills★ 2same name
- Bappoz/My-Claude-Skills★ 1same name
- michaelsvanbeek/personal-agent-skills★ 1same name
- novatic-cu/nova-skills★ 1same name
- 2867203296/hermes-agent★ 0same name
- shinzoxD/knackbox★ 0same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository78 other files it gives its agents.
- AGENTS.mdAGENTS.md
- rules/agents.mdAGENTS.md
- .github/copilot-instructions.mdCopilot instructions
- .cursor/rules/claude-initial-setup.mdcCursor rule
- parallel-task-executionSkill
- subagent-patternsSkill
- task-coordinationSkill
- agent-communicationSkill
- context-managementSkill
- multi-agent-orchestrationSkill
- deploy-strategiesSkill
- github-actions-guideSkill
- pipeline-patternsSkill
- anthropic-sdk-guideSkill
- prompt-engineeringSkill
- tool-use-patternsSkill
- automated-review-setupSkill
- pr-standardsSkill
- review-checklistSkill
- file-organizationSkill
- immutability-patternsSkill
- naming-conventionsSkill
- branching-strategySkill
- commit-conventionsSkill
- pr-workflowSkill
- migration-patternsSkill
- query-optimizationSkill
- schema-design-guideSkill
- error-tracingSkill
- log-analysisSkill
- systematic-debuggingSkill
- django-admin-customizationSkill
- django-orm-masterySkill
- drf-api-patternsSkill
- docker-compose-guideSkill
- dockerfile-best-practicesSkill
- multi-stage-buildsSkill
- express-error-handlingSkill
- middleware-patternsSkill
- rest-api-nodeSkill
- async-fastapiSkill
- dependency-injection-fastapiSkill
- pydantic-validationSkill
- concurrency-patterns-goSkill
- error-handling-goSkill
- idiomatic-goSkill
- automation-triggersSkill
- hook-recipesSkill
- pre-post-hooksSkill
- junit-testingSkill
- maven-gradle-guideSkill
- spring-boot-patternsSkill
- mcp-resource-patternsSkill
- mcp-server-creationSkill
- mcp-tool-designSkill
- context-optimizationSkill
- knowledge-persistenceSkill
- memory-patternsSkill
- lazy-loading-patternsSkill
- profiling-guideSkill
- The first 60 shown.
The file
Files
Caching Strategies
Cache data at the right layer to reduce latency, database load, and compute costs. The two hardest problems in computer science are cache invalidation and naming things. This guide focuses on getting invalidation right.
When to Use
- API endpoints that serve the same data to many users
- Database queries that are expensive and don't change frequently
- Static assets and CDN configuration
- Computed values that are expensive to recalculate
- Reducing latency for frequently accessed data
Core Patterns
In-Memory Memoization
Cache computed values within a single process. Simplest form of caching.
// Simple memoization with Map
function memoize<Args extends unknown[], Result>(
fn: (...args: Args) => Result,
keyFn: (...args: Args) => string = (...args) => JSON.stringify(args),
): (...args: Args) => Result {
const cache = new Map<string, Result>();
return (...args: Args): Result => {
const key = keyFn(...args);
if (cache.has(key)) {
return cache.get(key)!;
}
const result = fn(...args);
cache.set(key, result);
return result;
};
}
// For bounded caches, use an LRU eviction policy (e.g., lru-cache npm package)
// to prevent unbounded memory growth in long-running processes.
import { LRUCache } from 'lru-cache';
const userCache = new LRUCache<string, User>({ max: 1000 });Redis Caching Patterns
Distributed caching for multi-instance deployments.
import Redis from 'ioredis';
const redis = new Redis(process.env.REDIS_URL);
// Cache-aside pattern (most common)
async function getUserById(id: string): Promise<User> {
const cacheKey = `user:${id}`;
// 1. Check cache
const cached = await redis.get(cacheKey);
if (cached) {
return JSON.parse(cached);
}
// 2. Cache miss - fetch from database
const user = await db.users.findById(id);
if (!user) {
throw new Error('User not found');
}
// 3. Populate cache with TTL
await redis.set(cacheKey, JSON.stringify(user), 'EX', 3600); // 1 hour
return user;
}
// Write-through: update cache when data changes
async function updateUser(id: string, data: UpdateUserDto): Promise<User> {
const user = await db.users.update(id, data);
const cacheKey = `user:${id}`;
await redis.set(cacheKey, JSON.stringify(user), 'EX', 3600);
return user;
}
// Cache invalidation on delete
async function deleteUser(id: string): Promise<void> {
await db.users.delete(id);
await redis.del(`user:${id}`);
// Also invalidate related caches
await redis.del(`user:${id}:posts`);
await redis.del(`user:${id}:settings`);
}
// Pattern-based invalidation
async function invalidateUserCaches(userId: string): Promise<void> {
const keys = await redis.keys(`user:${userId}:*`);
if (keys.length > 0) {
await redis.del(...keys);
}
}HTTP Cache Headers
Control browser and CDN caching with proper headers.
// Express middleware for cache control
// Static assets: cache aggressively (use content hashing in filenames)
app.use('/assets', express.static('dist/assets', {
maxAge: '1y', // Cache for 1 year
immutable: true, // Never revalidate (filename changes on content change)
}));
// API responses: vary by use case
app.get('/api/products', (req, res) => {
res.set({
'Cache-Control': 'public, max-age=300, stale-while-revalidate=60',
'Vary': 'Accept-Encoding',
});
res.json(products);
});
// User-specific data: private caching only
app.get('/api/profile', authenticate, (req, res) => {
res.set({
'Cache-Control': 'private, max-age=60, must-revalidate',
});
res.json(req.user);
});
// Never cache sensitive data
app.get('/api/auth/session', (req, res) => {
res.set({
'Cache-Control': 'no-store',
});
res.json(sessionData);
});Cache-Control Directives Cheat Sheet:
public - CDN and browser can cache
private - Only browser can cache (user-specific data)
max-age=N - Fresh for N seconds
s-maxage=N - CDN-specific max-age (overrides max-age for CDN)
no-cache - Must revalidate with server before using cached copy
no-store - Never cache (sensitive data)
must-revalidate - After max-age expires, must revalidate (no stale serving)
immutable - Content will never change (use with content-hashed filenames)
stale-while-revalidate=N - Serve stale for N seconds while fetching fresh copyStale-While-Revalidate Pattern
Serve stale data immediately while refreshing in the background. The HTTP header
Cache-Control: stale-while-revalidate=60 does this at the CDN/browser level.
For server-side SWR, use libraries like swr (React) or implement a cache wrapper
that returns stale data and triggers a background refresh when the TTL expires.
### CDN Caching (Cloudflare / Vercel / AWS CloudFront)
Configure CDN edge caching for global performance.
```typescript
// Next.js ISR (Incremental Static Regeneration)
export async function getStaticProps() {
const posts = await fetchPosts();
return {
props: { posts },
revalidate: 60, // Regenerate page every 60 seconds
};
}
// Vercel Edge Config / Cloudflare Cache API
app.get('/api/popular-products', (req, res) => {
res.set({
'Cache-Control': 'public, s-maxage=300, stale-while-revalidate=600',
'CDN-Cache-Control': 'max-age=300', // CDN-specific
'Surrogate-Control': 'max-age=3600', // Varnish/Fastly
});
res.json(products);
});Anti-Patterns
- Caching without a TTL (data grows forever, never expires)
- Using
redis.keys('*')in production (blocks Redis, O(N) scan) - Caching user-specific data with
publicCache-Control - Invalidating cache on every write when reads vastly outnumber writes
- Not varying cache by relevant headers (Accept-Language, Authorization)
- Caching error responses (propagates failures even after recovery)
- Using unbounded in-memory caches (memory leak in long-running processes)
- Setting very long cache TTLs without a cache-busting mechanism
Quick Reference
| Layer | Tool | Best For |
| In-process | Map / LRU Cache | Computed values, hot path data |
| Distributed | Redis / Memcached | Shared state across instances |
| CDN edge | Cloudflare / CloudFront | Static assets, public API responses |
| Browser | Cache-Control headers | Repeat visits, static assets |
| Database | Query result cache | Expensive queries, materialized views |
| Pattern | When to Use |
| Cache-aside | Read-heavy, tolerance for occasional stale data |
| Write-through | Need cache always in sync with database |
| Write-behind | High write volume, eventual consistency OK |
| SWR | User-facing reads where freshness < speed |
| TTL-based | Simple expiration, no explicit invalidation needed |
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

