Redis eviction for a Next.js 16 cache handler: use volatile-lru
If a Next.js 16 cache handler keeps both cache entries and tag revalidation timestamps in Redis, don't run that Redis with an allkeys-* eviction policy. Under memory pressure Redis can evict the tag timestamps, and every entry cached before the last revalidation then looks fresh again. Store entries with a TTL, store tag state without one, and set maxmemory-policy to volatile-lru so Redis only ever evicts entries.
What a Redis cache handler for "use cache" stores
Next.js 16 lets you replace the storage behind "use cache" with your own module through cacheHandlers in next.config.js. The handler has to do two jobs. It stores cache entries, each with the tags it was rendered with and the time it was created. And it remembers when each tag was last revalidated, so that get can throw away an entry created before its tag changed, and getExpiration can tell Next.js the latest revalidation time for a set of tags.
When several instances share one Redis, both kinds of data have to live there. Entries are the obvious part. The tag timestamps matter just as much: when an editor publishes a change and the CMS calls a revalidation route on one instance, the other instances only find out because that instance wrote a new timestamp for the tag into Redis.
The two kinds of data behave very differently. An entry is disposable: lose it and the next request renders the page again. A tag timestamp is a record that something changed. Lose it and the cache forgets that the change ever happened.
Why allkeys-lru is the wrong policy here
In an earlier article on a fail-fast Redis cache handler I suggested allkeys-lru. That advice holds for a handler that stores only entries, where a missing key only costs a render. It stops holding the moment tag state lives in the same Redis.
With any allkeys-* policy, Redis picks eviction candidates from every key once it reaches maxmemory. LRU in Redis is approximate: it samples a handful of keys and evicts the least recently used of the sample. A key you read often is unlikely to go, but nothing protects it, and allkeys-lfu or allkeys-random make the odds worse. If the tag manifest is a single hash, one eviction removes every revalidation at once.
What happens next is quiet. Nothing errors. An instance that loads the manifest after the eviction finds no timestamp for a tag, so get sees no reason to discard an entry created before the last publish, and getExpiration reports that the tags were never revalidated. The old page is served as fresh until the entry's own TTL runs out, which for content that is meant to live a long time can be days.
How volatile-lru keeps the tag timestamps safe
The volatile-* policies only consider keys that have an expiry set. So the split is simple:
- Write every cache entry with
EX, using the entry'sexpireas the TTL. Redis would drop it then anyway, and it makes the entry an eviction candidate. - Write tag timestamps without an expiry, so they are never candidates.
- Set
maxmemory-policy volatile-lru.
Here is a minimal sketch of the storage side. It isn't a full handler, but it shows where the TTL goes and where it deliberately doesn't:
// cache-store.js
const Redis = require("ioredis");
const redis = new Redis(process.env.REDIS_URL);
const ENTRY = (key) => `cache:entry:${key}`;
const TAGS = "cache:tags";
// Entries are disposable: give each a TTL so volatile-lru may evict it.
async function writeEntry(key, record) {
const ttl = Math.max(1, Math.ceil(record.expire));
await redis.set(ENTRY(key), JSON.stringify(record), "EX", ttl);
}
// Tag timestamps record that content changed: no TTL, never evicted.
async function markTagsExpired(tags, now = Date.now()) {
const pipe = redis.pipeline();
for (const tag of tags) pipe.hset(TAGS, tag, String(now));
await pipe.exec();
}
async function latestExpiration(tags) {
if (tags.length === 0) return 0;
const values = await redis.hmget(TAGS, ...tags);
return Math.max(0, ...values.map((v) => Number(v) || 0));
}
module.exports = { writeEntry, markTagsExpired, latestExpiration };
And the Redis side, in redis.conf or as arguments to the server:
maxmemory 512mb
maxmemory-policy volatile-lru
Many Redis container images read the policy from an environment variable instead, so check how yours is configured rather than assuming the server default. In my case the whole fix was one environment variable on the Redis container, which is why it is easy to miss in review.
What volatile-lru costs you
There is one trade-off to know about. If memory fills up with keys that have no expiry, a volatile-* policy has nothing to evict and behaves like noeviction: write commands fail with an OOM command not allowed error. For a cache handler that already treats Redis errors as a cache miss, that is a render rather than an outage, and it is far better than silently serving stale pages. But it means the keys without a TTL have to stay small.
The tag hash is small, but it only ever grows. Every tag that has been revalidated stays in it. Once a tag's timestamp is older than the longest expire any entry can have, no entry that predates it can still exist, so it can't change any answer. A periodic job that removes those fields keeps the hash bounded. I'd add that before the number of distinct tags gets large, for example when tags include per-page paths.
How to check what your Redis is doing
Ask the running server rather than trusting the config file:
redis-cli CONFIG GET maxmemory-policy
redis-cli CONFIG GET maxmemory
redis-cli INFO stats | grep evicted_keys
A non-zero evicted_keys under an allkeys-* policy means Redis has already been choosing what to forget. Some managed Redis services disable CONFIG; set the policy through the provider's parameter settings there instead. It is also worth checking that no key the handler writes without a TTL gets one by accident, and that every entry write includes one, because an entry without a TTL can never be evicted under volatile-lru.
Key takeaways
- A Next.js 16 cache handler that shares tag revalidation timestamps through Redis must never let Redis evict them, or old entries come back as fresh without any error.
- Give cache entries a TTL from their
expirevalue and store tag timestamps without one, so the two kinds of data are separable by Redis. - Use
maxmemory-policy volatile-lruso eviction only ever touches keys with a TTL. - Under a
volatile-*policy, keys without a TTL can fill memory and cause write errors, so keep the tag hash small and prune timestamps older than the longest entry lifetime. - Check the live server with
CONFIG GET maxmemory-policyandevicted_keysrather than assuming the default.