You can find the project source code on GitHub.
When you self-host Next.js with next start or a Docker image, each instance
keeps its own cache in memory and on its local disk. Run two or more instances
behind a load balancer and they stop agreeing: one instance computes a value that
the others compute again, and revalidateTag() on one instance does not
invalidate the others. The cache is also lost on every restart.
Next.js solves this with cache handlers: a file you point to in
next.config.ts that stores cache entries wherever you want. This tutorial
writes cache handlers on top of Upstash Redis, so every instance reads and writes
the same cache and tag revalidation reaches all of them.
You do not need this on Vercel. Vercel already provides a shared cache for Next.js deployments. This tutorial is for apps you host yourself.
Next.js has two cache handler options. Both are stable; use the one that matches how your app caches, or both:
Option in next.config.ts | Caches | Since |
|---|---|---|
cacheHandlers (plural) | "use cache" and "use cache: remote" functions and components (Cache Components) | Next.js 16 |
cacheHandler (singular) | ISR pages, route handler responses, the fetch cache and unstable_cache | Next.js 14.1 |
The code below was tested with Next.js 16.4 and @upstash/redis 1.41.
Step 1: Create a database#
Create a Redis database in the Upstash Console or with the
Upstash CLI. Copy the REST URL and
REST token into a .env file in your project:
Install the client:
@upstash/redis talks to Redis over HTTP, so there is no connection to open
during next build and no connection pool to manage per instance.
Upstash Redis supports both protocols: the REST API over HTTP used here, and the
regular Redis protocol over TCP with a rediss:// URL (TLS is required). If you
already use a TCP client such as ioredis or node-redis, you can adapt the
handler to it; see Connect your client.
Step 2: Cache handler for "use cache"#
Create cache-handler.js in the project root:
How it works:
- Each entry is one Redis key,
next:cache:<key>, holding the entry as JSON with the rendered bytes in base64. The key gets a TTL from the entry’sexpire(set withcacheLife), so Redis deletes entries Next.js would no longer serve. - Tag invalidations are timestamps in one Redis hash,
next:tags.revalidateTag()andupdateTag()write to it throughupdateTags(), and every instance reads it once per request inrefreshTags(). An entry created before its tag was invalidated is treated as a miss (expired) or served once while it refreshes in the background (stale). - Soft tags, which back
revalidatePath(), are checked by Next.js throughgetExpiration(). - Errors in
get()turn into cache misses, so the app keeps working if Redis is unreachable.
Register the handler in next.config.ts. "use cache: remote" needs Cache
Components enabled:
The remote handler serves "use cache: remote". Plain "use cache" keeps
using the built-in in-memory cache, so you choose per function what goes to
Redis.
Step 3: Cache a slow query#
Mark a function with "use cache: remote", give it a tag with cacheTag and a
lifetime with cacheLife. The short lifetime below makes expiry easy to watch;
use longer values in production.
Add a route that invalidates the posts tag. { expire: 0 } expires the
entries immediately; "max" would serve the old value once while it refreshes
in the background.
updateTag("posts") in a Server Action works too and also reaches every
instance.
Step 4: Check it across two instances#
Build once and start two instances on different ports:
next start loads .env on its own. Then:
-
Shared cache. Open http://localhost:3001. The first load takes about two seconds. Open http://localhost:3002: it returns at once with the same
generatedAt, computed by the first instance. -
Expiry. Wait 30 seconds and reload either port. The entry has expired in Redis, so the page takes two seconds again and shows a new
generatedAt, which the other port then shares. -
Tag revalidation. Invalidate the tag on one instance and load the other:
http://localhost:3002 computes a new value instead of serving the old one.
In Redis you will see one next:cache:* key per cached call and the
next:tags hash. You can browse them in the Data Browser of the Upstash
Console.
Optional: ISR, fetch and unstable_cache#
Incremental Static Regeneration (export const revalidate, in apps without
Cache Components), the fetch cache, unstable_cache and prerendered page
shells go through a different option, cacheHandler (singular). Its entries
contain Buffer and Map values, so this handler serializes them itself and
turns off the client’s automatic JSON parsing.
Each entry is a next:isr:<key> key with a TTL from its expire, and each tag
is a Redis set of the keys that carry it. revalidateTag() and
revalidatePath() delete those keys, so every instance misses and renders
again. This handler expires tagged entries immediately for every
revalidateTag() profile.
Register it next to the other handler, and set cacheMaxMemorySize: 0 so
instances do not serve from their own in-memory copy:
If you use both handlers, put cacheHandler, cacheMaxMemorySize,
cacheComponents and cacheHandlers in the same config object.
Docker and other hosts#
- With
output: "standalone"innext.config.ts, Next.js copies the handler file and@upstash/redisinto.next/standalone, so the usual standalone Dockerfile works unchanged. Start it withnode server.js. - Pass
UPSTASH_REDIS_REST_URLandUPSTASH_REDIS_REST_TOKENas runtime environment variables on Railway, Render, Fly.io, Kubernetes or wherever the instances run. - Run the same build on every instance. Cache keys for
"use cache"include the build ID, so a new deploy starts with empty entries and the old ones expire through their TTL. If you build per instance, set the sameNEXT_SERVER_ACTIONS_ENCRYPTION_KEYand adeploymentIdfor all of them, as described in the Next.js self-hosting guide.
Costs and limits#
- Every cache read and write is a Redis command. With the
"use cache"handler, a request that reads the cache costs oneHGETALLfor the tags plus oneGETper cached call, and a miss adds aSET. See pricing to estimate your bill. - Remote caching pays off for slow or rate-limited work, such as database
queries and third-party APIs. For values that are cheap to compute or unique
per request, plain
"use cache"or no cache is cheaper. - Entries count toward your database size. Keep
expirefinite so old entries leave on their own. ISR pages with norevalidatehave no TTL and stay until their tag or path is revalidated. - The
next:tagshash keeps one or two fields per tag ever revalidated. That is small for a fixed set of tags; if you create tags per record (for examplepost-123), clear the hash from time to time.