ArchitectureIntermediate

State & Caching Decisions: Server vs Client State

DeveloperHat Team
16 min read

TL;DR

Where state lives decides latency, consistency and cost. Server vs client state, Redis cache patterns and invalidation — the decision, with its costs.

Every read your application serves is a state decision, whether anyone on the team made it deliberately or not. The moment a value is computed, fetched, or typed into a form, it lives somewhere — in the browser, on an edge node, in one server's memory, in a shared cache, or in the database — and where it lives decides three things at once: how fast the next read is, how stale it is allowed to be, and what happens when the process holding it dies. Most caching bugs are not performance problems. They are ownership problems: two layers both believed they owned the same fact, and they disagreed.

This article makes the decision explicit. It covers the five places state can live, the server-state versus client-state split that decides your frontend data layer, the Redis cache patterns that carry the shared layer, and invalidation — the part everyone postpones until a user sees someone else's data. The short version up front: keep UI state in the browser, treat server data in the browser as a cache with a freshness policy, put shared hot data in Redis behind a TTL and a versioned key, and let the database stay the only source of truth. Everything else is a variation on that sentence.

Client request Application checks cache first Cache hit → return fast Database miss → read + fill Cache-aside, step by step The application owns the pattern: read the cache, fall back to the database, fill the cache. Most reads end at the cache; the database only sees misses and writes.

The five places state can live

State is not one thing. It is five layers stacked on top of each other, and a request stops at the first layer that holds a fresh answer. The layers differ in who can see them, how long they live, and what clears them — and confusing two layers is the most reliable way to ship a stale-data bug.

Five places state can live — every layer is a cache with a different owner Browser / client state — UI state, TanStack Query cache, one user at a time Edge / CDN — static assets and cached responses, closest to the reader App server memory — request memoization, in-process cache, dies with the instance Shared cache — Redis, the one layer every instance can agree on Database of record — the only layer that is allowed to be the truth Every layer above the database is a copy — and every copy needs an expiry or an invalidation story.

Browser and client state is owned by one user and dies with the tab. Form input, the selected tab, whether a panel is open — the browser is the source of truth, and nothing else needs to know. Its lifetime is the session, and its invalidation story is trivial: it disappears on its own.

The edge and CDN hold static assets and cacheable responses close to the reader. A CDN cache is shared across users but blind to who is asking, which is why it is right for public content and wrong for anything personalized. Its invalidation is a purge or a TTL, and a purge that does not propagate is a stale page served worldwide.

App server memory holds request memoization and in-process caches. It is fast and free, and it dies with the instance — which means it is also wrong the moment you run two instances. Two servers with two in-process caches are two different truths, and a load balancer will happily serve both. Use it for per-request deduplication, never for anything that must agree across instances.

The shared cache is the layer every instance can agree on, and in practice that means Redis. Redis 8.12.0 shipped on 22 November 2026, with 8.10.3 as the previous stable line — check the Redis version table before trusting any older claim. A shared cache is the only cache that survives a deploy, a restart, and a scale-out, which is exactly why its invalidation story has to be designed rather than assumed.

The database of record is the only layer allowed to be the truth. Everything above it is a copy, and every copy is a promise to expire or invalidate. If a layer cannot say when its copy stops being valid, it is not a cache — it is a second database that nobody maintains.

Server state vs client state: the split that decides your frontend

The most consequential version of this decision lives in the frontend, and it is the one teams get wrong most often. Client state is data your app fully owns: the sidebar is open, the form has three characters typed, dark mode is on. You are the only writer, and when you set it, it is correct. Server state is different in every way that matters: it lives in a database you do not control, it can change without you, it is shared across your whole app, and reading it is asynchronous and can fail. The instant you read it, it might already be out of date.

Treating server data as ordinary component state forces you to hand-build caching, deduplication, retries, and refetching in every component — and most teams get it partially wrong. The honest fix is to treat server data in the browser as what it is: a cache. TanStack Query v5 is built on exactly that premise. A query key names the entry, staleTime says how long the entry counts as fresh before a background refetch is allowed, and gcTime says how long an inactive entry is kept before it is garbage-collected. Invalidation is explicit: a mutation calls invalidateQueries for the affected keys, and every subscriber refetches. The library handles the lifecycle; your job is the keys and the freshness policy.

// TanStack Query v5: server data is a cache, so give it a freshness policy.
// staleTime: fresh for 60s, no background refetch. gcTime: keep 5 minutes after unmount.
import { QueryClient, useQuery, useMutation, useQueryClient } from '@tanstack/react-query';

export const queryClient = new QueryClient({
  defaultOptions: {
    queries: { staleTime: 60_000, gcTime: 300_000, retry: 2 },
  },
});

function useProduct(id: string) {
  return useQuery({
    queryKey: ['product', id],
    queryFn: () => fetch(`/api/products/${id}`).then((r) => r.json()),
  });
}

function useUpdateProduct() {
  const client = useQueryClient();
  return useMutation({
    mutationFn: (p: { id: string; price: number }) =>
      fetch(`/api/products/${p.id}`, { method: 'PATCH', body: JSON.stringify(p) }),
    // The write invalidates the read. Without this line, the UI shows the old price.
    onSettled: (_data, _err, vars) => client.invalidateQueries({ queryKey: ['product', vars.id] }),
  });
}

The same split exists on the server. Next.js App Router has four caching layers with different lifetimes — request memoization for one render pass, the Data Cache that persists fetch results across requests and deployments, the Full Route Cache for rendered HTML, and the Router Cache on the client — and the framework's own caching guide is the primary source for how they interact. Two facts from it matter most: in Next.js 15, fetch() is no longer cached by default — you opt in with next: { revalidate: N } — and cached data is revalidated either by time or on demand, with revalidateTag and revalidatePath letting a mutation clear exactly the entries it affects. Cleartechy itself runs on this stack, and the same rules apply: a page that never revalidates is a page that never updates.

The rule that ties both halves together: server state gets a cache library or a framework cache with an explicit freshness and invalidation policy; client state gets useState or a light store. Mixing them — mirroring server data into a Zustand or Redux store — creates two copies that diverge after the first mutation, and the divergence is discovered by a user, not a test.

Redis cache patterns: who owns the write

On the server side, the shared cache needs a pattern, and the pattern decides who owns the write path. There are four, and the differences are about failure modes, not speed.

Cache-aside is the default and the one to reach for first. The application reads the cache, falls back to the database on a miss, and fills the cache itself. The database stays authoritative, the cache is a pure optimization, and a cache failure degrades to slow reads rather than wrong ones. Its cost is the miss path: the application owns the fill logic, and a hot key expiring under load can stampede the database.

// Cache-aside in Node with node-redis: the application owns the fill.
// A miss reads the database, then fills the cache with a TTL — never without one.
import { createClient } from 'redis';

const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();

async function getProduct(id: string) {
  const key = `product:${id}`;
  const cached = await redis.get(key);
  if (cached) return JSON.parse(cached);

  const product = await db.products.findById(id); // database of record
  if (product) await redis.set(key, JSON.stringify(product), { EX: 300 }); // 5-minute TTL
  return product;
}

Read-through moves the fill into the cache layer itself, so the application never sees a miss. It is simpler for callers and only worth it when the cache sits in front of the database as a managed tier. Write-through writes to the cache and the database together on every write, so reads never miss — at the price of write latency and a cache that must never lose a write. Write-behind acknowledges the write after the cache and flushes to the database asynchronously, which is the fastest write path and the riskiest: a cache crash before the flush is lost data. Unless the data is reconstructible or expendable, write-behind is a decision to trade durability for latency, and it should be named as one.

Spring Boot developers get the same patterns through the framework's cache abstraction rather than handwritten calls — @Cacheable for the read path, @CacheEvict for the invalidation — with Redis as the backing store. The built-in version is worth using precisely because it keeps the pattern in one place instead of scattered across services:

// Spring Boot cache abstraction over Redis: the annotation IS the pattern.
// The read fills the cache; the write evicts it. Same cache-aside, no handwritten calls.
@Service
public class ProductService {

    @Cacheable(value = "products", key = "#id")
    public Product getProduct(String id) {
        return productRepository.findById(id).orElseThrow();
    }

    @CacheEvict(value = "products", key = "#product.id")
    public Product updatePrice(Product product) {
        return productRepository.save(product);
    }
}

For the full pattern catalogue and the trade-offs between them, our earlier guide to Redis caching patterns walks each one with its failure modes. The decision here is narrower: start with cache-aside, add write-through only when a read must never miss, and treat write-behind as a durability decision, not a performance tweak.

Invalidation: the part that actually breaks

There are only two hard problems in computer science, and this article is about both of them. Invalidation has four honest mechanisms, and a system that uses none of them is serving stale data on a schedule it did not choose.

TTL expiry is the simplest and the most underrated. Every entry gets a lifetime, and staleness is bounded by it. A five-minute TTL on a product page means the worst case is a five-minute-old price — a known, defensible bound. Set the TTL from the data's freshness requirement, not from a round number: prices get minutes, reference data gets hours, and anything without a TTL is a leak, not a cache.

Explicit invalidation deletes or updates the key when the underlying data changes. It is precise, and it is the mechanism most teams forget to wire up — the write path and the invalidation path live in different code, and the second one is the one that gets skipped under deadline pressure. The Spring example above puts the eviction on the same method as the write for exactly this reason: invalidation that lives next to the mutation gets maintained; invalidation in a separate service gets forgotten.

Versioned keys sidestep deletion entirely: the key includes a version (product:42:v3), and a write bumps the version instead of deleting the old entry. Readers never see a half-updated value, and the old entries expire by TTL. It costs one extra lookup for the current version, and it is the right answer when a delete racing a fill can re-cache stale data.

Stampede protection covers the moment a hot key expires and a hundred requests all miss at once. The fixes are a lock so only one request refills, request coalescing at the cache layer, or probabilistic early expiry so the refill happens before the stampede. Any one of them works; none of them happens by accident.

One more discipline: never cache by a key you cannot enumerate for invalidation. A cache key built from a user id, a filter, and a page number is three dimensions of entries that a single write cannot find. If you cannot name the keys a write affects, you cannot invalidate them, and your only honest options are a short TTL or no cache at all.

The recommendation

Decide by what the reader needs, not by which cache is fashionable What does the reader need? start from the need, not the tech A fresh answer, now the user is waiting Shared, stale is fine many users, same data One user, UI-only toggles, drafts, tabs No cache / read-through pay the read, stay correct Shared cache + TTL Redis, versioned keys Client state useState, query cache A cache you cannot invalidate is a stale-data bug with a deployment schedule attached.

OptionBest forLatencyFreshness guaranteeWhat it costs you
Client state (useState, query cache)UI state, one user's view of server dataInstantAlways current (client-owned)Per-tab only; lost on refresh unless persisted
Edge / CDN cachePublic, cacheable responsesVery lowTTL or purge onlyBlind to the user; wrong for personalized data
App server memoryPer-request deduplicationInstantDies with the instanceDiverges across instances; never shared truth
Shared cache (Redis)Hot shared reads, sessions, rate limits~1msTTL + explicit invalidationA service to run; invalidation discipline
Database of recordThe truth, and everything that must not be lostSlowestExactEvery read pays the full cost

The default architecture that follows from the table: UI state in the browser with useState or a light store; server data in the browser through TanStack Query with a stated staleTime and invalidation on mutation; shared hot data in Redis behind cache-aside with a TTL and versioned keys; and the database as the only source of truth. Add the edge layer for public content, and keep in-process caching to per-request memoization. That stack covers the vast majority of applications, and every deviation from it should be justified by a measured need rather than a fashionable tool.

Architecture Decision

>

Decision: Keep UI state in the browser, manage server data in the browser as a cache with a freshness policy (TanStack Query, 60-second staleTime), and put shared hot data in Redis behind cache-aside with a 5-minute TTL and versioned keys. The database remains the only source of truth.

>

Context: One product team owns a catalog-and-checkout service. Product pages are read thousands of times per write, prices change a few times a day, and the frontend is a Next.js App Router application with two server instances behind a load balancer. Stale prices have already caused two support incidents; the team is choosing between in-process caching, Redis, and no cache at all.

>

Options considered: (a) In-process caching per server instance — free and fast. (b) Redis behind cache-aside with TTL and versioned keys. (c) Write-through Redis so reads never miss. (d) No shared cache — read the database on every request and rely on the CDN for public pages.

>

Why this one: Option (a) gives two instances two different truths, and the load balancer serves both — it recreates the stale-price incident with better latency. Option (c) makes every write pay cache latency and still needs an invalidation story for the versioned keys. Option (d) is honest but slow: the database takes the full read load, and the CDN cannot serve personalized prices. Option (b) bounds staleness at five minutes, survives deploys and scale-out, and degrades to slow reads rather than wrong ones when Redis is down.

>

What it costs you: A Redis service to run and monitor — Redis 8.12 is the current line as of November 2026 — plus the discipline of versioned keys, a TTL on every entry, and invalidation wired next to every mutation. Debugging moves from stack traces to cache hit ratios and key distributions. A hot key expiring under load needs stampede protection, not hope.

>

When to reverse it: When the read-to-write ratio drops below roughly 10:1 — the cache is no longer earning its complexity, and the database can carry the load directly. When a single instance is enough for the foreseeable future — in-process caching becomes correct again, and Redis is overhead. When the data must never be stale even for a minute — then there is no cache, only the database, and the latency budget has to accept it. The reversal trigger is measured — hit ratio, staleness incidents, and read volume — not fashion.

When not to use each option

Do not use a shared cache when the data is per-user and the cache key cannot be enumerated for invalidation — a personalized feed cached by user id is a deletion problem, not a performance win, and a short TTL is the only honest fallback. Do not use in-process caching across instances for anything that must agree; two servers with two caches are two truths, and the user who hits the wrong one gets the wrong answer.

Do not use write-behind for data you cannot afford to lose. A cache crash before the flush is silent data loss, and the write that was acknowledged is gone. Do not cache without a TTL — an entry with no expiry is not a cache entry, it is a leak that grows until the cache evicts something you actually needed.

Do not put server data in a client store. The moment the server copy and the store copy diverge — and they will, after the first mutation that forgets to update both — the UI shows one thing and the database holds another, and the bug is discovered by a user. And do not cache to fix a slow query: a cache in front of a missing index is a faster way to serve the same bad plan, and the day the cache is cold the database falls over anyway.

The same reasoning applies to the surrounding architecture: how the frontend is rendered decides which cache layers even exist, as our guide to frontend architecture — SSR vs SSG vs islands vs SPA lays out, and how services talk to each other decides whether a stale read is a nuisance or an inconsistency, which is the question our event-driven vs request-driven decision works through.

What to do next

This week, audit by ownership before you audit by performance:

  • [ ] List every piece of state in one user flow and name its owner — browser, edge, server memory, shared cache, or database
  • [ ] Find every in-process cache running behind a load balancer with more than one instance, and decide whether its staleness is acceptable or it needs to move to Redis
  • [ ] Give every cache entry a TTL, and write down the worst-case staleness each TTL allows — if the number is indefensible, the TTL is wrong
  • [ ] Put the invalidation next to the mutation: every write path should name the keys it clears, in the same change as the write
  • [ ] Measure the hit ratio on your hottest key before adding a second cache layer — a cache that does not hit is overhead with a dashboard
  • Why This Matters

    Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.

    Trade-offs to Consider

    Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.

    When NOT to Use This

    Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.

    Decision Framework

    Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.

    Share this articleShare on XShare on LinkedIn

    Keep the decision frameworks coming

    One practical architecture guide a week — patterns, trade-offs, and when not to use them. No spam, unsubscribe anytime.