← Back to dashboard
cachingtoolingfreshReader view (for NotebookLM)

Caching Integration Guide

What is caching?

The real model

A five-layer stack — browser, CDN, Next.js, Redis, origin — each with its own key, TTL and invalidation path.

Push stable public data toward the user (long `s-maxage` + `immutable` fingerprinted assets) and keep volatile data in layers you can purge (Redis `DEL`, Next.js `updateTag`/`revalidateTag`, CDN cache tags). `stale-while-revalidate` means the edge answers instantly and refreshes out of band; on Kenya-targeted 2G/3G projects that is the whole performance strategy. Upstash Redis holds webhook idempotency keys (`SET ... NX` on the Stripe `event.id`, or the M-Pesa `CheckoutRequestID` on Kenya-targeted projects). On Next.js 16.4 the framework layer is `'use cache'` with `cacheLife`/`cacheTag`; on Vercel one tag now purges the CDN, Runtime Cache and Data Cache together. The mature pattern is a long TTL backstop plus tag-based invalidation on the write path.

Six caching primitives

One request, five layers of cache — and the one hard problem that ties them together.

Text
 ██████╗ █████╗  ██████╗██╗  ██╗██╗███╗   ██╗ ██████╗
██╔════╝██╔══██╗██╔════╝██║  ██║██║████╗  ██║██╔════╝
██║     ███████║██║     ███████║██║██╔██╗ ██║██║  ███╗
██║     ██╔══██║██║     ██╔══██║██║██║╚██╗██║██║   ██║
╚██████╗██║  ██║╚██████╗██║  ██║██║██║ ╚████║╚██████╔╝
 ╚═════╝╚═╝  ╚═╝ ╚═════╝╚═╝  ╚═╝╚═╝╚═╝  ╚═══╝ ╚═════╝

Caching Integration Guide

Focus: a cache is a faster copy of a slower truth. The whole game is deciding how long the copy is allowed to lie and how you tell it to stop lying. This guide walks the layers a codeAmani request passes through (browser, CDN/edge, Next.js, application cache, origin) and treats invalidation as the part that's actually hard.

Overview

Every cache is the same trade: serve a stored copy instead of recomputing, accepting that the copy may be stale. For codeAmani's US-first products that trade buys lower latency, lower function and database bills, and protection from traffic spikes. On Kenya-targeted projects, where users are on 2G/3G, it is also the difference between a page that paints from a nearby edge node and one that waits on a round trip to a US origin.

There is no single cache. A request flows through a stack of them, each with its own TTL, its own key, and its own invalidation story:

The closer to the user a layer sits, the cheaper and faster the hit, and the harder it is to reach in and invalidate. You cannot purge a browser cache at all (only let it expire); you can DEL a Redis key in a millisecond. Design accordingly: put volatile data in layers you control, stable data in layers near the user.

Phil Karlton: "There are only two hard things in computer science: cache invalidation and naming things." The operational corollary: a cache hit is a guess that the world hasn't changed. Every section below is about making that guess safely.

Official Documentation

SourceURLWhat it covers
MDN HTTP cachinghttps://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CachingCache-Control directives, ETag/If-None-Match, 304 flow
Next.js Caching (Cache Components)https://nextjs.org/docs/app/getting-started/cachingcacheComponents, partialPrefetching, use cache, where entries are stored
Next.js use cachehttps://nextjs.org/docs/app/api-reference/directives/use-cacheCache keys, serialization, runtime caching on serverless vs self-hosted
Next.js previous modelhttps://nextjs.org/docs/app/guides/caching-without-cache-componentsfetch caching, revalidateTag/revalidatePath, unstable_cache
Vercel caching overviewhttps://vercel.com/docs/cachingCDN, ISR, Runtime and Image caches; request collapsing
Vercel CDN cachehttps://vercel.com/docs/caching/cdn-cacheTargeted headers, Vary rules, cacheable criteria, limits
Vercel CDN purgehttps://vercel.com/docs/caching/cdn-cache/purgeVercel-Cache-Tag, invalidate vs delete, purge rate limits
Vercel Runtime Cachehttps://vercel.com/docs/caching/runtime-cachegetCache(), use cache: remote, limits, pricing
Cloudflare cache controlhttps://developers.cloudflare.com/cache/concepts/cache-control/Origin Cache Control, SWR, stale-if-error, CF-Cache-Status
Cloudflare Workers Cachehttps://developers.cloudflare.com/workers/cache/Cache in front of a Worker, ctx.cache.purge()/invalidate()
Upstash Redis (TS)https://upstash.com/docs/redis/sdks/ts/getstartedREST client, set with { ex, nx }, Redis.fromEnv()

