caching-strategies
Skill6 starsChanged 6 months agoMITView on GitHub
When improving read performance and reducing database load.
11 other projects use a version of this.
Adopted by
Most recently taken up by
- reddygopalkrishna/developer-agent-skillstheir own version, first seen Nov 8, 2026
- cookieMonsterDev/agents-skillstheir own version, first seen Nov 1, 2026
- ThibautBaissac/rails_ai_agentstheir own version, first seen Oct 8, 2026
- 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
Used with
Projects with it also use observability and api-design.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
OpenAISkillobservability
Vercel Observability expert guidance — Drains (logs, traces, speed insights, web analytics), Web Analytics, Speed Insights, runtime logs, custom events, OpenTelemetry integration, and monitoring dashboards. Use when instrumenting, debugging, or optimizing application performance and user experience on Vercel.
Also in 3 projects that use this
MicrosoftSkillapi-design
Guide for designing and documenting RESTful APIs. Use when asked to design an API, create endpoints, or document an API.
Also in 3 projects that use this
Other versions11 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 11
- ThibautBaissac/rails_ai_agents★ 665same name
- reddygopalkrishna/developer-agent-skills★ 8same name
- cookieMonsterDev/agents-skills★ 7same name
- ffsshhttiikk/opencode-agents-skills★ 2same name
- kimtth/agent-skill-100-lines-or-less★ 2same name
- Bappoz/My-Claude-Skills★ 1same name
- harrissohail6/claude-code-config★ 1same name
- michaelsvanbeek/personal-agent-skills★ 1same name
- novatic-cu/nova-skills★ 1same name
- 2867203296/hermes-agent★ 0same name
1 more not listed
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 repository13 other files it gives its agents.
- event-driven-designSkill
- logging-observability-standardsSkill
- api-design-restSkill
- database-query-optimizationSkill
- error-handling-architectureSkill
- code-review-guidelinesSkill
- ci-cd-pipeline-architectureSkill
- debugging-strategiesSkill
- git-workflow-branchingSkill
- dom-security-hardeningSkill
- react-component-designSkill
- state-management-patternsSkill
- accessibility-ui-designSkill
The file
We split this skill into the rules it gives an agent
12 rules. 0 are common, 12 are distinctive, and 0 are very specific to this project.
0
Common
Most of the 9 edited versions we read keep these.
12
Distinctive
This author's own choices. Worth a look.
0
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 39
Before optimizing database queries (optimize first, cache second)
- Distinctive: line 41
When consistency is more important than performance
- Distinctive: line 47
Read/write patterns of the data
- Distinctive: line 63
MUST treat cache as ephemeral (can disappear at any time)
- Distinctive: line 64
MUST NOT cache highly personalized or sensitive data (PII) in shared caches
- Distinctive: line 65
MUST ALWAYS implement fallback to primary data store on cache failure
- Distinctive: line 66
MUST set TTL values (no infinite cache)
- Distinctive: line 67
MUST invalidate cache on mutations (UPDATE, DELETE operations)
- Distinctive: line 68
MUST use separate caches for different data types/sensitivity levels
- Distinctive: line 69
MUST NOT use cache as source of truth
- Distinctive: line 77
Cache Stampede: All requests hit cache miss simultaneously, causing DB spike
- Distinctive: line 82
No fallback logic when cache is unavailable
“Common” is measured: kept by at least 6 in 10 of the 9 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Caching Strategies
Purpose
Databases are slow; caches are fast. This skill teaches teams to strategically cache frequently accessed data in fast storage (Redis, Memcached) to intercept requests before they hit the database, dramatically reducing latency and database load. Caching is NOT a substitute for proper database optimization.
When to use
- System is experiencing high latency on read-heavy API endpoints
- Database CPU/Memory usage is constantly peaking due to repeated queries
- Designing a new system expecting massive read throughput
- Content rarely changes but reads happen constantly
When NOT to use
- Before optimizing database queries (optimize first, cache second)
- For data that changes frequently or is highly personalized
- When consistency is more important than performance
- As a quick fix for poor application architecture
Inputs required
- Slow query logs or endpoint metrics
- Cache infrastructure (Redis, Memcached)
- Read/write patterns of the data
- Acceptable staleness window (TTL)
Workflow
- Identify Bottlenecks: Profile APIs to find read-heavy, slow-changing data (user profiles, static config, product catalogs)
- Measure Access Patterns: How often is data read vs. written? How large? How old can it be?
- Select Strategy:
- Cache-Aside: App checks cache; on miss, fetches DB, writes cache
- Write-Through: App writes to cache and DB simultaneously
- Write-Behind: App writes to cache only; batch updates to DB later (use cautiously)
- Set Eviction Policy: Assign Time-To-Live (TTL) values based on business tolerance for stale data
- Handle Invalidation: Implement cache invalidation logic on mutations (UPDATE/DELETE)
- Prevent Stampedes: Implement caching locks or staggered TTLs to prevent multiple clients fetching from DB simultaneously when a key expires
- Add Monitoring: Track cache hit rates, eviction rates, and staleness
Rules
- MUST treat cache as ephemeral (can disappear at any time)
- MUST NOT cache highly personalized or sensitive data (PII) in shared caches
- MUST ALWAYS implement fallback to primary data store on cache failure
- MUST set TTL values (no infinite cache)
- MUST invalidate cache on mutations (UPDATE, DELETE operations)
- MUST use separate caches for different data types/sensitivity levels
- MUST NOT use cache as source of truth
Anti-patterns
- Infinite TTL: Storing keys without expiration (leads to unbounded memory, stale data)
- Premature Caching: Adding Redis before the database is properly indexed
- No Fallback: Cache failure crashes the application
- Over-Caching: Caching everything including rarely-used data (wastes cache memory)
- Forgetting Invalidation: Updating database but not cache (stale data served indefinitely)
- Cache Stampede: All requests hit cache miss simultaneously, causing DB spike
- Storing Mutable Objects: Storing references to objects that change, returning stale mutations
Failure conditions
- Cache becomes source of truth (data lost if cache clears)
- No fallback logic when cache is unavailable
- Cache miss causes cascading database failures
- Stale data leads to data corruption
- Cache stampede (all requests simultaneously fetch from DB)
Validation checklist
- Cache is treated as optimization layer, not data store
- Fallback to primary data store on cache miss works
- TTL is set (no infinite cache)
- Cache invalidation triggered on data mutations
- Cache hit rate > 80% for target queries
- No cache stampede when keys expire simultaneously
- Sensitive data not cached (or encrypted if cached)
- Cache memory usage monitored (no unbounded growth)
- Stale data handling defined (acceptable staleness window)
- Monitoring dashboards show hit rate and eviction rate
Output format
- Cache-Aside wrapper: Function that checks cache, handles miss, populates cache
- Invalidation triggers: ON UPDATE/DELETE, clear cache key
- Configuration: TTL values, eviction policy, cache key naming convention
- Monitoring: Hit rates, eviction rates, staleness metrics
- Documentation: Which data is cached, staleness tolerance, fallback behavior
Security considerations
- Sensitive data MUST NOT be cached or only in encrypted form
- Cache keys MUST be predictable (not guessable)
- Access control MUST be enforced (not all users can access all cache keys)
- Sensitive data MUST be masked in monitoring logs
- Cache MUST be protected from unauthorized access
Agent execution notes
- Agent MAY: Add cache checks, implement invalidation, set TTL, add monitoring
- Agent MUST NEVER: Use cache as source of truth, forget fallback logic, set infinite TTL
- Agent MUST ASK: Before caching sensitive data, before major caching strategy change
- Agent MUST VALIDATE: Fallback logic works, TTL configured, invalidation on mutations
Example
❌ Anti-pattern (No fallback, infinite TTL, no invalidation):
// WRONG: No fallback if cache fails
const getUser = async (userId) => {
return redis.get(`user:${userId}`); // Fails if Redis is down
};
// WRONG: Infinite TTL
redis.set(`config:app-settings`, settings); // Never expires = stale data forever
// WRONG: No invalidation on update
async function updateUser(userId, data) {
await db.users.update(userId, data);
// Forgot to clear cache - stale data served
}
// WRONG: Cache stampede - all requests hit DB when key expires
const getExpensiveData = async () => {
const cached = await redis.get('expensive-data');
if (!cached) {
// All concurrent requests hit this - DB spike
const data = await slowQuery();
await redis.set('expensive-data', data, { ex: 3600 });
return data;
}
return cached;
};✅ Correct pattern (Fallback, TTL, invalidation, stampede prevention):
// CORRECT: Fallback to database on cache miss or failure
const getUser = async (userId) => {
try {
const cached = await redis.get(`user:${userId}`);
if (cached) return JSON.parse(cached);
} catch (e) {
logger.warn('Cache miss, falling back to DB', e);
}
// Fallback to DB
const user = await db.users.findById(userId);
// Repopulate cache
try {
await redis.setex(`user:${userId}`, 3600, JSON.stringify(user)); // 1 hour TTL
} catch (e) {
logger.warn('Failed to cache, but returning DB data', e);
}
return user;
};
// CORRECT: TTL on all cache entries
redis.setex('config:app-settings', 86400, JSON.stringify(settings)); // 24 hour TTL
// CORRECT: Invalidate cache on mutations
async function updateUser(userId, data) {
await db.users.update(userId, data);
await redis.del(`user:${userId}`); // Clear specific key
}
// CORRECT: Prevent cache stampede with locks
const stampedeLock = new Mutex();
const getExpensiveData = async () => {
const cached = await redis.get('expensive-data');
if (cached) return JSON.parse(cached);
// Use lock to ensure only one request fetches from DB
return stampedeLock.runExclusive(async () => {
// Double-check if another request already populated cache
const cached = await redis.get('expensive-data');
if (cached) return JSON.parse(cached);
const data = await slowQuery();
await redis.setex('expensive-data', 3600, JSON.stringify(data));
return data;
});
};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.

