Skip to content
Development
Command

/implement-caching-strategy

Design and implement caching solutions

From plugin
claude-command-suite
1.3k199 skills89 agents199 commands
Install
$ npx -y skills add qdhenry/Claude-Command-Suite --agent claude-code

How 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.md

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.gen
Read more
Ships withclaude-command-suite

A comprehensive development toolkit designed following Anthropic's Claude Code Best Practices for AI-assisted software development.

Get the whole plugin