Mutation, invalidation, and freshness
Follow a write from durable storage through server caches and the current browser, choosing immediate freshness or background refresh deliberately.
What you will be able to do
- Distinguish a successful write from a fresh displayed view.
- Choose updateTag, revalidateTag and revalidatePath by scope and freshness needs.
- Test invalidation with multiple views and failed writes.
Before this lesson
A write and every view of it are separate events
Updating a product in the database changes the source of truth. A catalogue list, product page, navigation badge and browser query cache can still hold earlier representations. Mutation success therefore does not automatically prove that the current screen is fresh. Draw the representations that depend on the changed record and decide which ones need immediate consistency versus eventual refresh.
Perform the durable write before announcing success and invalidating dependent views. If the write fails, clearing caches as though new data exists can hide the real error and cause unnecessary work. If the write succeeds but invalidation fails, the system has a different partial-failure state that needs observability and possibly retry. Server actions make common flows convenient, but they do not remove the need to understand these stages.
Choose tag invalidation from the desired read behavior
updateTag is designed for a Server Action that requires read-your-own-writes: after the user changes a record, the next relevant read should wait for fresh data rather than receive the old cached value. revalidateTag with the max profile supports stale-while-revalidate, where a stale value may be served while the replacement is obtained. That can suit background catalogue updates but may be surprising immediately after the user edits their own item.
The caller matters as well as freshness. updateTag belongs to Server Actions; a webhook Route Handler should use an applicable revalidateTag policy. Do not call these APIs interchangeably or copy a single-argument legacy example without understanding its behavior and version. Choose tags that represent actual dependencies, such as one product and the catalogue listing, and invalidate only what the mutation makes stale.
- The sample demonstrates invalidation and navigation only. It intentionally performs no database write. A real mutation must authenticate, authorize, validate and commit its write before this invalidation sequence.
Server execution
'use server';
import { updateTag } from 'next/cache';
import { redirect } from 'next/navigation';
export async function finishPublicCatalogueDemo(formData: FormData) {
const productId = String(formData.get('productId') ?? '');
if (!/^[a-z0-9-]+$/.test(productId)) return { error: 'Invalid product ID' };
updateTag(`product:${productId}`);
updateTag('public-catalog');
redirect(`/catalog/${encodeURIComponent(productId)}`);
}Path scope and the current browser are different concerns
revalidatePath targets a route path or specified layout scope. Tags can describe data reused by several routes. If the same product appears in a category page and a saved-items page, a data tag can communicate that shared dependency more directly than remembering every URL. Path invalidation remains useful when the intended unit is the rendered route. Decide from the dependency graph, not from whichever function name you remember first.
A browser router refresh requests an updated server representation for the current route, but does not by itself mean all persistent server caches were invalidated. A client data library can also hold its own cache that needs reconciliation or invalidation. The next view can therefore still look stale if you refresh the wrong layer. Keep server cache mutation and client presentation updates explicit in your explanation.
Test the consistency promise, not only the function call
An assertion that updateTag was invoked proves only that code called a function. A stronger test reads the old value, performs an allowed mutation, then reads every affected view and checks the promised behavior. Include an unauthorized write and a failing write, verifying that neither is presented as a successful update. For background refresh, distinguish permitted stale output from eventual fresh output instead of demanding an impossible instant guarantee.
The kata models immediate eviction of entries tagged with any changed dependency. It intentionally does not model Next.js stale-while-revalidate scheduling. In the real /cache experiment, inspect the configured policy and record whether the first subsequent request waits for new data or may receive the old value. In distributed deployment, verify shared tag coordination too; one process invalidating its memory is not proof that every instance is fresh.
Misconceptions to replace
Compare the tempting shortcut with the model you can verify in code.
- CLAIM TO CHALLENGErouter.refresh guarantees every persistent server cache was invalidated.
- A more accurate model
It requests refreshed route output, but the server can still reuse cached data. Invalidate the relevant server dependency and reconcile any separate client cache.
- How to check it
N10, N11 and N15 support the distinction between route refresh and cached data invalidation.
- CLAIM TO CHALLENGECalling tag invalidation on one process proves all deployment instances are fresh.
- A more accurate model
Multiple instances need a shared invalidation or cache coordination strategy. Local memory behavior is not distributed evidence.
- How to check it
N25 describes shared cache and multi-instance tag coordination; the deployment lesson expands this operational requirement.
Mistakes to catch in your own code
- A successful database write does not automatically refresh every derived representation.
- Do not use updateTag in a Route Handler.
- Do not claim router.refresh invalidates every server cache.
Write it by hand
JavaScript logic playground
Evict entries with changed dependencies
Implement solve(input). This sandbox runs the lesson's logic with FrontendX's isolated code runner. Next.js server behavior is verified in the project lab below.
- Implement solve({entries,changedTags}). Each entry has key and tags. Remove an entry when any tag appears in changedTags.
- Return {kept,evicted} arrays of keys in original entry order. Duplicate changed tags have no additional effect. Untagged entries remain.
- This is an immediate-eviction model for dependency reasoning. It is not an implementation of Next.js revalidateTag scheduling.
Tab moves to the next control. Use spaces to indent and return your answer from solve. Console output is not retained.
Inspect 4 test cases
- One product has several views
Input
{ "entries": [ { "key": "detail-a", "tags": [ "product:a" ] }, { "key": "list", "tags": [ "catalog", "product:a" ] }, { "key": "detail-b", "tags": [ "product:b" ] } ], "changedTags": [ "product:a" ] }Expected
{ "kept": [ "detail-b" ], "evicted": [ "detail-a", "list" ] } - No changes
Input
{ "entries": [ { "key": "a", "tags": [ "catalog" ] } ], "changedTags": [] }Expected
{ "kept": [ "a" ], "evicted": [] } - Duplicate tags and untagged data
Input
{ "entries": [ { "key": "a", "tags": [ "catalog" ] }, { "key": "legal", "tags": [] } ], "changedTags": [ "catalog", "catalog" ] }Expected
{ "kept": [ "legal" ], "evicted": [ "a" ] } - Unrelated invalidation
Input
{ "entries": [ { "key": "a", "tags": [ "product:a" ] } ], "changedTags": [ "product:b" ] }Expected
{ "kept": [ "a" ], "evicted": [] }
Reveal the worked solution and reasoning
function solve(input) {
const changed = new Set(input.changedTags);
const kept = [];
const evicted = [];
for (const entry of input.entries) {
if (entry.tags.some(tag => changed.has(tag))) evicted.push(entry.key);
else kept.push(entry.key);
}
return { kept, evicted };
}An entry depends on all its listed tags, so a change to any one is sufficient to make that representation unsuitable under this policy.
The test preserves unaffected entries and order. Actual framework freshness and distributed invalidation require the real runtime lab.
Verify it in a real Next.js application
Next.js application lab
Verify the shipped write and add an external invalidation path
Open the local application route /cache after starting the workbench. Follow the experiment and collect the evidence described below.
Make the change
- Inspect changePrice in app/actions.ts: it verifies the practice session and admin role, validates input, compares the product version, commits the file-store write and then calls updateTag("catalog").
- Run production, sign in as Ada and record the old price/version. Submit a new whole-rupee price, then compare the action response, /catalog/keyboard and /api/catalog?q=keyboard.
- Open an old form in another tab and submit after a newer write. Repeat the permissions check as Linus, whose role cannot change prices. Explain how rejected mutations differ from successful writes with delayed freshness.
- As an explicit extension, build a protected webhook-style Route Handler that calls revalidateTag("catalog", "max") after a validated public-fixture change. Compare its stale-while-revalidate behavior with the existing action's read-your-own-writes behavior.
- Rebuild after resetting practice data, as the README requires, so prerendered catalogue output does not retain the previous experiment's store state.
Check the behavior
- A successful action returns the committed product price and an increased version.
- An unauthorized or stale-version attempt reports failure without a successful data change.
- The existing action uses updateTag in a supported Server Action context.
- If the webhook extension is implemented, its verified entry point uses revalidateTag with an explicit freshness profile and its observed behavior matches that policy.
Review the application reasoning
The project already has a real teaching write plus invalidation. The lesson's smaller invalidation-only snippet remains illustrative and must not be mistaken for that complete action.
The file store serializes writes within one process. It does not establish distributed transaction or cache-coordination guarantees; the pure eviction kata likewise cannot prove Next.js freshness scheduling.
Open the project files and run instructions
A complete App Router application with catalogue routing, cart state, a task dashboard, practice sessions, tenant checks, cached data, hydration repairs, and HTTP streaming. Next.js 16.4.6 and React 19.3.0 are pinned in the project.
The playground opens a new editable copy. A local Node.js 22.14+ installation also runs the project. Use the local production build when measuring caching, streaming, or deployment behavior.
cd nextjs-interview-lab
npm ci
npm run dev
# In a second terminal
npm test
# Stop dev, then verify the production application
npm run build
npm start
# In a second terminal, install the test browser once
npx playwright install chromium
npm run test:e2eOpen http://localhost:3003. The project includes a credential-free practice account selector and a single-process file store. Those choices make experiments reproducible; the security and deployment lessons show what a production system needs.
Explain it in an interview
Give your answer aloud before opening the explanation. Then answer the follow-ups using your implementation as evidence.
01When would you choose updateTag instead of revalidateTag?
For a Server Action whose next read must reflect the user’s own completed write, updateTag provides immediate expiry semantics. revalidateTag with the max profile permits serving stale data while refreshing and works for suitable non-action callers such as Route Handlers. I state the desired consistency behavior before selecting the API.
Follow-up questions
- Which API fits a webhook?
- Why might stale-while-revalidate surprise an editing user?
- revalidateTagOfficial documentation
- updateTagOfficial documentation
02How do tags differ from path invalidation?
A path names a route or layout scope; a tag names a data dependency that may be shared by several routes. I use the dependency graph to choose a narrow but complete invalidation set. Invalidating a product tag can cover multiple consumers, whereas a path is appropriate when the route output is the intended unit.
Follow-up questions
- Which tags should a product update invalidate?
- How do you avoid invalidating the whole catalogue for an unrelated change?
- revalidateTagOfficial documentation
- revalidatePathOfficial documentation
03Why can router.refresh still show old data?
The browser can request a new server representation while the server reads a still-valid cached result. Refreshing the current route and invalidating persistent data caches are distinct operations. I trace the visible field back through its server and client cache owners and apply the appropriate update at the relevant layer.
Follow-up questions
- Could SWR or another client cache also remain stale?
- What evidence identifies the stale layer?
- Caching with Cache ComponentsOfficial documentation
- Caching without Cache ComponentsOfficial documentation
- revalidatePathOfficial documentation
04How would you test cache invalidation?
I would establish an old cached value, execute a permitted mutation, and observe the affected views under the documented freshness policy. I include failed and unauthorized writes and verify they do not report success. For several server instances I also check that invalidation reaches the shared coordination mechanism rather than just one process.
Follow-up questions
- What does a mocked API-call assertion fail to prove?
- How would you test an allowed stale response followed by refresh?
- revalidateTagOfficial documentation
- updateTagOfficial documentation
- Self-hosting Next.jsOfficial documentation
Check your understanding
Answer these without reopening the worked examples. The feedback explains the reasoning and the misconception behind each choice.
Your checkpoint
Loading your local progress.
Sources and further reading
- Caching with Cache ComponentsOfficial documentation
- Caching without Cache ComponentsOfficial documentation
- revalidateTagOfficial documentation
- updateTagOfficial documentation
- revalidatePathOfficial documentation
- Data securityOfficial documentation
- Self-hosting Next.jsOfficial documentation
- GreatFrontEnd Next.js interview questionsPublisher practice bank
- Next.js system-design practice promptsPublisher practice bank