Advanced (अपडेट: 1/6/2026)

Real App ke liye Claude Code Caching Strategy

HTTP cache, CDN, Service Worker, Redis aur invalidation ko Claude Code ke saath safe tareeke se design karein.

Real App ke liye Claude Code Caching Strategy

Caching app ko fast banane ka magic button nahi hai. Real product me browser HTTP cache, CDN, Service Worker Cache API, Redis, aur process memory alag-alag data ko alag lifetime ke liye store karte hain. Agar aap Claude Code ko sirf “cache add kar do” bolte hain, to app fast ho sakta hai, par stale price, purana stock, ya galti se private user data shared cache me chala jaane ka risk bhi badh sakta hai.

Is guide ka goal beginner ko ek clear rulebook dena hai: pehle decide karo kaunsa data kis cache layer me jayega, kitni der tak stale reh sakta hai, aur update ke baad kaunsa key ya URL invalidate hoga. Masa ne is pattern ko ek chhote Express app aur content-site workflow me test kiya. Sabse bada gain Redis helper se nahi, balki cache ownership likhne se mila.

flowchart LR
  User[Browser] --> Http[HTTP cache]
  Http --> SW[Service worker Cache API]
  SW --> CDN[CDN or edge cache]
  CDN --> App[Node app]
  App --> Redis[Redis cache]
  App --> DB[(Database)]

Pehle Chaar Faisle Karein

Claude Code ko implementation dene se pehle ye chaar sawaal likh dein:

  1. Kaunse users same response dekh sakte hain?
  2. Data kitni der stale reh sakta hai bina business ko nuksan pahunchaye?
  3. Update ke baad kaunsa key, URL, ya cache tag delete hoga?
  4. Cache galat ho to rollback ya purge kaun karega?

Static images aur hashed JavaScript bundle ek saal tak cache ho sakte hain. Billing page, account settings, aur authenticated HTML ko shared cache me nahi jana chahiye. MDN ka HTTP caching guide private browser cache aur shared CDN cache ka farq samjhata hai.

Layer Comparison

LayerBest forTTL guideInvalidation modelCommon failure
Browser HTTP cacheImages, CSS, JS, public short API1 minute se 1 yearfilename change, ETag, Cache-ControlAPI purana screen dikhata hai
CDN or edge cachearticle HTML, product list, OGP image30 seconds se 1 dayURL purge, tag purge, deploy purgeauthenticated HTML sabko mil jata hai
Service Worker Cache APIoffline page, app shell, static assetsversion basedcache name changeold worker old JS serve karta hai
Redis or app cacheDB aggregate, external API result10 seconds se 1 hourkey design, TTL, update eventKEYS command production block karta hai
Process memoryconfig value, feature flag copyseconds to minutesrestart or explicit clearmultiple instances disagree

Is table ko CLAUDE.md me rakhein. Isse Claude Code har naye route me same policy follow karta hai. Project instructions ke liye CLAUDE.md best practices bhi dekhein.

Use case 1: Express me HTTP Cache Header

Pehla cache aksar Redis nahi hota. Sabse pehle response header sahi karein. Cache-Control browser aur CDN ko batata hai ki response kitni der store ho sakta hai. Details MDN ke Cache-Control header me hain.

npm install express
node server.js
// server.js
const express = require("express");

const app = express();

function cacheControl(req, res, next) {
  const path = req.path;

  if (path.startsWith("/assets/")) {
    res.set("Cache-Control", "public, max-age=31536000, immutable");
    return next();
  }

  if (path.startsWith("/api/private/")) {
    res.set("Cache-Control", "no-store");
    return next();
  }

  if (path.startsWith("/api/public/")) {
    res.set("Cache-Control", "public, max-age=60, s-maxage=300, stale-while-revalidate=600");
    res.set("Vary", "Accept-Encoding");
    return next();
  }

  res.set("Cache-Control", "no-cache");
  next();
}

app.use(cacheControl);
app.use("/assets", express.static("public/assets"));

app.get("/api/public/products", (_req, res) => {
  res.json({ items: ["book", "template", "consultation"], generatedAt: new Date().toISOString() });
});

app.get("/api/private/me", (_req, res) => {
  res.json({ userId: "demo-user", plan: "team" });
});

app.listen(3000, () => console.log("http://localhost:3000"));

Yahan key design route separation hai. /api/private/ ko no-store milta hai, isliye browser ya CDN usse store nahi kare. Public API ko short browser TTL aur longer CDN TTL s-maxage se milta hai.

Use case 2: Redis getOrSet Helper

Redis tab useful hota hai jab database query ya external API repeatedly call hoti hai. Safe default cache-aside pattern hai: pehle Redis check karo, miss ho to source se load karo, phir TTL ke saath store karo.

npm install redis
// cache.js
const { createClient } = require("redis");

const redis = createClient({
  url: process.env.REDIS_URL || "redis://localhost:6379",
});

let connecting;

async function client() {
  if (redis.isOpen) return redis;
  if (!connecting) connecting = redis.connect();
  await connecting;
  return redis;
}

async function getOrSet(key, ttlSeconds, loader) {
  const r = await client();
  const cached = await r.get(key);

  if (cached !== null) return JSON.parse(cached);

  const fresh = await loader();
  await r.set(key, JSON.stringify(fresh), { EX: ttlSeconds });
  return fresh;
}

async function invalidate(keys) {
  const r = await client();
  if (keys.length > 0) await r.del(keys);
}

module.exports = { getOrSet, invalidate };
// products.js
const { getOrSet, invalidate } = require("./cache");

async function loadProductsFromDb() {
  return [
    { id: "p1", name: "Prompt Templates", price: 500 },
    { id: "p2", name: "Claude Code Consultation", price: 15000 },
  ];
}

async function getPublicProducts() {
  return getOrSet("products:list:v1", 300, loadProductsFromDb);
}

async function updateProduct(productId, patch) {
  console.log("update db", productId, patch);
  await invalidate(["products:list:v1", `products:item:${productId}:v1`]);
}

module.exports = { getPublicProducts, updateProduct };

Production me KEYS products:* se bachein. Keyspace bada ho to Redis block ho sakta hai. Known key list, related-key set, ya maintenance command me SCAN ka use karein.

Use case 3: Service Worker Cache Versioning

Service worker browser request intercept kar sakta hai. Cache API offline page, app shell, aur static asset ke liye useful hai. Pitfall ye hai ki purana worker deploy ke baad bhi old JavaScript serve kar sakta hai.

// public/sw.js
const CACHE_VERSION = "claude-code-cache-v2026-06-01";
const STATIC_CACHE = `${CACHE_VERSION}:static`;
const PRECACHE_URLS = ["/", "/offline.html", "/assets/app.css"];

self.addEventListener("install", (event) => {
  event.waitUntil(
    caches
      .open(STATIC_CACHE)
      .then((cache) => cache.addAll(PRECACHE_URLS))
      .then(() => self.skipWaiting())
  );
});

self.addEventListener("activate", (event) => {
  event.waitUntil(
    caches
      .keys()
      .then((names) =>
        Promise.all(
          names
            .filter((name) => !name.startsWith(CACHE_VERSION))
            .map((name) => caches.delete(name))
        )
      )
      .then(() => self.clients.claim())
  );
});

self.addEventListener("fetch", (event) => {
  const request = event.request;
  if (request.method !== "GET") return;

  event.respondWith(
    caches.match(request).then((cached) => {
      if (cached) return cached;
      return fetch(request).catch(() => caches.match("/offline.html"));
    })
  );
});

Register code:

if ("serviceWorker" in navigator) {
  window.addEventListener("load", () => {
    navigator.serviceWorker.register("/sw.js");
  });
}

Claude Code ko clearly bolen: cache name me release date ya build ID ho, aur activate me old caches delete hon.

Use case 4: Claude Code Cache Audit Prompt