Versions and prices verified 2026-10-20

ItemValueSource
next16.4.2 (latest)npm view next version
@upstash/redis1.39.0npm view @upstash/redis version
@vercel/functions3.10.1npm view @vercel/functions version
@vercel/global-config1.5.1npm view @vercel/global-config version
@cloudflare/workers-types5.20261019.1npm view @cloudflare/workers-types version
Vercel Runtime Cache$0.40 per 1M reads, $4.00 per 1M writes in iad1 (regional range $0.40–$0.64 / $4.00–$6.40)vercel.com/docs/pricing/regional-pricing
Upstash RedisFree: 250 MB + 500K commands/month. Pay as you go: $0.20 per 100K commands. Fixed plans from $10/monthupstash.com/pricing/redis
Workers KV (Paid)10M reads/month then $0.50/M; 1M writes/month then $5.00/M; 1 GB then $0.50/GB-monthdevelopers.cloudflare.com/kv/platform/pricing

Layer 1 — HTTP caching (Cache-Control, ETag, SWR)

The HTTP cache is the foundation every other layer builds on. It is driven entirely by response headers: no library, no SDK. Get these right and the browser, the CDN and any proxy cooperate for free.

The directives that matter

DirectiveMeaningUse for
max-age=NFresh for N seconds in any cache (incl. browser)Data the browser may keep
s-maxage=NFresh for N seconds in shared caches (CDN); overrides max-age thereCDN TTL distinct from browser (see the Cloudflare caveat below)
stale-while-revalidate=NServe stale up to N s while refreshing in backgroundAnything where instant beats perfectly fresh
stale-if-error=NServe stale up to N s if the origin returns 5xxRiding out origin outages (Vercel and Cloudflare both honor it)
no-cacheStore, but revalidate every time before reuseHTML that changes but supports ETag
no-storeNever store anywhereAuth tokens, webhook callbacks, PII
privateBrowser only, never a shared cachePersonalised responses
publicCacheable even with AuthorizationShared, non-sensitive assets
immutableContent will never change; skip revalidationHashed/fingerprinted static assets

The two patterns you'll write most:

HTTP
# Fingerprinted asset (app-abc123.js): cache forever, it can never change
Cache-Control: public, max-age=31536000, immutable

# Dynamic JSON on Vercel: browser 10 s, CDN 60 s, then stale for 5 min while refreshing
Cache-Control: public, max-age=10, s-maxage=60, stale-while-revalidate=300

stale-while-revalidate: the default for dynamic data

SWR decouples latency from freshness: the user gets an instant response from cache, and the cache refreshes itself out of band. The cost of a slow origin is paid by a background fetch, never by a user staring at a spinner. On Kenya-targeted projects on 2G/3G this is the single most valuable directive.

ETag / If-None-Match: cheap revalidation

When content must be revalidated (no-cache, or an expired max-age), an ETag turns a full re-download into a tiny 304 Not Modified. The server hashes the body into an ETag; the browser echoes it back as If-None-Match; if unchanged, the server replies 304 with no body. Cloudflare's soft purge (invalidate_cache, below) also relies on your origin answering conditional requests.

TypeScript
// app/api/profile/route.ts
import { createHash } from "node:crypto";

export async function GET(req: Request): Promise<Response> {
  const profile = await getProfile();
  const body = JSON.stringify(profile);
  const etag = `"${createHash("sha256").update(body).digest("base64url").slice(0, 16)}"`;
  if (req.headers.get("if-none-match") === etag) {
    return new Response(null, { status: 304, headers: { ETag: etag } });
  }
  return new Response(body, {
    headers: { "Content-Type": "application/json", ETag: etag, "Cache-Control": "private, no-cache" },
  });
}

Never cache secrets. Auth tokens, payment credentials, webhook callbacks and PII responses get Cache-Control: no-store. Vercel's CDN already refuses to cache a request carrying Authorization or a response with Set-Cookie, but be explicit and don't rely on the platform to save you.


Layer 2 — CDN / edge caching (Vercel + Cloudflare)

