Caching logo

Caching

CommunityPopular
zebbern
caching

Caching strategies — invalidation, TTL guidelines, cache keys, cache layers, and when not to cache. Use when implementing or reviewing caching logic.

Overview

Publisherzebbern
Repositoryclaude-code-guide
Skill namecaching
Stars
4.6K
Forks
464
Bundled files
Instructions only
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by zebbern on GitHub. Read the source before you install it.

Installation

Install the Caching AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/zebbern/claude-code-guide.git /tmp/claude-code-guide
mkdir -p .claude/skills
cp -r /tmp/claude-code-guide/skills/caching .claude/skills/caching
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Caching in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Caching on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Caching is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

WHEN_TO_USE

  • When implementing a cache layer (in-memory, Redis, CDN) for an API or service.
  • When choosing TTL values or invalidation strategies for cached data.
  • When designing cache key schemas to avoid collisions or stale-data bugs.
  • When reviewing code that reads from or writes to any cache.
  • When debugging stale data, cache stampedes, or inconsistent responses.
  • When configuring TanStack Query staleTime/gcTime for client-side caching.

INVALIDATION

  • [P0-MUST] Define an invalidation strategy for every cache. Stale data is worse than no cache.
  • [P0-MUST] Invalidate caches when the underlying data changes — do not rely solely on TTL expiry.
  • [P1-SHOULD] Prefer event-driven invalidation (on write/update/delete) over time-based expiry alone.
  • [P1-SHOULD] Use cache versioning (include a version key) when data schemas change.

TTL_GUIDELINES

  • [P1-SHOULD] Set TTLs based on data volatility: static config (hours/days), user profiles (minutes), real-time data (seconds or no cache).
  • [P1-SHOULD] Use stale-while-revalidate: serve stale data immediately while refreshing in the background.
  • [P2-MAY] Use shorter TTLs in development and longer TTLs in production.

CACHE_KEYS

  • [P0-MUST] Include all query parameters that affect the result in the cache key.
  • [P1-SHOULD] Use a consistent key format: <entity>:<id>:<variant> (e.g., user:123:profile, products:list:page=2).
  • [P1-SHOULD] Namespace keys by service or module to prevent collisions.
  • [P2-MAY] Hash long or complex keys to keep storage efficient.

CACHE_LAYERS

  • [P1-SHOULD] Use the appropriate cache layer for the use case:
LayerBest ForTTL Range
In-memory (Map, LRU)Hot data, single-instance appsSeconds to minutes
Redis / MemcachedShared cache across instances, sessionsMinutes to hours
CDN / EdgeStatic assets, public API responsesHours to days
HTTP cache headersBrowser caching, API responsesVaries by resource
  • [P1-SHOULD] Layer caches: check memory → Redis → origin. Write-through on miss.

WHEN_NOT_TO_CACHE

  • [P0-MUST] Do not cache user-specific sensitive data (auth tokens, payment info) in shared caches.
  • [P1-SHOULD] Do not cache rapidly changing data where staleness causes incorrect behavior (inventory counts, real-time pricing).
  • [P1-SHOULD] Do not cache error responses — use short TTL or skip caching on failure.
  • [P2-MAY] Avoid caching when the computation is cheap and the data set is small.

CODE_EXAMPLES

In-memory LRU cache with TTL

ts
const cache = new Map<string, { value: unknown; expires: number }>();
const MAX_SIZE = 500;

export function getOrSet<T>(key: string, ttlMs: number, compute: () => T): T {
  const entry = cache.get(key);
  if (entry && entry.expires > Date.now()) return entry.value as T;

  const value = compute();
  if (cache.size >= MAX_SIZE) {
    // Evict oldest entry (first inserted)
    const oldest = cache.keys().next().value!;
    cache.delete(oldest);
  }
  cache.set(key, { value, expires: Date.now() + ttlMs });
  return value;
}

Redis stale-while-revalidate with ioredis

ts
import Redis from "ioredis";
const redis = new Redis(process.env.REDIS_URL);

export async function swr<T>(
  key: string,
  freshSec: number,
  staleSec: number,
  fetcher: () => Promise<T>,
): Promise<T> {
  const raw = await redis.get(key);
  if (raw) {
    const { value, createdAt } = JSON.parse(raw) as { value: T; createdAt: number };
    const ageMs = Date.now() - createdAt;
    if (ageMs < freshSec * 1000) return value; // Fresh — return immediately
    if (ageMs < staleSec * 1000) {
      // Stale — return cached, refresh in background
      fetcher().then((v) =>
        redis.set(key, JSON.stringify({ value: v, createdAt: Date.now() }), "EX", staleSec),
      );
      return value;
    }
  }
  const value = await fetcher();
  await redis.set(key, JSON.stringify({ value, createdAt: Date.now() }), "EX", staleSec);
  return value;
}

HTTP cache headers in Express/Hono

ts
// Immutable assets (hashed filenames)
app.use("/assets", (_, res, next) => {
  res.setHeader("Cache-Control", "public, max-age=31536000, immutable");
  next();
});

// API responses — short cache with revalidation
app.get("/api/products", (_, res) => {
  res.setHeader("Cache-Control", "public, max-age=60, stale-while-revalidate=300");
  res.json(products);
});

TanStack Query cache configuration

tsx
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 5 * 60 * 1000, // Data fresh for 5 minutes
      gcTime: 30 * 60 * 1000,   // Garbage-collect after 30 minutes
      retry: 2,
      refetchOnWindowFocus: false,
    },
  },
});

// Usage in a component
const { data } = useQuery({
  queryKey: ["products", { page, category }], // Cache key includes params
  queryFn: () => fetchProducts({ page, category }),
});

ANTI_PATTERNS

  • Cache-and-forget — Caching data with no invalidation strategy. Data goes stale permanently.

    • Instead: define explicit invalidation (event-driven on write, or bounded TTL) for every cache key.
  • Uniform TTL — Using the same TTL (e.g., 1 hour) for all data regardless of volatility.

    • Instead: match TTL to data change frequency — seconds for prices, minutes for profiles, hours for configs.
  • Missing key parameters — Cache key omits user ID, locale, or query params, serving wrong data.

    • Instead: include every parameter that affects the result: products:list:page=2:locale=en.
  • Caching errors — Storing error responses (500s, timeouts) with long TTLs.

    • Instead: skip caching on failure, or use a very short TTL (5-10 seconds) to allow fast retry.
  • Cache stampede — All instances hit the origin simultaneously when a popular key expires.

    • Instead: use stale-while-revalidate, jittered TTLs, or a mutex lock to let one instance refresh.

Frequently asked questions

What does the Caching AI skill do?

Caching strategies — invalidation, TTL guidelines, cache keys, cache layers, and when not to cache. Use when implementing or reviewing caching logic.

Why use Caching on TypingMind?

Because you install it once and use it with any model. Caching is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Caching in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/zebbern/claude-code-guide/tree/main/skills/caching. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Caching?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Caching?

As many as you like. As long as a model supports skills, you can use Caching with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Caching AI skill free?

Yes. It is published on GitHub by zebbern under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