fix(cache): true LRU, stale-while-revalidate and cross-process invalidation
The in-process cache was a FIFO of 500 entries that was never touched on a read, so a key polled on every request could be evicted by an unrelated burst of dynamic keys. That looked exactly like the cache being cleared at random, and it is what made the site fall back to the database unpredictably. - Evict least-recently-used instead, and raise the default budget to 2000 (CACHE_MEMORY_MAX_ENTRIES). Reading a key now marks it as used, so a hot key only leaves when a hotter one takes its place. - Add opt-in stale-while-revalidate (CachedOptions.staleMs). The grace window lives on the entry, so one call site opting in protects every reader of that key. A failed background refresh keeps serving the last good value instead of falling through to the origin, and is reported once rather than per read. - Invalidate across processes. invalidateKey() now clears memory, deletes the Redis key and publishes a signal, so a value written by one process is no longer served stale by the others for the rest of its TTL. A failed Redis delete no longer skips the broadcast. - Guard against a refresh that started before an invalidation writing its outdated result back into the cache. - Read the news revision at most once a second per process instead of on every call, with a pub/sub signal to drop the local copy when it rotates. A Redis outage now degrades to the in-process cache rather than to no cache at all. - Warm the hot public keys on boot, so the first visitors after a deploy do not each pay for a miss. - Count hits, misses, stale serves, errors and evictions per key, exposed at GET /api/admin/devops/cache. Without it a wrong REDIS_URL, a full budget and a dead origin all look identical from the outside. - Enforce the imaging cache budget for real: records are .img/.json pairs, so the old cap counted files and never removed anything while entries were fresh. Sweeps are throttled per directory and prune to a low-water mark. - Cap the JWT version map, and stop per-test scratch roots from littering the runtime imaging cache. Public read-only endpoints get grace windows; admin, account and auth data deliberately stays fresh. Redis TTLs get a little jitter so keys written together no longer expire together. 3209 tests pass. next build could not be verified on this host: the optimized build is OOM-killed before prerender, so this has not run in a real Next runtime yet.
This commit is contained in:
1 parent
f490fcc9da
commit
203399aab7
43 files changed
+1737
-212
No files matched your search
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -1,28 +1,83 @@
|
||||
import "server-only";
|
||||
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { cached } from "@/lib/cache";
|
||||
import { onCacheSignal, publishCacheSignal } from "@/lib/cache-invalidation";
|
||||
import { logger } from "@/lib/logger";
|
||||
import { redis } from "@/lib/redis";
|
||||
|
||||
const REVISION_KEY = "cms:news:revision";
|
||||
|
||||
/** News entries are namespaced by a revision, so a new revision drops them all. */
|
||||
const REVISION_CHANNEL = "cache:news-revision";
|
||||
|
||||
// The revision is read from Redis at most this often per process. Reading it on
|
||||
// every call (as this used to) put a Redis round-trip in front of the in-process
|
||||
// fast path, which is exactly what the cache exists to avoid. A published article
|
||||
// still shows up immediately: the invalidation signal clears this copy, and the
|
||||
// window is only the fallback for when pub/sub is unavailable.
|
||||
const REVISION_TTL_MS = 1_000;
|
||||
|
||||
let revision: { value: string; expiresAt: number } | null = null;
|
||||
let inFlightRevision: Promise<string> | null = null;
|
||||
|
||||
async function readRevision(): Promise<string> {
|
||||
const now = Date.now();
|
||||
if (revision && revision.expiresAt > now) return revision.value;
|
||||
inFlightRevision ??= (async () => {
|
||||
try {
|
||||
return (await redis?.get(REVISION_KEY)) ?? "0";
|
||||
} catch {
|
||||
return "0";
|
||||
} finally {
|
||||
inFlightRevision = null;
|
||||
}
|
||||
})();
|
||||
const value = await inFlightRevision;
|
||||
revision = { value, expiresAt: Date.now() + REVISION_TTL_MS };
|
||||
return value;
|
||||
}
|
||||
|
||||
function setRevision(value: string): void {
|
||||
revision = { value, expiresAt: Date.now() + REVISION_TTL_MS };
|
||||
}
|
||||
|
||||
// Another process published new news: forget the revision so the next read picks
|
||||
// up the new one instead of serving entries under the old namespace.
|
||||
onCacheSignal(REVISION_CHANNEL, () => {
|
||||
revision = null;
|
||||
});
|
||||
|
||||
export async function cacheNews<T>(
|
||||
key: string,
|
||||
ttlMs: number,
|
||||
query: () => Promise<T>,
|
||||
): Promise<T> {
|
||||
if (!redis || redis.status === "end") return query();
|
||||
let revision: string;
|
||||
try {
|
||||
revision = (await redis.get(REVISION_KEY)) ?? "0";
|
||||
} catch {
|
||||
return query();
|
||||
}
|
||||
return cached(`news:${revision}:${key}`, ttlMs, query);
|
||||
// Every caller of cacheNews is a public news read, so the grace window lives
|
||||
// here rather than at each call site. Publishing an article rotates the
|
||||
// revision, which drops these entries immediately; the window only matters
|
||||
// when that signal cannot be delivered.
|
||||
const options = { staleMs: ttlMs };
|
||||
// Without Redis the revision cannot be shared, so fall back to a fixed one:
|
||||
// the in-process cache still works, which is far better than hitting the
|
||||
// database on every request for the whole duration of a Redis outage.
|
||||
if (!redis || redis.status === "end")
|
||||
return cached(`news:0:${key}`, ttlMs, query, options);
|
||||
return cached(`news:${await readRevision()}:${key}`, ttlMs, query, options);
|
||||
}
|
||||
|
||||
async function rotateRevision(): Promise<string> {
|
||||
const next = randomUUID();
|
||||
if (redis) await redis.set(REVISION_KEY, next);
|
||||
setRevision(next);
|
||||
await publishCacheSignal(REVISION_CHANNEL, next);
|
||||
return next;
|
||||
}
|
||||
|
||||
export async function invalidateNewsCache(): Promise<void> {
|
||||
if (!redis || redis.status === "end") return;
|
||||
try {
|
||||
await redis.set(REVISION_KEY, randomUUID());
|
||||
await rotateRevision();
|
||||
} catch (error) {
|
||||
logger.error("News saved but public cache invalidation failed", {
|
||||
module: "news",
|
||||
@@ -36,5 +91,5 @@ export async function refreshNewsCacheForDelivery(): Promise<void> {
|
||||
if (!redis) return;
|
||||
if (redis.status === "end")
|
||||
throw new Error("News cache connection is closed");
|
||||
await redis.set(REVISION_KEY, randomUUID());
|
||||
await rotateRevision();
|
||||
}
|
||||
Reference in new issue
Block a user