CA

caching-strategies

Configures dual-layer caching (CDN + KV) to optimize site performance. Use for setting Cache-Control headers and managing stale-while-revalidate patterns.

Install

mkdir -p .claude/skills/caching-strategies-zhongyuhangcn && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/13688" && unzip -o skill.zip -d .claude/skills/caching-strategies-zhongyuhangcn && rm skill.zip

Installs to .claude/skills/caching-strategies-zhongyuhangcn

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Dual-layer caching strategies for the Flare Stack Blog. Use when implementing CDN cache headers, KV caching with versioned invalidation, or debugging cache-related issues.
171 chars✓ has a “when” trigger
Advanced

Key capabilities

  • Control browser and CDN caching via HTTP headers
  • Set cache headers in TanStack Start routes
  • Use predefined cache control constants
  • Implement versioned KV caching for data invalidation
  • Purge CDN cache using Cloudflare API

How it works

The skill implements a dual-layer caching architecture using CDN HTTP headers for browser and edge caching, and Cloudflare KV for persistent, versioned data caching.

Inputs & outputs

You give it
A request to configure caching for a route or data
You get back
HTTP response headers for CDN/browser caching or KV cache operations

When to use caching-strategies

  • Setting CDN cache headers for routes
  • Configuring browser stale-while-revalidate
  • Debugging cache-related performance issues
  • Managing static asset cache duration

About this skill

Caching Strategies

The project employs a dual-layer caching architecture: CDN (HTTP headers) and KV (Cloudflare KV storage).

CDN Layer (HTTP Headers)

Control browser and CDN caching via response headers. Set headers through page routes or Hono routes.

Setting Cache Headers in Page Routes

For TanStack Start routes, set headers in the headers function:

// routes/sitemap[.]xml.ts
export const Route = createFileRoute("/sitemap.xml")({
  headers: () => ({
    "Cache-Control": "public, max-age=3600, s-maxage=3600",
  }),
});

Cache Control Constants (lib/constants.ts)

Predefined constants for common scenarios. Each constant is an object with two headers: Cache-Control (browser) and CDN-Cache-Control (CDN edge). This dual-header pattern lets you control browser and CDN caching independently.

ConstantCache-Control (Browser)CDN-Cache-Control (CDN)Use Case
CACHE_CONTROL.immutablepublic, max-age=31536000, immutablepublic, max-age=31536000, immutableStatic assets
CACHE_CONTROL.swrpublic, max-age=0, must-revalidatepublic, s-maxage=1, stale-while-revalidate=604800General pages
CACHE_CONTROL.publicpublic, max-age=0, must-revalidatepublic, s-maxage=31536000Public pages
CACHE_CONTROL.forbiddenpublic, max-age=0, must-revalidatepublic, s-maxage=3600403 pages
CACHE_CONTROL.privateprivate, no-store, no-cache, must-revalidateprivate, no-storeAdmin pages
CACHE_CONTROL.notFoundpublic, max-age=0, must-revalidatepublic, s-maxage=10404 pages
CACHE_CONTROL.serverErrorpublic, max-age=0, must-revalidatepublic, s-maxage=10500 pages

Hono Route Caching

Hono API routes use middleware for cache headers:

// lib/hono/middlewares.ts
app.use("/api/*", cacheMiddleware());

Invalidation

Purge CDN cache using the Cloudflare API:

await purgePostCDNCache(context.env, post.slug);

KV Layer (Cloudflare KV)

Used for persistent caching of longer-lived data (post lists, details).

Cache Key Definition

The CacheKey type supports both strings and readonly arrays (tuples), allowing for type-safe key construction using as const.

// features/cache/types.ts
export type CacheKey =
  | string
  | readonly (string | number | boolean | null | undefined)[];

Cache Key Factory Pattern

Instead of hardcoding key arrays in services, define Cache Key Factories in the feature's schema.ts. This provides a single source of truth and ensures types match the requirements of the cache key.

1. Define Factory in schema.ts

// features/posts/posts.schema.ts
export const POSTS_CACHE_KEYS = {
  /** Post detail cache key (includes version) */
  detail: (version: string, slug: string) => [version, "post", slug] as const,
} as const;

2. Use in Service Layer

Pass the tuple directly to CacheService functions. No spread ([...]) is needed since CacheKey supports readonly arrays.

const version = await CacheService.getVersion(context, "posts:detail");
return await CacheService.get(
  context,
  POSTS_CACHE_KEYS.detail(version, data.slug),
  PostSchema,
  fetcher,
);

