Client caches and live synchronization
Give server data one clear owner while coordinating browser caches, mutations and incoming events.
What you will be able to do
- Distinguish local UI state from remote resource snapshots.
- Design complete client query keys and identity boundaries.
- Reconcile mutations and live events without stale overwrites.
- Choose polling, focus revalidation or a stream from product needs.
Several caches do not imply shared truth
A Next.js server cache, the router's route data and a browser query library cache are different stores. Invalidating one does not automatically make every other store display a new value. Start by deciding which layer owns each visible value. A live dashboard panel may use a client query cache, while a public product description is rendered from server data.
Local UI state such as an open tab or unsaved draft is not the same as a remote resource snapshot. Copying fetched data into a second useState without a reconciliation rule creates another source of truth. Keep the authoritative snapshot in its chosen cache and derive presentation, while storing only the user's independent editing intent separately.
Identity includes every input that changes a result
A query for products in tenant A with filter available must not share the same cache key as tenant B or a different filter. Include all result-defining inputs in a stable key, and define what happens when the authenticated identity changes. Never use a process-global server QueryClient to retain private user data across unrelated requests.
The example is an optional TanStack Query integration sketch, not a dependency bundled into the article runner. Install and configure the library in the real project before using it. The key factory itself is a pure shared function. A request-specific server client and a stable browser client have different lifetimes because their isolation responsibilities differ.
Shared application logic
export function catalogKey(tenantId: string, query: string, page: number) {
return ["catalog", tenantId, query.trim(), page] as const;
}Server execution
import "server-only";
import { QueryClient } from "@tanstack/react-query";
export function createRequestQueryClient() {
return new QueryClient({ defaultOptions: { queries: { staleTime: 30_000 } } });
}Update the layers that actually render the result
After a mutation, decide whether the confirmed response can replace a client cache entry or whether the query should refetch. If the same record also appears in server-rendered output, coordinate the appropriate server cache invalidation and route refresh. Avoid blindly invalidating every query when a precise key or tag can express the affected data.
An optimistic update must be reconciled with the server response. A delayed response for an old query should not overwrite the current filter or a newer version. Cancel obsolete work when possible, and also use identity or sequence checks because cancellation can race with completion. Reset private caches when the user changes rather than letting the next session inherit a prior snapshot.
Choose freshness from the user promise
Polling is simple when modest staleness is acceptable. Focus and reconnect revalidation help a tab that was idle become current again. A stream can reduce latency for updates, but introduces subscription lifecycle, replay, ordering and connection recovery. A WebSocket is not automatically required because a screen contains changing numbers.
For incoming events, define an entity ID, a monotonically ordered version within the relevant scope, and deletion semantics. If a deletion removes all version evidence, an older delayed update can resurrect the record. Retain a tombstone or another version watermark until the protocol guarantees older events cannot return. The exercise models this specific failure.
Make disagreement observable
Offline behavior requires a product decision: display the last successful snapshot, allow a queued draft, or block an operation that cannot be validated safely. Mark stale or pending data honestly. If edits are queued, define conflict handling and durable storage rather than assuming reconnect simply makes them correct.
Debug from the displayed value backward. Which component owns it? Which key selected it? Which response version last wrote it? Which mutation or event should have invalidated it? Inspect the server cache separately from the browser cache. A precise timeline makes synchronization bugs easier to explain than saying React did not rerender.
Misconceptions to replace
Compare the tempting shortcut with the model you can verify in code.
- CLAIM TO CHALLENGERemote snapshots should always be copied into another useState.
- A more accurate model
Store independent editing intent separately and avoid duplicate uncontrolled owners of the same server data.
- How to check it
The client cache ownership section traces which value each component reads.
- CLAIM TO CHALLENGEA stream guarantees exactly-once ordered updates.
- A more accurate model
Design replay, duplicate handling, meaningful versions and cancellation explicitly.
- How to check it
The HTML SSE standard and version/tombstone exercise.
Mistakes to catch in your own code
- Assuming updateTag invalidates an unrelated browser query library automatically.
- Omitting tenant or filter values from a query key.
- Creating a shared server cache client for all users.
- Resurrecting deleted records with an older delayed event.
Write it by hand
JavaScript logic playground
Merge versioned updates and tombstones
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.
- Input is {records,events}; each entry has {id,version,value}, and value=null means deleted.
- Apply an event only if its version is strictly greater than the stored version for that ID. Unknown IDs start below all supplied nonnegative versions.
- Return {live,versions}, both sorted by id. live excludes tombstones; versions includes every ID with its latest version.
Tab moves to the next control. Use spaces to indent and return your answer from solve. Console output is not retained.
Inspect 3 test cases
- Ignore an older update
Input
{ "records": [ { "id": "a", "version": 3, "value": "new" } ], "events": [ { "id": "a", "version": 2, "value": "old" } ] }Expected
{ "live": [ { "id": "a", "version": 3, "value": "new" } ], "versions": [ { "id": "a", "version": 3 } ] } - Do not resurrect a deletion
Input
{ "records": [ { "id": "a", "version": 1, "value": "item" } ], "events": [ { "id": "a", "version": 3, "value": null }, { "id": "a", "version": 2, "value": "older" } ] }Expected
{ "live": [], "versions": [ { "id": "a", "version": 3 } ] } - Insert and sort independent records
Input
{ "records": [], "events": [ { "id": "b", "version": 1, "value": 2 }, { "id": "a", "version": 1, "value": 1 } ] }Expected
{ "live": [ { "id": "a", "version": 1, "value": 1 }, { "id": "b", "version": 1, "value": 2 } ], "versions": [ { "id": "a", "version": 1 }, { "id": "b", "version": 1 } ] }
Reveal the worked solution and reasoning
function solve(input) {
const byId = new Map();
for (const record of [...input.records, ...input.events]) {
const old = byId.get(record.id);
if (!old || record.version > old.version) byId.set(record.id, { ...record });
}
const ordered = [...byId.values()].sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
return {
live: ordered.filter(item => item.value !== null),
versions: ordered.map(item => ({ id: item.id, version: item.version }))
};
}Version comparison makes duplicate delivery harmless within this contract.
Keeping deletion versions prevents older events from undoing a deletion.
The server must provide meaningful versions; this kata cannot manufacture ordering guarantees for a real distributed system.
Verify it in a real Next.js application
Next.js application lab
Observe cancellation first, then implement a versioned event feed
Open the local application route /stream after starting the workbench. Follow the experiment and collect the evidence described below.
Make the change
- Run /stream and inspect its EventSource consumer. The existing endpoint emits deterministic text tokens and a done event; it does not broadcast catalogue mutations or provide a resumable change log.
- Start, stop and restart the stream. Trace the active generation counter and cleanup that prevent an old connection from appending into a new run.
- Compare the existing /session flow: sign out in another tab and press Refresh server snapshot. This is an explicit manual reconciliation path, not automatic cross-tab session broadcasting.
- Implementation extension: publish ordered catalogue change events with entity IDs, monotonically meaningful versions and deletion tombstones; feed them into a version-aware client cache.
- Implementation extension: mutate data in another tab, test duplicate and reordered delivery, and add reconnection with a documented resume or snapshot policy. The current endpoint does not implement Last-Event-ID replay.
- Implementation extension: partition private cache entries by identity and clear or invalidate them on logout. Prevent delayed responses from an old identity from repopulating the next session.
Check the behavior
- The shipped stream can complete or stop, and stale-generation callbacks do not modify the current output.
- The shipped manual session refresh receives a new server-authoritative DTO after another tab changes the cookie.
- In the versioned-feed extension, older and duplicate events cannot overwrite newer entities, and delayed pre-deletion events cannot resurrect a tombstoned item.
- In the private-cache extension, identity changes clear or partition data and obsolete responses are discarded.
- Reconnect recovery and catalogue broadcasting are reported as implemented only after the added server/client protocol has been exercised.
Review the application reasoning
The runner tests merge semantics. The working lab establishes actual SSE transport and a separate manual session-refresh example. A real live-catalogue synchronization claim requires the additional event producer, ordering contract and cache consumer.
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.
01Why can the server show new data while a client widget still shows old data?
They may read from different caches. Server invalidation can refresh the server-rendered view while the widget still uses a browser query entry that has not been updated or refetched.
I identify the owner of each visible value, then coordinate the relevant tag, query key and route refresh. I avoid assuming one API updates every cache layer.
Follow-up questions
- What should the mutation response contain?
- When would you eliminate one of the duplicate owners?
- revalidateTagOfficial documentation
- updateTagOfficial documentation
- TanStack Query advanced server renderingOfficial documentation
02What belongs in a query key?
Every input that changes the result belongs in its identity, such as tenant, resource ID, search term, sort order and page. Inputs should be normalized consistently so equivalent queries do not fragment the cache.
I also ensure private caches are isolated or reset across account changes. The key is part of correctness and privacy, not just a performance optimization.
Follow-up questions
- Should a raw access token be a key value?
- How do you handle an empty filter?
- TanStack Query advanced server renderingOfficial documentation
- Authentication with Cache ComponentsOfficial documentation
03How do you prevent stale events from undoing newer data?
I compare a reliable event or entity version before applying it and ignore duplicates or older versions. Deletions retain a tombstone or watermark so an older update cannot recreate the record.
The version scope must be defined by the server protocol. A local receive timestamp does not prove which write happened later.
Follow-up questions
- What if versions are only ordered per entity?
- How long must tombstones be retained?
- HTML server-sent events standardOfficial documentation
04When would polling be preferable to a stream?
When update frequency and acceptable staleness permit it, polling has a simple request lifecycle and can be easier to operate. Focus/reconnect refresh may be enough for an intermittently used page.
I choose a stream when low-latency delivery materially improves the product and I can support reconnection, authorization and cleanup. Transport complexity should buy a specific user benefit.
Follow-up questions
- How would you stop hidden-tab polling?
- What data must refresh immediately after a write?
- SWR automatic revalidationOfficial documentation
- HTML server-sent events standardOfficial 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
- TanStack Query advanced server renderingOfficial documentation
- SWR automatic revalidationOfficial documentation
- HTML server-sent events standardOfficial documentation
- revalidateTagOfficial documentation
- updateTagOfficial documentation
- Authentication with Cache ComponentsOfficial documentation