Claude Code ka best use poore repository ko audit karna hai. Official Claude Code common workflows small investigation, edit, aur verification loop ko encourage karta hai; cache work me ye bahut fit hota hai.

You are auditing cache behavior in a web application.
Inspect this repository for HTTP headers, CDN assumptions, service workers, Redis, and process-memory caches.

Return:
1. Data stored by each cache layer
2. TTL and invalidation condition
3. Risk that personal or authenticated responses reach a shared cache
4. Concrete screens where stale data can appear
5. Minimal fix plan and verification commands

Constraints:
- Mark assumptions clearly
- Follow existing project patterns
- Suggest large refactors separately instead of applying them immediately

Practical scenarios

Use case: product catalog. Public product cards ko CDN me short TTL mil sakta hai, aur DB list Redis me 5 minutes cache ho sakti hai. Product edit ke baad product-list key delete karein aur affected CDN URL purge karein.

Use case: admin dashboard. Revenue aggregate 30 seconds se 5 minutes cache ho sakta hai. Permissions, notification, aur billing data ko private ya no-store rakhein.

Use case: docs/blog. Article HTML short edge cache me rahe, hashed assets long lived rahein, aur offline shell service worker own kare. Content-heavy site jaise ClaudeCodeLab ke liye ye pattern practical hai.

Use case: external API. Weather, plan, exchange rate, ya status feed ko Redis se absorb kiya ja sakta hai. Claude Code ko API terms check karne ko bolen, kyunki kuch providers storage restrict karte hain.

Pitfalls and failure cases

Sabse serious mistake authenticated HTML ko CDN me cache karna hai. Agar response cookies par depend karta hai to default private ya no-store rakhein. Speed chahiye to public shell alag rakhein aur user-specific data baad me fetch karein.

Missing Vary header galat response dikha sakta hai. Language, compression, device type, ya authorization response badalta hai to URL alag karein ya correct Vary bhejein.

Redis cache stampede tab hota hai jab popular key expire hoti hai aur bahut requests ek saath DB par girti hain. TTL jitter, short lock, ya stale-while-revalidate fallback add karein.

Service worker stale files zinda rakh sakta hai. Cache version change karein, old names delete karein, aur emergency unregister procedure rakhein.

Invalidation runbook

  1. Blast radius define karein: product, article, user, ya whole app.
  2. Database write pehle complete karein; write fail ho to cache delete na karein.
  3. Redis keys known list, related-key set, ya SCAN se delete karein.
  4. CDN ko URL ya tag se purge karein. Full purge last resort hai.
  5. Service worker cache version bump karein aur old caches disappear hone ki confirmation lein.
  6. curl -I, browser DevTools, aur Redis hit-rate logs se verify karein.

Is runbook ko Claude Code ki definition of done me add karein. Workflow discipline ke liye Claude Code productivity tips ke saath pair karein.

Training, templates, and consultation

Team workflow banana hai to ClaudeCodeLab product and template library se start karein. Agar CDN, Redis, permissions, aur review rules ko real repository par map karna hard hai, to Claude Code training and consultation page dekhein.

Official references: MDN HTTP caching, Cache API, Cache-Control, aur Anthropic Claude Code common workflows.

Is article ke examples ko try karne ke baad Masa ne dekha ki static asset requests kam hue, public API TTL predictable hua, aur Redis getOrSet helper ne unnecessary DB reads ko logs me visible bana diya. Service worker test ne sabse important lesson diya: versioned deletion ke bina stale CSS deploy ke baad bhi bach sakta hai. Practical win sirf speed nahi, balki ye clarity hai ki har cached value kitni der purani reh sakti hai.

#Claude Code #caching #Redis #CDN #Service Worker
मुफ़्त

मुफ़्त PDF: Claude Code cheatsheet

Email डालें और commands, review habits तथा safe workflow वाली एक-page PDF पाएँ.

हम आपका data सुरक्षित रखते हैं और spam नहीं भेजते.

Masa

लेखक के बारे में

Masa

Claude Code workflow और team adoption पर काम करने वाला engineer.