Versioned Key Invalidation Strategy

This pattern enables efficient bulk invalidation without iterating through keys:

1. Get Current Version

const version = await CacheService.getVersion(context, "posts:detail");
// Returns "v1", "v2", etc.

2. Bump Version to Invalidate

When data changes, increment the version number:

await CacheService.bumpVersion(context, "posts:detail");
// All old keys with the previous version become unreachable

3. Direct Key Deletion

For single-record invalidation, delete the specific key using the factory:

const version = await CacheService.getVersion(context, "posts:detail");
await CacheService.deleteKey(context, POSTS_CACHE_KEYS.detail(version, slug));

Complete Example

// posts.service.ts
import { POSTS_CACHE_KEYS } from "./posts.schema";

export async function updatePost(
  context: DbContext & { executionCtx: ExecutionContext },
  data: UpdatePostInput,
) {
  // 1. Update in database
  const post = await PostRepo.updatePost(context.db, data);

  // 2. Invalidate KV cache
  await CacheService.bumpVersion(context, "posts:list");
  const version = await CacheService.getVersion(context, "posts:detail");
  await CacheService.deleteKey(context, POSTS_CACHE_KEYS.detail(version, post.slug));

  // 3. Purge CDN cache
  await purgePostCDNCache(context.env, post.slug);

  return post;
}

Cache Namespace Conventions

NamespaceData TypeInvalidation Trigger
posts:listPost listingsPost create/update/delete
posts:detailIndividual postsPost update/delete
tags:listTag listingsTag create/update/delete
comments:listComment listingsComment create/approve/delete

When to Use Each Layer

ScenarioCDNKV
Public API responses✅ SWR✅ Version-keyed
Admin API responses❌ PrivateOptional
Static assets✅ Immutable
User-specific data❌ PrivateDepends

Debugging Cache Issues

  1. Stale data after update?

    • Check if bumpVersion() was called
    • Verify CDN purge completed
    • Check cache key construction
  2. Cache misses?

    • Verify version string consistency
    • Check TTL settings
    • Inspect key serialization
  3. Memory issues?

    • Review cached data size
    • Consider selective field caching

When not to use it

  • When caching user-specific data with public CDN cache
  • When using immutable caching for frequently changing data
  • When expecting KV cache to handle static assets

Limitations

  • Requires `bumpVersion()` to be called for KV cache invalidation
  • Requires CDN purge for CDN cache invalidation
  • KV cache keys must be type-safe using Cache Key Factories

How it compares

This dual-layer approach provides granular control over caching at both the CDN and data storage levels, enabling efficient invalidation and independent cache control for different content types.

Compared to similar skills

caching-strategies side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
caching-strategies (this skill)05moReviewAdvanced
workflow42moReviewIntermediate
bullmq-specialist256moNo flagsIntermediate
azure-monitor-opentelemetry-ts13moReviewIntermediate

Try saying

Example prompts that trigger this skill in your AI assistant.

You might also like

workflow

vercel

Creates durable, resumable workflows using Vercel's Workflow DevKit. Use when building workflows that need to survive restarts, pause for external events, retry on failure, or coordinate multi-step operations over time. Triggers on mentions of "workflow", "durable functions", "resumable", "workflow devkit", or step-based orchestration.

431

bullmq-specialist

davila7

BullMQ expert for Redis-backed job queues, background processing, and reliable async execution in Node.js/TypeScript applications. Use when: bullmq, bull queue, redis queue, background job, job queue.

2595

azure-monitor-opentelemetry-ts

microsoft

Instrument applications with Azure Monitor and OpenTelemetry for JavaScript (@azure/monitor-opentelemetry). Use when adding distributed tracing, metrics, and logs to Node.js applications with Application Insights.

11

idmp

ha0z1

Use when you need to deduplicate concurrent or repeated async calls, prevent duplicate API requests, cache async function results, add automatic retry with exponential backoff, memoize heavy computation wrapped in Promise, replace SWR/Provider for request sharing, invalidate cache with flush, or per

00

perf

microsoft

Speed and memory performance rules for Rust crates, webui-framework, and webui-router.

00

nextjs-developer

zenobi-us

Expert Next.js developer mastering Next.js 14+ with App Router and full-stack features. Specializes in server components, server actions, performance optimization, and production deployment with focus on building fast, SEO-friendly applications.

328531

Search skills

Search the agent skills registry