Skip to article content
LESSON 24 / 28

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

lib/catalog-key.ts
export function catalogKey(tenantId: string, query: string, page: number) {
  return ["catalog", tenantId, query.trim(), page] as const;
}

Server execution

lib/server-query-client.ts
import "server-only";
import { QueryClient } from "@tanstack/react-query";
export function createRequestQueryClient() {
  return new QueryClient({ defaultOptions: { queries: { staleTime: 30_000 } } });
}

PAUSE AND PREDICT

updateTag refreshes server data, but a client query widget still shows the old value. What should you inspect?

Choose one answer, then check your reasoning.

This check does not mark the lesson as solved.

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.

PAUSE AND PREDICT

A deletion at version 5 is followed by an old update at version 4. How should the client avoid resurrection?

Choose one answer, then check your reasoning.

This check does not mark the lesson as solved.

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.

  1. Input is {records,events}; each entry has {id,version,value}, and value=null means deleted.
  2. 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.
  3. 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.

Ready when you are. Try the exercise before opening the worked solution.
Inspect 3 test cases
  1. 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
        }
      ]
    }
  2. 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
        }
      ]
    }
  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
solution.js
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

  1. 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.
  2. Start, stop and restart the stream. Trace the active generation counter and cleanup that prevent an old connection from appending into a new run.
  3. 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.
  4. Implementation extension: publish ordered catalogue change events with entity IDs, monotonically meaningful versions and deletion tombstones; feed them into a version-aware client cache.
  5. 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.
  6. 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.

Terminal
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:e2e

Open 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.

  1. 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?
  2. 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?
  3. 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?
  4. 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?

Check your understanding

Answer these without reopening the worked examples. The feedback explains the reasoning and the misconception behind each choice.

FINAL KNOWLEDGE CHECK

A browser query cache contains tenant A data when the user switches to tenant B. Which design is correct?

Choose one answer, then check your reasoning.

This check does not mark the lesson as solved.

Your checkpoint

Mark what you can do independently

Loading your local progress.

Sources and further reading

© 2026 FrontendX. All rights reserved.