The CDN is a shared cache in dozens of cities. It keys on the URL (plus any Vary headers) and obeys s-maxage or the targeted CDN-Cache-Control headers. This is where a single origin render gets amortised across thousands of visitors.

Vercel CDN

Vercel caches a function/SSR response when its cache header contains s-maxage=N, optionally with stale-while-revalidate=Z and stale-if-error=Z (now supported). It also honours targeted headers, so you can give Vercel, downstream CDNs and the browser different TTLs in one response:

TypeScript
// app/api/catalog/route.ts: browser 10s, downstream CDNs 60s, Vercel 1h
export async function GET(): Promise<Response> {
  return Response.json(await getCatalog(), {
    headers: {
      "Cache-Control": "public, max-age=10",
      "CDN-Cache-Control": "public, s-maxage=60",
      "Vercel-CDN-Cache-Control": "public, s-maxage=3600, stale-while-revalidate=86400, stale-if-error=86400",
    },
  });
}
  • Vercel-CDN-Cache-Control controls only Vercel and is never forwarded. If you set Cache-Control without CDN-Cache-Control, Vercel strips s-maxage and stale-while-revalidate before the response reaches the browser.
  • Cacheable only if: GET/HEAD; no Range or Authorization request header; status 200/404/410/301/302/307/308; ≤10 MB (20 MB streaming); no Set-Cookie; no private/no-cache/no-store; no Vary: *; and no Vary naming a high-cardinality header such as Cookie (new: such responses come back MISS with reason "Vary key denied"). Max cache time is 1 year, best-effort. proxy-revalidate is still unsupported.
  • The cache key is method + URL + host + deployment URL + scheme. It is not configurable: to purge selectively you need cache tags.
  • x-vercel-cache tells you what happened: HIT, MISS, STALE, PRERENDER, REVALIDATED (regenerated in the foreground after a delete) or BYPASS. For runtime-cached data inside a dynamic route it often reads MISS; check runtime logs instead.

Vercel cache tags and purging

Tag a response with the Vercel-Cache-Tag header (comma-separated), addCacheTag() from @vercel/functions, or Next.js cacheTag(). Purging a tag purges the CDN cache, Runtime Cache and Data Cache together. Two purge styles:

Invalidate (serve stale, refresh in background)Delete (regenerate in foreground)
@vercel/functionsinvalidateByTag(tag)dangerouslyDeleteByTag(tag, { revalidationDeadlineSeconds })
next/cache (Next.js 16)revalidateTag(tag, "max")updateTag(tag), revalidatePath(path), deprecated revalidateTag(tag)
CLIvercel cache invalidate --tagvercel cache dangerously-delete --tag
REST/invalidate-by-tag/dangerously-delete-by-tag

Limits: 256 UTF-8 bytes per tag, 128 tags per response, no commas, 16 tags per bulk REST call. Function-side purge calls are rate-limited at 50/s per team (Hobby), 200/s per team (Pro), 500/s per project (Enterprise), averaged over 30 s; over the limit you get 429 with retry-after and nothing is purged. A full example is in examples/vercel-cdn-and-runtime-cache.ts.

Cloudflare

Cloudflare honours origin Cache-Control (Origin Cache Control is on by default), and stale-while-revalidate is fully asynchronous: the first request after expiry gets the stale copy with CF-Cache-Status: UPDATING while the refresh runs. Status values: HIT, MISS, EXPIRED, STALE, UPDATING, REVALIDATED, BYPASS, DYNAMIC, NONE/UNKNOWN.

Cloudflare gotcha: s-maxage turns SWR off. Per RFC 9111, s-maxage implies proxy-revalidate, so with it present Cloudflare will not serve stale content and you get EXPIRED instead of UPDATING. The same goes for must-revalidate, proxy-revalidate and no-cache. For SWR with a separate edge TTL, send max-age + stale-while-revalidate and set the edge TTL with a Cache Rule, or put the edge policy in Cloudflare-CDN-Cache-Control (Cloudflare only, not forwarded) or CDN-Cache-Control (forwarded to downstream CDNs).

HTTP
Cache-Control: public, max-age=60
Cloudflare-CDN-Cache-Control: max-age=86400, stale-while-revalidate=3600, stale-if-error=86400
Cache-Tag: catalog,prices,vendor-42

