/implement-caching-strategy
Design and implement caching solutions
$ npx -y skills add qdhenry/Claude-Command-Suite --agent claude-codeHow it fires
How this command gets triggered: by you, by Claude, or both.
- Fires itselfClaude auto-loads it when your prompt matches the work.
- You can call itInvoke it directly when you want it.
- Slash command
/implement-caching-strategy
Context preview
What this command does when you run it.
Design and implement caching solutions
Command definition
implement-caching-strategy.mdImplement Caching Strategy
Design and implement caching solutions
Instructions
1. **Caching Strategy Analysis**
- Analyze application architecture and identify caching opportunities
- Assess current performance bottlenecks and data access patterns
- Define caching requirements (TTL, invalidation, consistency)
- Plan multi-layer caching architecture (browser, CDN, application, database)
- Evaluate caching technologies and storage solutions
2. **Browser and Client-Side Caching**
- Configure HTTP caching headers and cache policies:
**HTTP Cache Headers:**
// Express.js middleware
app.use((req, res, next) => {
// Static assets with long-term caching
if (req.url.match(/\.(js|css|png|jpg|jpeg|gif|ico|svg)$/)) {
res.setHeader('Cache-Control', 'public, max-age=31536000'); // 1 year
res.setHeader('ETag', generateETag(req.url));
}
// API responses with short-term caching
if (req.url.startsWith('/api/')) {
res.setHeader('Cache-Control', 'public, max-age=300'); // 5 minutes
}
next();
});**Service Worker Caching:**
// sw.js - Service Worker
const CACHE_NAME = 'app-cache-v1';
const urlsToCache = [
'/',
'/static/js/bundle.js',
'/static/css/main.css',
];
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME)
.then((cache) => cache.addAll(urlsToCache))
);
});
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request)
.then((response) => {
// Return cached version or fetch from network
return response || fetch(event.request);
})
);
});3. **Application-Level Caching**
- Implement in-memory and distributed caching:
**Node.js Memory Cache:**
const NodeCache = require('node-cache');
const cache = new NodeCache({ stdTTL: 600 }); // 10 minutes default TTL
class CacheService {
static get(key) {
return cache.get(key);
}
static set(key, value, ttl = 600) {
return cache.set(key, value, ttl);
}
static del(key) {
return cache.del(key);
}
static flush() {
return cache.flushAll();
}
// Cache wrapper for expensive operations
static async memoize(key, fn, ttl = 600) {
let result = this.get(key);
if (result === undefined) {
result = await fn();
this.set(key, result, ttl);
}
return result;
}
}
// Usage example
app.get('/api/users/:id', async (req, res) => {
const userId = req.params.id;
const cacheKey = `user:${userId}`;
const user = await CacheService.memoize(
cacheKey,
() => getUserFromDatabase(userId),
900 // 15 minutes
);
res.json(user);
});**Redis Distributed Cache:**
const redis = require('redis');
const client = redis.createClient({
host: process.env.REDIS_HOST || 'localhost',
port: process.env.REDIS_PORT || 6379,
});
class RedisCache {
static async get(key) {
try {
const value = await client.get(key);
return value ? JSON.parse(value) : null;
} catch (error) {
console.error('Cache get error:', error);
return null;
}
}
static async set(key, value, ttl = 600) {
try {
const serialized = JSON.stringify(value);
if (ttl) {
await client.setex(key, ttl, serialized);
} else {
await client.set(key, serialized);
}
return true;
} catch (error) {
console.error('Cache set error:', error);
return false;
}
}
static async del(key) {
try {
await client.del(key);
return true;
} catch (error) {
console.error('Cache delete error:', error);
return false;
}
}
// Pattern-based cache invalidation
static async invalidatePattern(pattern) {
try {
const keys = await client.keys(pattern);
if (keys.length > 0) {
await client.del(keys);
}
return true;
} catch (error) {
console.error('Cache invalidation error:', error);
return false;
}
}
}4. **Database Query Caching**
- Implement database-level caching strategies:
**PostgreSQL Query Caching:**
const { Pool } = require('pg');
const pool = new Pool();
class DatabaseCache {
static async cachedQuery(sql, params = [], ttl = 300) {
const cacheKey = `query:${Buffer.from(sql + JSON.stringify(params)).toString('base64')}`;
// Try cache first
let result = await RedisCache.get(cacheKey);
if (result) {
return result;
}
// Execute query and cache result
const dbResult = await pool.query(sql, params);
result = dbResult.rows;
await RedisCache.set(cacheKey, result, ttl);
return result;
}
// Invalidate cache by table
static async invalidateTable(tableName) {
await RedisCache.invalidatePattern(`query:*${tableName}*`);
}
}
// Usage
app.get('/api/products', async (req, res) => {
const products = await DatabaseCache.cachedQuery(
'SELECT * FROM products WHERE active = true ORDER BY created_at DESC',
[],
600 // 10 minutes
);
res.json(products);
});**MongoDB Caching with Mongoose:**
const mongoose = require('mongoose');
// Mongoose query caching plugin
function cachePlugin(schema) {
schema.add({
cacheKey: { type: String, index: true },
cachedAt: { type: Date },
});
schema.methods.cache = function(ttl = 300) {
this.cacheKey = this.constructor.genRead more
Implement Caching Strategy
Design and implement caching solutions
Instructions
1. **Caching Strategy Analysis**
- Analyze application architecture and identify caching opportunities
- Assess current performance bottlenecks and data access patterns
- Define caching requirements (TTL, invalidation, consistency)
- Plan multi-layer caching architecture (browser, CDN, application, database)
- Evaluate caching technologies and storage solutions
2. **Browser and Client-Side Caching**
- Configure HTTP caching headers and cache policies:
**HTTP Cache Headers:**
// Express.js middleware
app.use((req, res, next) => {
// Static assets with long-term caching
if (req.url.match(/\.(js|css|png|jpg|jpeg|gif|ico|svg)$/)) {
res.setHeader('Cache-Control', 'public, max-age=31536000'); // 1 year
res.setHeader('ETag', generateETag(req.url));
}
// API responses with short-term caching
if (req.url.startsWith('/api/')) {
res.setHeader('Cache-Control', 'public, max-age=300'); // 5 minutes
}
next();
});**Service Worker Caching:**
// sw.js - Service Worker
const CACHE_NAME = 'app-cache-v1';
const urlsToCache = [
'/',
'/static/js/bundle.js',
'/static/css/main.css',
];
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME)
.then((cache) => cache.addAll(urlsToCache))
);
});
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request)
.then((response) => {
// Return cached version or fetch from network
return response || fetch(event.request);
})
);
});3. **Application-Level Caching**
- Implement in-memory and distributed caching:
**Node.js Memory Cache:**
const NodeCache = require('node-cache');
const cache = new NodeCache({ stdTTL: 600 }); // 10 minutes default TTL
class CacheService {
static get(key) {
return cache.get(key);
}
static set(key, value, ttl = 600) {
return cache.set(key, value, ttl);
}
static del(key) {
return cache.del(key);
}
static flush() {
return cache.flushAll();
}
// Cache wrapper for expensive operations
static async memoize(key, fn, ttl = 600) {
let result = this.get(key);
if (result === undefined) {
result = await fn();
this.set(key, result, ttl);
}
return result;
}
}
// Usage example
app.get('/api/users/:id', async (req, res) => {
const userId = req.params.id;
const cacheKey = `user:${userId}`;
const user = await CacheService.memoize(
cacheKey,
() => getUserFromDatabase(userId),
900 // 15 minutes
);
res.json(user);
});**Redis Distributed Cache:**
const redis = require('redis');
const client = redis.createClient({
host: process.env.REDIS_HOST || 'localhost',
port: process.env.REDIS_PORT || 6379,
});
class RedisCache {
static async get(key) {
try {
const value = await client.get(key);
return value ? JSON.parse(value) : null;
} catch (error) {
console.error('Cache get error:', error);
return null;
}
}
static async set(key, value, ttl = 600) {
try {
const serialized = JSON.stringify(value);
if (ttl) {
await client.setex(key, ttl, serialized);
} else {
await client.set(key, serialized);
}
return true;
} catch (error) {
console.error('Cache set error:', error);
return false;
}
}
static async del(key) {
try {
await client.del(key);
return true;
} catch (error) {
console.error('Cache delete error:', error);
return false;
}
}
// Pattern-based cache invalidation
static async invalidatePattern(pattern) {
try {
const keys = await client.keys(pattern);
if (keys.length > 0) {
await client.del(keys);
}
return true;
} catch (error) {
console.error('Cache invalidation error:', error);
return false;
}
}
}4. **Database Query Caching**
- Implement database-level caching strategies:
**PostgreSQL Query Caching:**
const { Pool } = require('pg');
const pool = new Pool();
class DatabaseCache {
static async cachedQuery(sql, params = [], ttl = 300) {
const cacheKey = `query:${Buffer.from(sql + JSON.stringify(params)).toString('base64')}`;
// Try cache first
let result = await RedisCache.get(cacheKey);
if (result) {
return result;
}
// Execute query and cache result
const dbResult = await pool.query(sql, params);
result = dbResult.rows;
await RedisCache.set(cacheKey, result, ttl);
return result;
}
// Invalidate cache by table
static async invalidateTable(tableName) {
await RedisCache.invalidatePattern(`query:*${tableName}*`);
}
}
// Usage
app.get('/api/products', async (req, res) => {
const products = await DatabaseCache.cachedQuery(
'SELECT * FROM products WHERE active = true ORDER BY created_at DESC',
[],
600 // 10 minutes
);
res.json(products);
});**MongoDB Caching with Mongoose:**
const mongoose = require('mongoose');
// Mongoose query caching plugin
function cachePlugin(schema) {
schema.add({
cacheKey: { type: String, index: true },
cachedAt: { type: Date },
});
schema.methods.cache = function(ttl = 300) {
this.cacheKey = this.constructor.genA comprehensive development toolkit designed following Anthropic's Claude Code Best Practices for AI-assisted software development.
Repo: qdhenry/Claude-Command-Suite
Other commands on claude-command-suite.
- /boundary-bbcr-fallback
Execute automatic BBCR (Collapse-Rebirth Correction) when knowledge boundaries are exceeded or reasoning fails.
Open command - /boundary-detect
Analyze semantic position relative to knowledge boundaries to prevent hallucination and identify uncertainty zones.
Open command - /boundary-heatmap
Generate a visual heatmap of knowledge boundaries showing safe zones, risk areas, and semantic coverage.
Open command - /boundary-risk-assess
Evaluate the current risk level and provide detailed analysis of potential hallucination or reasoning failure.
Open command - /boundary-safe-bridge
Find and construct semantic bridges to safely navigate from current position to target concept without crossing dangerous boundaries.
Open command - /optimize-prompt
Takes an input prompt and returns ONLY a token-optimized version that preserves meaning while minimizing token count. Based on LLM tokenization principles: common words tokenize more efficiently, unusual words break into more tokens, and conciseness reduces cost.
Open command

