Skip to content

A Cache Needs an Expiry Policy

The Course
•
18 min study

The decision

A shared cache entry is a stored representation with an owner and lifetime. Decide whether expired data may be served, which writes invalidate it, and whether the value is public enough to share.

Read, predict, run

The model receives a timestamp rather than reading Date.now(), so a test can hit the boundary exactly. It treats the expiry moment itself as stale:

JavaScript
export function run({ now, expiresAt }) {
  return now < expiresAt ? "fresh" : "stale";
}

Before pressing Run, predict what run returns for {"now": 9, "expiresAt": 10} and {"now": 10, "expiresAt": 10}, from the code above. Write your answers down first: after Run, the case table shows the expected values beside the actual ones.

A Cache Needs an Expiry Policy Next.js · 5 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Review Queue · Practice lab</strong> </header> {children} </body> </html> ); } import Cases from "./Cases.jsx"; export default function Page() { return ( <main> <h1>A Cache Needs an Expiry Policy</h1> <p> Read the input and predict the result before running. Change lib/contract.js for the exercise. </p> <Cases /> </main> ); } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } export function run({ now, expiresAt }) { return now < expiresAt ? "fresh" : "stale"; } export const examples = [ [{ now: 9, expiresAt: 10 }, "fresh"], [{ now: 10, expiresAt: 10 }, "stale"], ];
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Check your prediction
  • Input {"now": 9, "expiresAt": 10} → "fresh".
  • Input {"now": 10, "expiresAt": 10} → "stale".

The case table computes these results on the server side of the simulation. It compares values; it does not prove a production deployment or database works.

The same three decisions in Next.js 16

Every cache answers three questions: who may share an entry (scope), how long it stays fresh (lifetime), and which write ends it early (invalidation). Next.js 16's Cache Components answer them in code. The simulator can't run this, so read it; the capstone on Day 7 runs on a real server. It needs cacheComponents: true in next.config.js:

JavaScript
// lib/reviews.js
import { cacheLife, cacheTag } from "next/cache";

export async function publicReviewCounts() {
  "use cache"; //                       scope: one entry, shared by every caller
  cacheLife("minutes"); //              lifetime: a built-in profile
  cacheTag("review-counts"); //         a name that writes can invalidate
  return db.query("SELECT status, count(*) FROM reviews GROUP BY status");
}
JavaScript
// app/reviews/actions.js
"use server";
import { updateTag } from "next/cache";

export async function approveReview(id, version) {
  // ...authorize and write, as on Days 1 and 2...
  updateTag("review-counts"); //        invalidation: the next read recomputes
}
DecisionThe contract aboveNext.js 16
Scopeprivate means bypass"use cache" shares one entry for the same arguments; it may not read cookies() or headers(), which throws
Lifetimenow < expiresAtcacheLife("minutes"), a named profile, or an object with stale, revalidate and expire in seconds
Invalidationa later expiresAtcacheTag names the entry; updateTag in a Server Action expires it so the person who wrote sees the change; revalidateTag(tag, "max") elsewhere refreshes it in the background
Never cachedbypassleave out "use cache"; await connection() from next/server marks a component as rendered for every request

The scope row is the one that leaks data. Because a "use cache" function can't read the request, its result can only depend on its arguments, so the same arguments must mean the same answer for everyone. Per-user data, such as "my reviews", is read outside the cache, or passed in as an argument that really identifies the user, never looked up inside.

The failure to avoid

The simulator runs pages dynamically and can't prove a production cache hit. Don't infer static rendering, revalidation timing or user isolation from this lab.

Compare a shared cache keyed by URL alone with a private bypass. Ada loads /reviews/mine; the cache stores her list under that URL; Grace loads the same URL and receives Ada's list. Marking the representation private and bypassing the shared cache for it makes that impossible, at the cost of a slower page.

Exercise

Extend the contract

A value marked private must return bypass even when fresh. Keep the normal expiry rule for public values.

Edit lib/contract.js, then rerun the original cases. If the requested rule changes an earlier result, update that expected value deliberately. Keep the other cases. Add the acceptance cases to examples so the preview checks them too.

  • Input {"now": 1, "expiresAt": 10, "private": true} must return "bypass".
Your working space Next.js · 5 files
import "./globals.css"; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <header> <strong>Review Queue · Practice lab</strong> </header> {children} </body> </html> ); } import Cases from "./Cases.jsx"; export default function Page() { return ( <main> <h1>A Cache Needs an Expiry Policy</h1> <p> Read the input and predict the result before running. Change lib/contract.js for the exercise. </p> <Cases /> </main> ); } import { run, examples } from "@/lib/contract.js"; const text = (value) => JSON.stringify(value) ?? "undefined"; export default async function Cases() { const results = await Promise.all( examples.map(async ([input, expected]) => { // Record the input before running, to show whether run changed it. const before = text(input); const actual = await run(input); return { input: before, expected, actual, kept: text(input) === before, pass: text(actual) === text(expected), }; }), ); return ( <section> <h2>Executable cases</h2> <p> Checks: {results.filter((row) => row.pass).length}/{results.length}{" "} passed </p> <table> <thead> <tr> <th>Input</th> <th>Expected</th> <th>Actual</th> <th>Input kept</th> </tr> </thead> <tbody> {results.map((row, i) => ( <tr key={i}> <td> <code>{row.input}</code> </td> <td> <code>{text(row.expected)}</code> </td> <td className={row.pass ? "pass" : "fail"}> <code>{text(row.actual)}</code> </td> <td className={row.kept ? "pass" : "fail"}> {row.kept ? "yes" : "no: run changed it"} </td> </tr> ))} </tbody> </table> </section> ); } body { font: 16px/1.5 system-ui; margin: 0; color: #182b3c; background: #f4f8fc; } header, main { max-width: 900px; margin: auto; padding: 20px; } header { border-bottom: 1px solid #cbd5e1; } a { color: #075985; } button, input, textarea, select { font: inherit; padding: 8px; margin: 4px; } button { cursor: pointer; } table { border-collapse: collapse; width: 100%; } th, td { padding: 10px; border: 1px solid #cbd5e1; text-align: left; vertical-align: top; } pre, code { white-space: pre-wrap; overflow-wrap: anywhere; } .pass { color: #166534; } .fail, [role="alert"] { color: #a01818; } section { margin: 16px 0; padding: 12px; background: white; border-radius: 8px; } nav { display: flex; gap: 16px; } export function run({ now, expiresAt }) { return now < expiresAt ? "fresh" : "stale"; } export const examples = [ [{ now: 9, expiresAt: 10 }, "fresh"], [{ now: 10, expiresAt: 10 }, "stale"], ];
Runs with real Next.js on your computer: unzip, then npm install and npm run dev.
Add and remove files here; write their code in the editor.
Hint 1: the idea

Whether something may be shared at all comes before how long it stays fresh. A private representation is never served from a shared cache, fresh or not.

Hint 2: a first step

Classify the representation before deciding whether its cached copy is usable.

Show one solution

Replace the exported run function and any constants shown here; keep the examples export underneath it. Compare the result with your own approach.

JavaScript
export function run({ now, expiresAt, private: isPrivate }) {
  return isPrivate ? "bypass" : now < expiresAt ? "fresh" : "stale";
}

The private check comes first, so a fresh private entry is still bypass; freshness only matters for values that may be shared. The destructuring renames private to isPrivate because private is reserved in strict-mode code. Treating private data as always stale would still store it, which is the leak you're avoiding.

Explain it without the code

For the Review Queue's item list, write whether it's public or private, and which write must invalidate it.

Going further

Read the Next.js reference for use cache, cacheLife and updateTag. The preview runs code-playpad's Next.js simulation. Real caching, hydration, authentication and persistence require the real-server checks described on Day 7.

Was this article helpful?

Your response is saved on this device.