Caching Integration Guide
Technology: caching · Category: tooling · Last reviewed: 2026-10-20
Source: https://tech-stack.codeamanilabs.org/guide/caching
Insight:
A cache is a faster copy of a slower truth, and the whole discipline reduces to one trade-off: how long the stored copy is allowed to lie versus how precisely you can tell it to stop. The codeAmani default is stale-while-revalidate at the edge plus tag-based invalidation on the write path, with Upstash Redis for non-HTTP values such as webhook idempotency keys. Two things changed the picture in 2026: on Vercel, one tag now reaches every layer (Next.js
cacheTagfeeds the CDN, Runtime Cache and Data Cache, andrevalidateTagpurges them together), and Next.js 16'suse cacheis per-instance memory unless you sayuse cache: remote. Check which layer actually holds the entry before you trust a hit rate.
██████╗ █████╗ ██████╗██╗ ██╗██╗███╗ ██╗ ██████╗
██╔════╝██╔══██╗██╔════╝██║ ██║██║████╗ ██║██╔════╝
██║ ███████║██║ ███████║██║██╔██╗ ██║██║ ███╗
██║ ██╔══██║██║ ██╔══██║██║██║╚██╗██║██║ ██║
╚██████╗██║ ██║╚██████╗██║ ██║██║██║ ╚████║╚██████╔╝
╚═════╝╚═╝ ╚═╝ ╚═════╝╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═════╝
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:
flowchart LR
A["Browser<br/>Cache-Control · Cache API"] --> B["CDN / Edge<br/>Vercel CDN · Cloudflare · Workers Cache<br/>s-maxage · SWR · cache tags"]
B --> C["Framework<br/>Next.js use cache · ISR<br/>cacheTag · revalidateTag"]
C --> D["App / runtime cache<br/>Upstash Redis · Vercel Runtime Cache · Workers KV"]
D --> E["Origin<br/>Postgres · Stripe · LLM APIs"]
style A fill:#1e3a5f,stroke:#3B82F6,color:#fff
style B fill:#1e3a5f,stroke:#3B82F6,color:#fff
style C fill:#1e3a5f,stroke:#3B82F6,color:#fff
style D fill:#1e3a5f,stroke:#3B82F6,color:#fff
style E fill:#2a2a2a,stroke:#888,color:#fff
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
| Source | URL | What it covers |
|---|---|---|
| MDN HTTP caching | https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Caching | Cache-Control directives, ETag/If-None-Match, 304 flow |
| Next.js Caching (Cache Components) | https://nextjs.org/docs/app/getting-started/caching | cacheComponents, partialPrefetching, use cache, where entries are stored |
Next.js use cache |
https://nextjs.org/docs/app/api-reference/directives/use-cache | Cache keys, serialization, runtime caching on serverless vs self-hosted |
| Next.js previous model | https://nextjs.org/docs/app/guides/caching-without-cache-components | fetch caching, revalidateTag/revalidatePath, unstable_cache |
| Vercel caching overview | https://vercel.com/docs/caching | CDN, ISR, Runtime and Image caches; request collapsing |
| Vercel CDN cache | https://vercel.com/docs/caching/cdn-cache | Targeted headers, Vary rules, cacheable criteria, limits |
| Vercel CDN purge | https://vercel.com/docs/caching/cdn-cache/purge | Vercel-Cache-Tag, invalidate vs delete, purge rate limits |
| Vercel Runtime Cache | https://vercel.com/docs/caching/runtime-cache | getCache(), use cache: remote, limits, pricing |
| Cloudflare cache control | https://developers.cloudflare.com/cache/concepts/cache-control/ | Origin Cache Control, SWR, stale-if-error, CF-Cache-Status |
| Cloudflare Workers Cache | https://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/getstarted | REST client, set with { ex, nx }, Redis.fromEnv() |
Versions and prices verified 2026-10-20
| Item | Value | Source |
|---|---|---|
next |
16.4.2 (latest) | npm view next version |
@upstash/redis |
1.39.0 | npm view @upstash/redis version |
@vercel/functions |
3.10.1 | npm view @vercel/functions version |
@vercel/global-config |
1.5.1 | npm view @vercel/global-config version |
@cloudflare/workers-types |
5.20261019.1 | npm 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 Redis | Free: 250 MB + 500K commands/month. Pay as you go: $0.20 per 100K commands. Fixed plans from $10/month | upstash.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-month | developers.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
| Directive | Meaning | Use for |
|---|---|---|
max-age=N |
Fresh for N seconds in any cache (incl. browser) | Data the browser may keep |
s-maxage=N |
Fresh for N seconds in shared caches (CDN); overrides max-age there |
CDN TTL distinct from browser (see the Cloudflare caveat below) |
stale-while-revalidate=N |
Serve stale up to N s while refreshing in background | Anything where instant beats perfectly fresh |
stale-if-error=N |
Serve stale up to N s if the origin returns 5xx | Riding out origin outages (Vercel and Cloudflare both honor it) |
no-cache |
Store, but revalidate every time before reuse | HTML that changes but supports ETag |
no-store |
Never store anywhere | Auth tokens, webhook callbacks, PII |
private |
Browser only, never a shared cache | Personalised responses |
public |
Cacheable even with Authorization |
Shared, non-sensitive assets |
immutable |
Content will never change; skip revalidation | Hashed/fingerprinted static assets |
The two patterns you'll write most:
# 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.
sequenceDiagram
participant U as User
participant C as Cache (edge)
participant O as Origin
Note over C: max-age=60, stale-while-revalidate=300
U->>C: GET /prices (t=0, fresh)
C-->>U: 200 cached · instant
U->>C: GET /prices (t=90s, STALE but in SWR window)
C-->>U: 200 STALE · instant (no wait!)
C->>O: background revalidate
O-->>C: fresh copy stored
U->>C: GET /prices (t=120s)
C-->>U: 200 fresh · instant
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.
// 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 carryingAuthorizationor a response withSet-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:
// 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-Controlcontrols only Vercel and is never forwarded. If you setCache-ControlwithoutCDN-Cache-Control, Vercel stripss-maxageandstale-while-revalidatebefore the response reaches the browser.- Cacheable only if:
GET/HEAD; noRangeorAuthorizationrequest header; status 200/404/410/301/302/307/308; ≤10 MB (20 MB streaming); noSet-Cookie; noprivate/no-cache/no-store; noVary: *; and noVarynaming a high-cardinality header such asCookie(new: such responses come backMISSwith reason "Vary key denied"). Max cache time is 1 year, best-effort.proxy-revalidateis 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-cachetells you what happened:HIT,MISS,STALE,PRERENDER,REVALIDATED(regenerated in the foreground after a delete) orBYPASS. For runtime-cached data inside a dynamic route it often readsMISS; 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/functions |
invalidateByTag(tag) |
dangerouslyDeleteByTag(tag, { revalidationDeadlineSeconds }) |
next/cache (Next.js 16) |
revalidateTag(tag, "max") |
updateTag(tag), revalidatePath(path), deprecated revalidateTag(tag) |
| CLI | vercel cache invalidate --tag |
vercel 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-maxageturns SWR off. Per RFC 9111,s-maxageimpliesproxy-revalidate, so with it present Cloudflare will not serve stale content and you getEXPIREDinstead ofUPDATING. The same goes formust-revalidate,proxy-revalidateandno-cache. For SWR with a separate edge TTL, sendmax-age+stale-while-revalidateand set the edge TTL with a Cache Rule, or put the edge policy inCloudflare-CDN-Cache-Control(Cloudflare only, not forwarded) orCDN-Cache-Control(forwarded to downstream CDNs).
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:
# 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 }inwrangler.jsonc, returnCache-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.propsand Worker version, not hostname. Zone Cache Rules and zone purges do not apply; purge from the Worker withctx.cache.purge({ tags | pathPrefixes | purgeEverything })or soft-purge withctx.cache.invalidate(...)(also importable ascachefromcloudflare: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.putis incompatible with Tiered Cache), no request collapsing, andmatch/putignorestale-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: trueinnext.config.ts. Newcreate-next-appprojects ship with it andpartialPrefetching: trueenabled. SetpartialPrefetchingexplicitly (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 withcacheLife()/cacheTag(); anything uncached must sit inside<Suspense>or the dev overlay flags a blocking route. With Cache Components on,GETRoute Handlers follow the same prerendering model as pages. - Previous model (Cache Components off):
fetchopt-in caching plusunstable_cache, invalidated withrevalidateTag/revalidatePath. Still supported in 16 and still what most existing codeAmani apps run.
// 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.
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();
}
| Profile | stale (client) |
revalidate (background refresh) |
expire (hard limit) |
|---|---|---|---|
default |
5 min | 15 min | never |
seconds |
30 s | 1 s | 1 min |
minutes |
5 min | 1 min | 1 h |
hours |
5 min | 1 h | 1 day |
days |
5 min | 1 day | 1 week |
weeks |
5 min | 1 week | 30 days |
max |
5 min | 30 days | 1 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:
| Directive | Store | Notes |
|---|---|---|
"use cache" |
Prerendered static shell + per-instance in-memory LRU at runtime | On 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 Vercel |
Durable 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 only | May 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:
// 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_cacheis 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 keepunstable_cacheonly 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.
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.
"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. AnycacheLifeprofile 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,
cacheTagalso tags the CDN entry, andrevalidateTag/updateTag/revalidatePathpurge the CDN, Runtime Cache and Data Cache together. They do not expire entries you wrote yourself withgetCache().set()(useexpireTag). 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:
| Store | Best for | Durability | Watch out for |
|---|---|---|---|
| Upstash Redis (codeAmani default) | Cache-aside, idempotency keys, locks, rate limits; any host | Durable until TTL | Every op is a billed command; REST round trip |
| Vercel Runtime Cache | Read-through cache inside Vercel Functions | Regional, LRU-evicted, survives deploys, split preview/prod | 2 MB/item; Hobby projects share one cache; not for data that must stay its full TTL |
| Workers KV | Read-heavy config/catalog data at Cloudflare's edge | Durable | Eventually consistent (60 s+ across locations); 1 write/s per key |
| Vercel Global Config (formerly Edge Config) | Feature flags, redirects, IP blocklists read on every request | Durable, replicated with your functions | A 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.
// 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:
// 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
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 | |
|---|---|---|
| Idea | Expire after N seconds, hope that's often enough | Invalidate the instant the data actually changes |
| Staleness | Up to the full TTL | Near-zero |
| Best for | Data that drifts predictably (exchange rates, leaderboards) | Data with a clear write event (a vendor edits a price) |
| Cost | Wasted refreshes / stale windows | Must wire every writer to invalidate |
| Tools | CDN s-maxage, cacheLife, next.revalidate, Redis ex |
updateTag/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, Cloudflareinvalidate_cacheandctx.cache.invalidate()serve stale while refreshing; hard deletes cause a cold-cache stampede on hot tags. - Fingerprint immutable assets.
app-[hash].jswithimmutable, max-age=31536000never 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 NXsingle-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:
| Symptom | Check | Header / signal |
|---|---|---|
| Browser shows old page | DevTools → Network → Disable cache | Cache-Control, Age |
| Edge serving stale | Response header | x-vercel-cache (HIT/STALE/REVALIDATED) · CF-Cache-Status (HIT/UPDATING/EXPIRED) |
| Vercel never caches a route | Runtime logs cache reason | Vary: Cookie, Set-Cookie, private, Authorization |
| Cloudflare SWR not kicking in | CF-Cache-Status: EXPIRED instead of UPDATING |
s-maxage or must-revalidate in the header |
| Next.js route won't update | Did 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 Vercel |
Per-instance memory on serverless | Switch hot paths to use cache: remote |
| Redis returns old value | redis.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):
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:
| Variable | Example | Purpose |
|---|---|---|
CLOUDFLARE_ZONE_ID |
023e105f4ecef8ad9ca31a8372d0c353 |
Zone for purge_cache / invalidate_cache |
NEXT_PRIVATE_DEBUG_CACHE |
1 |
Verbose 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 getimmutable, and personalised responses areprivate/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 anETag304 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.idby default (SET stripe:evt:<id> 1 NX EX 86400after signature verification). M-Pesa only on Kenya-targeted projects: dedupe onCheckoutRequestIDand 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-Tagand 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 acacheLife, useupdateTagin Server Actions andrevalidateTag(tag, "max")in webhook Route Handlers. Never ship the deprecated one-argumentrevalidateTag. - 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, neverNEXT_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/andopen-ai/guides. - Edge Config is now Global Config. New code imports
@vercel/global-config; existing@vercel/edge-configprojects keep working with no deadline, but upgrade before connecting a new store.
Official docs:
- https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Caching
- https://nextjs.org/docs/app/getting-started/caching
- https://nextjs.org/docs/app/api-reference/directives/use-cache
- https://nextjs.org/docs/app/guides/caching-without-cache-components
- https://vercel.com/docs/caching
- https://vercel.com/docs/caching/cdn-cache
- https://vercel.com/docs/caching/runtime-cache
- https://developers.cloudflare.com/cache/concepts/cache-control/
- https://developers.cloudflare.com/workers/cache/
- https://upstash.com/docs/redis/sdks/ts/getstarted