Agent skill

caching-cdn-strategy-planner

Designs multi-layer caching strategy with edge CDN, server-side caching, cache invalidation, and CDN configuration. Use for "caching strategy", "CDN setup", "cache invalidation", or "performance optimization".

Stars 23
Forks 2

Install this agent skill to your Project

npx add-skill https://github.com/patricio0312rev/skills/tree/main/performance/caching-cdn-strategy-planner

SKILL.md

Caching & CDN Strategy Planner

Design effective caching at all layers.

Caching Layers

Client → CDN (Edge) → Server Cache → Database

CDN Configuration (CloudFront)

typescript
const distribution = {
  Origins: [
    {
      DomainName: "api.example.com",
      CustomHeaders: [
        {
          HeaderName: "X-CDN-Secret",
          HeaderValue: process.env.CDN_SECRET,
        },
      ],
    },
  ],
  DefaultCacheBehavior: {
    ViewerProtocolPolicy: "redirect-to-https",
    AllowedMethods: ["GET", "HEAD", "OPTIONS"],
    CachedMethods: ["GET", "HEAD"],
    Compress: true,
    DefaultTTL: 86400, // 1 day
    MaxTTL: 31536000, // 1 year
    MinTTL: 0,
    ForwardedValues: {
      QueryString: true,
      Cookies: { Forward: "none" },
      Headers: ["Accept", "Accept-Encoding"],
    },
  },
  CacheBehaviors: [
    {
      PathPattern: "/api/static/*",
      DefaultTTL: 31536000, // 1 year - never changes
    },
    {
      PathPattern: "/api/dynamic/*",
      DefaultTTL: 300, // 5 min - changes frequently
    },
  ],
};

Server-side Caching (Redis)

typescript
import Redis from 'ioredis';

const redis = new Redis(process.env.REDIS_URL);

async function getCachedOrFetch<T>(
  key: string,
  fetcher: () => Promise<T>,
  ttl: number = 3600
): Promise<T> {
  // Try cache
  const cached = await redis.get(key);
  if (cached) {
    return JSON.parse(cached);
  }

  // Fetch and cache
  const data = await fetcher();
  await redis.setex(key, ttl, JSON.stringify(data));

  return data;
}

// Usage
app.get('/api/user/:id', async (req, res) => {
  const user = await getCachedOrFetch(
    \`user:\${req.params.id}\`,
    () => prisma.user.findUnique({ where: { id: req.params.id } }),
    3600
  );

  res.json(user);
});

Cache Invalidation

typescript
// Invalidate on update
app.put('/api/user/:id', async (req, res) => {
  const user = await prisma.user.update({
    where: { id: req.params.id },
    data: req.body,
  });

  // Invalidate cache
  await redis.del(\`user:\${req.params.id}\`);

  // Invalidate CDN
  await cloudfront.createInvalidation({
    DistributionId: DISTRIBUTION_ID,
    InvalidationBatch: {
      Paths: { Items: [\`/api/user/\${req.params.id}\`] },
      CallerReference: Date.now().toString(),
    },
  });

  res.json(user);
});

Cache Headers

typescript
app.get("/api/products", (req, res) => {
  res.set({
    "Cache-Control": "public, max-age=3600", // Browser + CDN: 1h
    ETag: generateETag(products),
    "Last-Modified": new Date(products.updatedAt).toUTCString(),
  });

  res.json(products);
});

app.get("/api/user/profile", (req, res) => {
  res.set({
    "Cache-Control": "private, no-cache", // No caching (sensitive)
  });

  res.json(profile);
});

Output Checklist

  • CDN configured
  • Server cache implemented
  • Invalidation strategy
  • Cache headers set
  • Monitoring configured ENDFILE

Expand your agent's capabilities with these related and highly-rated skills.

patricio0312rev/skills

rate-limiting-abuse-protection

Implements rate limiting and abuse prevention with per-route policies, IP/user-based limits, sliding windows, safe error responses, and observability. Use when adding "rate limiting", "API protection", "abuse prevention", or "DDoS protection".

23 2
Explore
patricio0312rev/skills

rbac-permissions-builder

Implements role-based access control with permission matrix, route guards, policy functions, and UI permission hints. Provides middleware/guards, helper utilities, test suggestions, and permission checking patterns. Use when building "RBAC", "permissions", "access control", or "authorization".

23 2
Explore
patricio0312rev/skills

websocket-realtime-builder

Implements real-time features using WebSockets with Socket.io, rooms, authentication, and reconnection handling. Use when users request "real-time updates", "WebSocket", "Socket.io", "live chat", or "push notifications".

23 2
Explore
patricio0312rev/skills

webhook-receiver-hardener

Secures webhook receivers with signature verification, retry handling, deduplication, idempotency keys, and error responses. Provides verification code, dedupe storage strategy, runbook for incidents. Use when implementing "webhooks", "webhook security", "event receivers", or "third-party integrations".

23 2
Explore
patricio0312rev/skills

auth-module-builder

Implements secure authentication patterns including login/registration, session management, JWT tokens, password hashing, cookie settings, and CSRF protection. Provides auth routes, middleware, security configurations, and threat model documentation. Use when building "authentication", "login system", "JWT auth", or "session management".

23 2
Explore
patricio0312rev/skills

rest-to-graphql-migrator

Migrates REST APIs to GraphQL incrementally with schema stitching, REST datasources, and gradual endpoint migration. Use when users request "migrate to GraphQL", "REST to GraphQL", "GraphQL wrapper", or "API modernization".

23 2
Explore

Didn't find tool you were looking for?

Be as detailed as possible for better results