Purge by Cache-Tag is now available on every plan (Free, Pro, Business, Enterprise). Free accounts are limited to 5 tag/host/prefix purge requests per minute (bucket 25); Pro 5/s; Business 10/s; Enterprise 50/s; up to 100 tags per request. Tags are case-insensitive, printable ASCII, no spaces, total header ≤16 KB. There are now two endpoints with the same request body:

Bash
# Hard purge: content removed, next request is a MISS
curl -X POST "https://api.cloudflare.com/client/v4/zones/$CLOUDFLARE_ZONE_ID/purge_cache" \
  -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" -H "Content-Type: application/json" \
  --data '{"tags":["prices"]}'

# Soft purge (invalidate): content kept, marked stale, revalidated with ETag/Last-Modified
curl -X POST "https://api.cloudflare.com/client/v4/zones/$CLOUDFLARE_ZONE_ID/invalidate_cache" \
  -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" -H "Content-Type: application/json" \
  --data '{"tags":["prices"]}'

Workers Cache (new) vs the Cache API

  • Workers Cache sits in front of a Worker: enable "cache": { "enabled": true } in wrangler.jsonc, return Cache-Control, and Cloudflare serves hits without running your code. It is tiered (lower tier near the user, upper tier aggregating the network), collapses concurrent misses into one Worker run, and is keyed by path, entrypoint, ctx.props and Worker version, not hostname. Zone Cache Rules and zone purges do not apply; purge from the Worker with ctx.cache.purge({ tags | pathPrefixes | purgeEverything }) or soft-purge with ctx.cache.invalidate(...) (also importable as cache from cloudflare:workers). No separate price, but with caching on every request is billed at the Workers request rate (including static-asset and worker-to-worker requests that are otherwise free); cache hits use no CPU time.
  • Cache API (caches.default, caches.open()) is the older programmatic store: per data center only, not tiered (cache.put is incompatible with Tiered Cache), no request collapsing, and match/put ignore stale-while-revalidate/stale-if-error.

See examples/cloudflare-worker-cache.ts.


Layer 3 — Next.js caching (two models)

As of Next.js 16 (latest 16.4.2) there are two ways to drive the framework caches, and which one you're in changes the API you reach for:

  • Cache Components (current model): cacheComponents: true in next.config.ts. New create-next-app projects ship with it and partialPrefetching: true enabled. Set partialPrefetching explicitly (added in 16.3; leaving it unset logs a warning); Next says both will be always-on in the next major. You mark cached work with "use cache" and control it with cacheLife()/cacheTag(); anything uncached must sit inside <Suspense> or the dev overlay flags a blocking route. With Cache Components on, GET Route Handlers follow the same prerendering model as pages.
  • Previous model (Cache Components off): fetch opt-in caching plus unstable_cache, invalidated with revalidateTag/revalidatePath. Still supported in 16 and still what most existing codeAmani apps run.
TypeScript
// next.config.ts
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  cacheComponents: true,
  partialPrefetching: true,
  cacheLife: {
    // custom profile, usable as cacheLife("catalog")
    catalog: { stale: 300, revalidate: 900, expire: 86_400 },
  },
};

export default nextConfig;

"use cache" and cacheLife

Put "use cache" at the top of an async function, component or file. Arguments and captured closure values form the cache key, so there is no manual key array. Always pair it with cacheLife(); without one the implicit default profile applies.

TypeScript
import { cacheLife, cacheTag } from "next/cache";

export async function getVendors(): Promise<Vendor[]> {
  "use cache";
  cacheTag("vendors");   // up to 128 tags per call, 256 chars each
  cacheLife("hours");
  return db.listVendors();
}
Profilestale (client)revalidate (background refresh)expire (hard limit)
default5 min15 minnever
seconds30 s1 s1 min
minutes5 min1 min1 h
hours5 min1 h1 day
days5 min1 day1 week
weeks5 min1 week30 days
max5 min30 days1 year

Inline form: cacheLife({ stale, revalidate, expire }); expire must exceed revalidate. You can redefine any built-in (including default) or add custom names in next.config.ts.

Where "use cache" entries actually live

This is the part that surprises people:

DirectiveStoreNotes
"use cache"Prerendered static shell + per-instance in-memory LRU at runtimeOn serverless, runtime entries usually don't survive between requests. Self-hosted: persistent, sized by cacheMaxMemorySize
"use cache: remote"A shared cache handler (cacheHandlers); Vercel Runtime Cache on VercelDurable across instances; costs a network round trip, so only worth it at a high hit rate (rate-limited APIs, slow backends)
"use cache: private"Browser onlyMay read cookies()/headers()/searchParams directly; for compliance cases or code you can't refactor

None of them survive a deploy: the build id is part of the cache key. For non-fetch data that must persist across deploys, the use cache docs still point to unstable_cache or the fetch cache.

Inside "use cache" you cannot call cookies()/headers()/searchParams. Read them outside and pass the value in as an argument. draftMode().isEnabled is allowed; in Draft Mode cached functions re-run on every request.

Previous model: fetch + unstable_cache

fetch is not cached by default (since Next.js 15). Opt in:

TypeScript
// Time-based, regenerate at most once per hour
const data = await fetch("https://api.example.com/catalog", { next: { revalidate: 3600 } });

// Tag for on-demand invalidation, with a 24 h backstop
const vendors = await fetch("https://api.example.com/vendors", { next: { tags: ["vendors"], revalidate: 86_400 } });

// Cache until invalidated (Vercel Data Cache)
const stable = await fetch("https://api.example.com/config", { cache: "force-cache" });

unstable_cache is replaced by "use cache" in Next.js 16 (its docs page says so). It still ships and works; use "use cache" for new code, and keep unstable_cache only where an entry must outlive a deploy.

Request memoization

Within one render, identical fetch() calls hit the network once. For non-fetch access (an ORM, the Supabase client) wrap it in React's cache(). Note that React.cache is isolated inside "use cache" boundaries: values memoized outside are not visible inside.

TypeScript
import { cache } from "react";
export const getVendor = cache(async (id: string) => db.vendorById(id));

Tag-based, on-demand invalidation

Time-based revalidation is a guess at how often data changes. Tag-based invalidation is precise: tag the data when you read it, then invalidate that tag when you write.

TypeScript
"use server";
import { revalidatePath, revalidateTag, updateTag } from "next/cache";

// Read-your-own-writes: the caller sees fresh data on the next request (Server Actions only)
export async function addVendor(form: FormData): Promise<void> {
  await db.createVendor(form);
  updateTag("vendors");
  revalidatePath("/vendors");
}

// Background SWR: mark stale, refresh on next visit (Server Actions AND Route Handlers)
export async function onVendorWebhook(): Promise<void> {
  revalidateTag("vendors", "max");
}
  • updateTag(tag): Server Actions only (throws elsewhere). Expires the tag immediately; the next request waits for fresh data.
  • revalidateTag(tag, profile): Server Functions and Route Handlers, not Client Components or Proxy. "max" (recommended) = serve stale while revalidating, for up to a year. Any cacheLife profile name or { expire: N } sets a different window; { expire: 0 } makes the next request block. The single-argument form is deprecated and behaves like { expire: 0 }. Revalidation is triggered lazily by requests, not by the call.
  • revalidatePath(path, type?): unchanged; 'page' | 'layout' second argument.
  • Tags are case-sensitive and capped at 256 characters; longer tags are silently never assigned.

Which layers does it reach? On Vercel, cacheTag also tags the CDN entry, and revalidateTag/updateTag/revalidatePath purge the CDN, Runtime Cache and Data Cache together. They do not expire entries you wrote yourself with getCache().set() (use expireTag). On Cloudflare or self-hosted, they only touch Next's own caches, so purge the CDN separately (Cache-Tag + purge_cache/invalidate_cache).


Layer 4 — Application and runtime caches

When the thing you're caching isn't an HTTP response (a computed result, a DB aggregate, a short-lived token, an idempotency key) you reach for an application cache. Pick by where the code runs and how durable the entry must be:

StoreBest forDurabilityWatch out for
Upstash Redis (codeAmani default)Cache-aside, idempotency keys, locks, rate limits; any hostDurable until TTLEvery op is a billed command; REST round trip
Vercel Runtime CacheRead-through cache inside Vercel FunctionsRegional, LRU-evicted, survives deploys, split preview/prod2 MB/item; Hobby projects share one cache; not for data that must stay its full TTL
Workers KVRead-heavy config/catalog data at Cloudflare's edgeDurableEventually consistent (60 s+ across locations); 1 write/s per key
Vercel Global Config (formerly Edge Config)Feature flags, redirects, IP blocklists read on every requestDurable, replicated with your functionsA config store, not a cache: 1 MB per store, 100 writes/hour on Pro

