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 cacheTag feeds the CDN, Runtime Cache and Data Cache, and revalidateTag purges them together), and Next.js 16's use cache is per-instance memory unless you say use 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 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:

// 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 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-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).

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

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:

// 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_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.

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");
}

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:

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


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

Official docs: