Skip to content

Private Cache Keys Need the Whole Identity

The Course
•
18 min study

The decision

A cache can return the wrong user’s data faster than a database can. Before adding a shared cache, define its scope, lifetime, identity and invalidation policy.

Read, predict, run

The model builds an unambiguous key from tenant, actor and record. JSON encoding avoids delimiter collisions. This is an identity exercise, not an implementation of Next.js caching. Private data may be better left uncached:

JavaScript
export function run({ tenantId, actorId, id }) {
  return JSON.stringify([tenantId, actorId, id]);
}

Before pressing Run, predict what run returns for {"tenantId": "a", "actorId": "ada", "id": 1}, from the code above. Write your answers down first: after Run, the case table shows the expected values beside the actual ones.

Private Cache Keys Need the Whole Identity 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>Private Cache Keys Need the Whole Identity</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({ tenantId, actorId, id }) { return JSON.stringify([tenantId, actorId, id]); } export const examples = [ [{ tenantId: "a", actorId: "ada", id: 1 }, '["a","ada",1]'], ];
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 {"tenantId": "a", "actorId": "ada", "id": 1} → "[\"a\",\"ada\",1]".

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 failure to avoid

A correct key alone is not authorization. Validate access before returning a cached result too, and re-check when permissions or session state change.

Compare a delimiter key, tenantId + ":" + actorId + ":" + id, with the JSON array. Tenant "a:b" with actor "c", and tenant "a" with actor "b:c", both produce a:b:c:1: one user can be served the other's entry. The JSON version produces two different strings, because each part is quoted.

Exercise

Extend the contract

Add a schema version of 2 at the start of the key to keep old and new response shapes separate.

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 {"tenantId": "a", "actorId": "ada", "id": 1} must return "[2,\"a\",\"ada\",1]".
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>Private Cache Keys Need the Whole Identity</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({ tenantId, actorId, id }) { return JSON.stringify([tenantId, actorId, id]); } export const examples = [ [{ tenantId: "a", actorId: "ada", id: 1 }, '["a","ada",1]'], ];
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

The cached value's shape is part of its identity too. When the response format changes, an old entry stored under the same key would be served to the new code.

Hint 2: a first step

Version the representation explicitly instead of relying on a deployment to clear every cache.

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({ tenantId, actorId, id }) {
  return JSON.stringify([2, tenantId, actorId, id]);
}

Putting the version first makes every new key differ from every old one, so new code never reads an entry written in the old format, and old entries simply expire. The number is part of the same JSON array, so it keeps the collision-free encoding. Clearing the cache at every deploy would also work, but only as long as every deploy remembers to do it.

Explain it without the code

Name one field that, left out of this key, would let a cached answer reach the wrong person, and one that's safe to leave out.

Going further

Read the Next.js guide for the framework boundary around this rule. 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.