Upstash Redis (cache-aside)

@upstash/redis is REST-based, so it works from Vercel Functions, Edge and Cloudflare Workers (import { Redis } from "@upstash/redis/cloudflare") with no connection pool.

TypeScript
// lib/cache.ts
import { Redis } from "@upstash/redis";

export const redis = Redis.fromEnv(); // UPSTASH_REDIS_REST_URL + UPSTASH_REDIS_REST_TOKEN

/** Cache-aside: try cache, fall back to origin, backfill with a TTL. */
export async function cached<T>(key: string, ttlSec: number, fetcher: () => Promise<T>): Promise<T> {
  const hit = await redis.get<T>(key);
  if (hit !== null) return hit; // HIT

  const fresh = await fetcher(); // MISS: compute
  await redis.set(key, fresh, { ex: ttlSec }); // backfill with TTL
  return fresh;
}

The TTL on set(..., { ex }) is your safety net: even if you forget to invalidate, the key self-destructs. Always set a TTL. examples/cache-aside.ts adds a single-flight lock against stampedes and a firstSeen() idempotency helper.

Webhook idempotency with SET NX

Payment webhooks get retried. After verifying the signature, record the event ID with NX so a duplicate delivery is a no-op:

TypeScript
// Stripe (default payments): dedupe on event.id after stripe.webhooks.constructEvent()
const first = await redis.set(`stripe:evt:${event.id}`, "1", { nx: true, ex: 86_400 });
if (first === null) return new Response(null, { status: 200 }); // already processed

Kenya-targeted projects use the same pattern for M-Pesa: store the CheckoutRequestID as soon as STK Push responds and dedupe callbacks with SET mpesa:cri:<id> 1 NX EX 86400; cache the Daraja OAuth token for ~50 minutes so it refreshes before its 1-hour expiry.

Vercel Runtime Cache

TypeScript
import { getCache } from "@vercel/functions";

const cache = getCache({ namespace: "products" });
const hit = await cache.get(id);                       // null on miss or expiry
await cache.set(id, product, { ttl: 3600, tags: [`product-${id}`] });
await cache.expireTag(`product-${id}`);                 // global within ~300 ms

In Next.js 16 the same store backs "use cache: remote". Watch reads, writes and hit rate under Observability > Runtime Cache.


Cache invalidation — the actual hard problem

Invalidation is where systems rot. The core tension: the longer the TTL, the better the hit rate, and the longer wrong data is served. There is no universally correct TTL, only a deliberate choice per data type.

Time-based (TTL)Tag/event-based
IdeaExpire after N seconds, hope that's often enoughInvalidate the instant the data actually changes
StalenessUp to the full TTLNear-zero
Best forData that drifts predictably (exchange rates, leaderboards)Data with a clear write event (a vendor edits a price)
CostWasted refreshes / stale windowsMust wire every writer to invalidate
ToolsCDN s-maxage, cacheLife, next.revalidate, Redis exupdateTag/revalidateTag(tag,"max"), Vercel-Cache-Tag + invalidateByTag, Cloudflare Cache-Tag + purge/invalidate, Redis DEL

The mature pattern combines them: a long TTL as a backstop plus tag invalidation for correctness. Tags handle the known changes; the TTL guarantees nothing is stale forever if an invalidation is missed (and one always eventually is).

Practical rules

  • Match the layer to volatility. Volatile, must-be-correct data goes in a cache you can DEL. Stable, public data goes to the CDN with a long TTL.
  • Invalidate on write, not on a timer, when you can.
  • Prefer soft purge. revalidateTag(tag, "max"), invalidateByTag, Cloudflare invalidate_cache and ctx.cache.invalidate() serve stale while refreshing; hard deletes cause a cold-cache stampede on hot tags.
  • Fingerprint immutable assets. app-[hash].js with immutable, max-age=31536000 never needs invalidating: you change the URL instead.
  • Beware the stampede. When a hot key expires, every concurrent request misses at once. SWR, Vercel's and Cloudflare's request collapsing, and a Redis SET NX single-flight lock all prevent it.
  • Mind the purge rate limits (Vercel 50–500/s, Cloudflare Free 5/min). Batch tags into one call; one call with many tags counts once on Vercel.
  • Never cache what you can't afford to be stale, and never put a secret in a cache.

Debugging: which layer is lying?

A stale page is almost always one layer holding an old copy. Walk the stack from the user inward:

SymptomCheckHeader / signal
Browser shows old pageDevTools → Network → Disable cacheCache-Control, Age
Edge serving staleResponse headerx-vercel-cache (HIT/STALE/REVALIDATED) · CF-Cache-Status (HIT/UPDATING/EXPIRED)
Vercel never caches a routeRuntime logs cache reasonVary: Cookie, Set-Cookie, private, Authorization
Cloudflare SWR not kicking inCF-Cache-Status: EXPIRED instead of UPDATINGs-maxage or must-revalidate in the header
Next.js route won't updateDid the mutation call updateTag/revalidateTag? Is the tag spelled identically (case-sensitive, ≤256 chars)?NEXT_PRIVATE_DEBUG_CACHE=1 verbose logging
use cache hit rate is near zero on VercelPer-instance memory on serverlessSwitch hot paths to use cache: remote
Redis returns old valueredis.ttl(key): is it expiring? Did the writer DEL?TTL value

A HIT anywhere means you're being served a cached copy: that's the layer to invalidate, not the origin.


Environment

Secrets (store in the vault, .env.local locally, Vercel/Cloudflare env in production):

Bash
UPSTASH_REDIS_REST_URL=https://your-db.upstash.io
UPSTASH_REDIS_REST_TOKEN=AX...
CLOUDFLARE_API_TOKEN=cf-token-with-cache-purge-permission
GLOBAL_CONFIG=https://global-config.vercel.com/ecfg_...?token=...

Non-secret settings:

VariableExamplePurpose
CLOUDFLARE_ZONE_ID023e105f4ecef8ad9ca31a8372d0c353Zone for purge_cache / invalidate_cache
NEXT_PRIVATE_DEBUG_CACHE1Verbose Next.js cache logging while debugging

GLOBAL_CONFIG is created automatically when you connect a Global Config store to a Vercel project. The new SDK falls back to the legacy EDGE_CONFIG variable, but @vercel/edge-config cannot read stores connected after the rename. Workers on Cloudflare get the Upstash values via wrangler secret put.


codeAmani notes

  • US-first default. Dynamic public responses get s-maxage + stale-while-revalidate (+ stale-if-error) on Vercel, fingerprinted assets get immutable, and personalised responses are private/no-store. On Kenya-targeted projects the same settings are the 2G/3G performance strategy: perceived speed is how rarely the user waits for the origin, and an ETag 304 saves bytes on metered data plans.
  • Upstash Redis is the app-cache default (REST, works on Vercel and Cloudflare). Use it for cache-aside, single-flight locks and webhook idempotency: Stripe event.id by default (SET stripe:evt:<id> 1 NX EX 86400 after signature verification). M-Pesa only on Kenya-targeted projects: dedupe on CheckoutRequestID and cache the Daraja token ~50 min. Vercel Runtime Cache is fine for read-through caching inside Vercel Functions, but not for idempotency keys (entries can be evicted early).
  • One tag, every layer (Vercel). Use the same tag name for cacheTag, Vercel-Cache-Tag and Redis key namespaces (vendor-42 ↔ vendor:42:*) so a single write path can invalidate all of them. On Cloudflare-hosted apps, add the CDN purge call to that write path.
  • Next.js 16 apps: turn on cacheComponents + partialPrefetching, pair every "use cache" with a cacheLife, use updateTag in Server Actions and revalidateTag(tag, "max") in webhook Route Handlers. Never ship the deprecated one-argument revalidateTag.
  • Never cache secrets or PII. Clerk session data, Stripe objects with customer details, payment callbacks: Cache-Control: no-store, never in a shared cache key, never NEXT_PUBLIC_*.
  • AI responses: caching identical, non-personal LLM calls (summaries of public content, embeddings) in Redis keyed by a hash of model + prompt saves real money; never cache responses that include user data in a shared key. Provider-side prompt caching (Anthropic, OpenAI) is a separate mechanism covered in the anthropic/ and open-ai/ guides.
  • Edge Config is now Global Config. New code imports @vercel/global-config; existing @vercel/edge-config projects keep working with no deadline, but upgrade before connecting a new store.