Caching strategy
Produce caching that is correct first and fast second, tailored to the app in front of you: its stack and versions, its routes, its staleness tolerance and its failure modes. Paths below are relative to this skill's directory.
Rules that hold for the whole task
- Classify every route or data type with references/core/decision-framework.md before proposing any cache. Record the decision step.
- Never put
public,s-maxage, a CDN TTL or a CDN/proxy/framework shared-cache rule on a response whose body depends on cookies, sessions,Authorization, tenant, entitlement or A/B bucket. Useprivate(withno-cache+ ETag);no-storefor secrets, payment and auth. - Every response, including errors and redirects, gets an explicit
Cache-Control. Defaultno-store; routes opt in. Platform and CDN defaults differ and change without notice. - The cache key must fully determine the response: allow-list query params, normalize, include host/tenant/locale where they change output. Never
Vary: CookieorVary: User-Agenton shared caches. - Use only APIs that exist in the detected framework version. Read versions from lockfiles; prefer the project's bundled docs (Next.js 16.3+ ships
node_modules/next/dist/docs). - On writes: commit the database first, then delete (not set) cache entries, inner layer before outer (app cache → proxy → CDN). Keep a TTL backstop. Use leases or version-conditional sets where stale-set races matter.
- Every hot or expensive cache gets single-flight (or request collapsing), TTL jitter and stale-while-revalidate, and the app must keep working when the cache is down.
- An error is not a miss: never cache 5xx as data, never treat a cache failure as "not found", never delete entries because a backend failed.
- Purges, flushes, CDN rule changes and cache-store migrations are destructive or outward-facing: write
plan.json, runscripts/validate_plan.py, show the user the change and get approval first. - Nothing is done until headers, HIT/
Agebehavior, a conditional GET (304) and a two-session leak test pass on the real path through the CDN.
Workflow (copy into your response and tick off)
- [ ] 0. Scope: audit + plan, implement a phase, or answer one question? (narrow question → read the matching reference, answer with the output contract, still obey the rules)
- [ ] 1. python scripts/detect_stack.py <repo> → read every path in "read"; note "read_when"
- [ ] 2. python scripts/find_cache_primitives.py <repo> → existing caches + warnings (confirm each)
- [ ] 3. Inventory routes/endpoints/data types (method, auth, cookies read, params, sources, writes)
- [ ] 4. If the user gives URLs: python scripts/probe_headers.py <url>... [--cookie-a ... --cookie-b ...] [--deception]
- [ ] 5. Confirm archetype, staleness budgets, tenancy and instance count with the user (one round of questions)
- [ ] 6. Classify each row (decision tree steps 0–9); fill assets/caching-plan.template.md and write plan.json
- [ ] 7. python scripts/validate_plan.py plan.json → fix until valid
- [ ] 8. Implement phase by phase (safety fixes first), with approval before destructive steps
- [ ] 9. Verify per references/core/observability-testing.md; leave monitoring and rollback in placeAsk before assuming when it changes the plan: who may see the response (public vs per user/tenant), the staleness budget per data type, which CDN fronts production, and how many app instances run. Everything else, decide with the defaults in the references and state the assumption.
Scripts
| Command | Output |
|---|---|
python scripts/detect_stack.py <repo> |
Frameworks with versions and config (Next cacheComponents, SvelteKit adapter, …), hosting/CDN, proxies, data stores, ORM, CMS, API, mobile, AI, CI, service workers, instance count (k8s, compose, Fly, Render, ECS, serverless), archetype candidates, read and read_when reference lists |
python scripts/find_cache_primitives.py <repo> [--layer L] |
Existing caching code/config with file:line, layer, kind; heuristic warnings (one-argument revalidateTag, Vary: Cookie, KEYS, unbounded LRU, module-level DataLoader, …) |
python scripts/probe_headers.py <url>... [--cookie-a 'k=v'] [--cookie-b 'k=v'] [--deception] |
Read-only live probe: repeat GETs (MISS→HIT, Age), conditional GET, header findings, two-session leak test, web cache deception probes. Cookie values are never printed. Only for URLs the user owns or is authorized to test |
python scripts/validate_plan.py plan.json |
{valid, errors, warnings}; exit 1 on errors (shared caching of private data, TTL over budget, missing invalidation/owner/verify, bad tags, Vary: Cookie, …) |
python scripts/size_cache.py --rps R --hit-ratio h --hit-ms A --miss-ms B [--keys K --avg-bytes V] |
Effective latency, origin load, hit ratio needed for a target, memory estimate |
All scripts are Python 3.9+ standard library, print JSON on stdout and accept --help.
Routing table
Read the files detect_stack.py lists; this table is the same mapping for manual use. Read only what the stack needs.
No CDN detected: ask what fronts production before choosing shared-cache headers. Mixed stacks or monorepos: run detect_stack.py per app directory.
Gotchas that span layers
- A missing
Cache-Controlis not "uncached": caches apply heuristic freshness to 200, 301, 404 and others. no-cachemeans "store but revalidate";no-storemeans "don't store". Shared caches still collapse requests forno-cache/max-age=0, so personalized responses needprivate.Set-Cookieon a public page silently disables caching at most CDNs, or gets cached and replayed at others. Strip cookies from anonymous cacheable responses.- Browser caches can't be purged: browser TTL ≤ staleness budget unless the URL is versioned.
- Layers stack: worst-case staleness is the sum of tier TTLs plus stale windows when each refills from a stale lower tier.
- Framework revalidation (
revalidateTag,revalidatePath) doesn't purge a CDN you run; "works locally, stale in production" is almost always a CDN copy. immutableonly on fingerprinted URLs. Keep previous builds' assets deployed so old HTML still loads.- One hot key expiring is a stampede even with jitter; use single-flight, SWR or early refresh.
- In-process caches drift per instance; serverless module scope is an opportunistic L1 only.
- Path confusion (
/account.css,/account;x.css,%2F) plus extension-based CDN rules is web cache deception: origins must sendprivate/no-storefor authenticated paths. - Hit ratio excludes BYPASS/uncacheable requests; measure per path class.
- When a vendor or framework skill is installed (Next.js cache components, Cloudflare, Redis, Vercel), use it for API detail; this skill owns the cross-layer plan and safety rules.
Glossary
| Term | Meaning |
|---|---|
| shared cache | Any cache serving many users: CDN, edge, reverse proxy, API gateway, framework full-route cache |
| private cache | A cache for one user: browser HTTP cache, mobile client cache |
| app cache | Server-side data cache: in-process L1 and/or distributed L2 (Redis, Valkey, Memcached) |
| staleness budget (S) | Max age of data the business tolerates being served, in seconds |
| cache key | Everything that selects a stored response/value (URL, allowed query params, Vary headers, tenant, version) |
| variant | One stored response per distinct cache key for the same URL |
| tag | Label for group invalidation (Cache-Tag, Surrogate-Key, cacheTag); lowercase entity:id plus all, ≤ 50 per response |
| soft purge / hard purge | Mark stale and revalidate / delete outright |
| SWR / SIE | stale-while-revalidate / stale-if-error (500, 502, 503, 504 only) |
| single-flight | Coalescing concurrent misses for one key into one recomputation |
| negative caching | Caching "not found" briefly |
| TTL jitter | Randomizing TTLs (about ±10 %) so keys don't expire together |
| cache-aside | App reads the cache; on a miss loads the source and fills the cache |
App-cache keys: {app}:{env}:v{schema}:[t:{tenant}:]{entity}:{id}. Bump v{schema} instead of flushing.
Output contract
For an audit or plan, deliver:
- Findings, safety issues first, each with evidence (
file:line, probe output) and the fix's phase. - The plan from assets/caching-plan.template.md plus
plan.jsonper assets/plan.schema.json (complete example: assets/plan.example.json), withvalidate_plan.pypassing. Defaults per data class: assets/policy-defaults.csv. - Every row states: route and methods, data class, audience, staleness budget, browser
Cache-Control, shared layer and exact header,Vary/cache key, app-cache mechanism and key, tags, invalidation trigger → mechanism → propagation time, decision step, owner, and a verification command.no-storerows stay in the table. - Rollout phases ordered by risk and ROI (safety first), each with a rollback, plus monitoring targets.
- Assumptions and open questions, explicitly.
For a narrow question, answer with the same fields that apply (mechanism, scope, TTL/freshness, key/Vary, invalidation, how to verify) and exact copy-paste headers or code for the detected version.
When implementing, start from the snippets and adapt them to the codebase's conventions: